Range calendar

A month calendar for single dates or date ranges where selection feels continuous. In single mode a filled pill glides from the old day to the new one; in range mode the first click sets the start, hovering previews the band across the days in between and the second click sets the end. Months slide in the direction you move and today has a thin ring. A preset rail (Today, Last 7 days, This month, Next weekend or your own) sits beside the grid in wide containers and turns into chips above it in narrow ones, and a second month appears on its own when there is room. Supports min and max, a disabled(date) callback, per-day annotations such as dots or prices, any week start and Intl month and weekday names. Keyboard: arrows by day or week, PageUp/PageDown by month (Shift for a year), Home/End for the week, Enter to select; the range is also described in text.

Forms & inputsComponentTailwind v4

Source

import * as React from "react";
import { ChevronLeft, ChevronRight } from "lucide-react";
import { cn } from "@/lib/utils";

export type DateRange = { from: Date; to?: Date };
export type CalendarPreset = { label: string; range: () => DateRange };

type CommonProps = {
  defaultMonth?: Date;
  /** 0 = Sunday, 1 = Monday. */
  weekStart?: 0 | 1 | 2 | 3 | 4 | 5 | 6;
  min?: Date;
  max?: Date;
  disabled?: (date: Date) => boolean;
  /** Small content under a day's number: a dot, a price. */
  annotations?: (date: Date) => React.ReactNode;
  /** "auto" shows two months when the container is wide enough. */
  months?: "auto" | 1 | 2;
  locale?: string;
  className?: string;
  label?: string;
};
export type SingleCalendarProps = CommonProps & {
  mode?: "single";
  value?: Date | null;
  defaultValue?: Date | null;
  onChange?: (date: Date) => void;
  presets?: never;
};
export type RangeCalendarProps = CommonProps & {
  mode: "range";
  value?: DateRange | null;
  defaultValue?: DateRange | null;
  onChange?: (range: DateRange) => void;
  /** true for the built-in list, or your own. */
  presets?: boolean | CalendarPreset[];
};
export type CalendarProps = SingleCalendarProps | RangeCalendarProps;

/* ---------- date helpers (local time, day precision) ---------- */
const day = (date: Date) => new Date(date.getFullYear(), date.getMonth(), date.getDate());
const addDays = (date: Date, amount: number) => new Date(date.getFullYear(), date.getMonth(), date.getDate() + amount);
const monthStart = (date: Date) => new Date(date.getFullYear(), date.getMonth(), 1);
const addMonths = (date: Date, amount: number) => {
  const target = new Date(date.getFullYear(), date.getMonth() + amount, 1);
  const last = new Date(target.getFullYear(), target.getMonth() + 1, 0).getDate();
  return new Date(target.getFullYear(), target.getMonth(), Math.min(date.getDate(), last));
};
const same = (a?: Date | null, b?: Date | null) => !!a && !!b && a.getFullYear() === b.getFullYear() && a.getMonth() === b.getMonth() && a.getDate() === b.getDate();
const key = (date: Date) => `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;
const monthDiff = (a: Date, b: Date) => (b.getFullYear() - a.getFullYear()) * 12 + b.getMonth() - a.getMonth();

export const DEFAULT_PRESETS: CalendarPreset[] = [
  { label: "Today", range: () => ({ from: day(new Date()), to: day(new Date()) }) },
  { label: "Last 7 days", range: () => ({ from: addDays(day(new Date()), -6), to: day(new Date()) }) },
  {
    label: "This month",
    range: () => {
      const now = new Date();
      return { from: new Date(now.getFullYear(), now.getMonth(), 1), to: new Date(now.getFullYear(), now.getMonth() + 1, 0) };
    },
  },
  {
    label: "Next weekend",
    range: () => {
      const today = day(new Date());
      const saturday = addDays(today, ((6 - today.getDay() + 7) % 7) || 7);
      return { from: saturday, to: addDays(saturday, 1) };
    },
  },
];

const ring = "outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background";

function useWidth<T extends HTMLElement>() {
  const ref = React.useRef<T>(null);
  const [width, setWidth] = React.useState(0);
  React.useEffect(() => {
    const element = ref.current;
    if (!element) return;
    const observer = new ResizeObserver(([entry]) => setWidth(entry.contentRect.width));
    observer.observe(element);
    return () => observer.disconnect();
  }, []);
  return [ref, width] as const;
}

export function Calendar(props: CalendarProps) {
  const { weekStart = 1, min, max, disabled, annotations, months = "auto", locale, className, label = "Calendar" } = props;
  const range = props.mode === "range";
  const today = day(new Date());

  const [inner, setInner] = React.useState<Date | DateRange | null>(() => (props.defaultValue ?? null) as Date | DateRange | null);
  const controlled = props.value !== undefined;
  const value = (controlled ? props.value : inner) as Date | DateRange | null;
  const single = !range ? (value as Date | null) : null;
  const span = range ? (value as DateRange | null) : null;

  const initial = day(props.defaultMonth || (single ?? span?.from) || today);
  const [month, setMonth] = React.useState(() => monthStart(initial));
  const [focusDate, setFocusDate] = React.useState(initial);
  const [hover, setHover] = React.useState<Date | null>(null);
  const [direction, setDirection] = React.useState<"next" | "prev" | null>(null);
  const shouldFocus = React.useRef(false);
  const [rootRef, width] = useWidth<HTMLDivElement>();
  const id = React.useId();

  const presets = range ? (props.presets === true ? DEFAULT_PRESETS : props.presets || []) : [];
  const railSide = presets.length > 0 && width >= 576;
  const count = months === "auto" ? (width >= (railSide ? 800 : 620) ? 2 : 1) : months;

  const isDisabled = React.useCallback(
    (date: Date) => (!!min && date < day(min)) || (!!max && date > day(max)) || !!disabled?.(date),
    [min, max, disabled],
  );

  const commit = (next: Date | DateRange) => {
    if (!controlled) setInner(next);
    if (range) (props.onChange as ((r: DateRange) => void) | undefined)?.(next as DateRange);
    else (props.onChange as ((d: Date) => void) | undefined)?.(next as Date);
  };

  const select = (date: Date) => {
    if (isDisabled(date)) return;
    if (!range) return commit(date);
    if (!span || span.to || !span.from) {
      setHover(null);
      return commit({ from: date });
    }
    setHover(null);
    commit(date < span.from ? { from: date, to: span.from } : { from: span.from, to: date });
  };

  const show = (target: Date, dir?: "next" | "prev") => {
    setDirection(dir || (target > month ? "next" : "prev"));
    setMonth(monthStart(target));
  };

  /* Keep the focused day inside the visible months, shifting by the smallest step. */
  const moveFocus = (target: Date) => {
    let next = target;
    if (min && next < day(min)) next = day(min);
    if (max && next > day(max)) next = day(max);
    const offset = monthDiff(month, next);
    if (offset < 0) show(monthStart(next), "prev");
    else if (offset >= count) show(addMonths(monthStart(next), -(count - 1)), "next");
    setFocusDate(next);
    shouldFocus.current = true;
  };

  React.useEffect(() => {
    if (!shouldFocus.current) return;
    shouldFocus.current = false;
    rootRef.current?.querySelector<HTMLButtonElement>(`[data-day="${key(focusDate)}"]`)?.focus();
  });

  const onKey = (event: React.KeyboardEvent, date: Date) => {
    const weekday = (date.getDay() - weekStart + 7) % 7;
    const moves: Record<string, () => Date> = {
      ArrowLeft: () => addDays(date, -1),
      ArrowRight: () => addDays(date, 1),
      ArrowUp: () => addDays(date, -7),
      ArrowDown: () => addDays(date, 7),
      Home: () => addDays(date, -weekday),
      End: () => addDays(date, 6 - weekday),
      PageUp: () => addMonths(date, event.shiftKey ? -12 : -1),
      PageDown: () => addMonths(date, event.shiftKey ? 12 : 1),
    };
    if (moves[event.key]) {
      event.preventDefault();
      const target = moves[event.key]();
      moveFocus(target);
      if (range && span?.from && !span.to) setHover(target);
      return;
    }
    if (event.key === "Enter" || event.key === " ") {
      event.preventDefault();
      select(date);
    }
  };

  const navigate = (amount: number) => {
    show(addMonths(month, amount), amount > 0 ? "next" : "prev");
    const target = addMonths(focusDate, amount);
    setFocusDate(target);
  };

  /* Keep focusDate visible when the month count changes with the container. */
  React.useEffect(() => {
    const offset = monthDiff(month, focusDate);
    if (offset < 0 || offset >= count) setFocusDate(month);
  }, [count, month, focusDate]);

  const monthName = (date: Date) => new Intl.DateTimeFormat(locale, { month: "long", year: "numeric" }).format(date);
  const longDate = (date: Date) => new Intl.DateTimeFormat(locale, { weekday: "long", day: "numeric", month: "long", year: "numeric" }).format(date);
  const shortDate = (date: Date) => new Intl.DateTimeFormat(locale, { day: "numeric", month: "short" }).format(date);
  const weekdays = Array.from({ length: 7 }, (_, index) => addDays(new Date(2024, 0, 7 + weekStart), index)); // 7 Jan 2024 is a Sunday

  const bandEnd = span?.to || (span?.from && hover ? hover : null);
  const lo = span?.from && bandEnd ? (bandEnd < span.from ? bandEnd : span.from) : span?.from || null;
  const hi = span?.from && bandEnd ? (bandEnd < span.from ? span.from : bandEnd) : span?.from || null;
  const previewing = range && !!span?.from && !span.to;

  const activePreset = presets.find((preset) => {
    const r = preset.range();
    return span?.to && same(r.from, span.from) && same(r.to, span.to);
  });

  const nights = span?.from && span.to ? Math.round((day(span.to).getTime() - day(span.from).getTime()) / 86_400_000) + 1 : 0;
  const description = !range
    ? ""
    : !span?.from
      ? "Choose a start date"
      : !span.to
        ? `From ${shortDate(span.from)} · choose an end date`
        : `${shortDate(span.from)} – ${shortDate(span.to)} · ${nights} ${nights === 1 ? "day" : "days"}`;

  const cellHeight = annotations ? "h-[3.25rem]" : "h-10";

  const renderMonth = (offset: number) => {
    const first = addMonths(month, offset);
    const lead = (first.getDay() - weekStart + 7) % 7;
    const length = new Date(first.getFullYear(), first.getMonth() + 1, 0).getDate();
    const cells: (Date | null)[] = [
      ...Array.from({ length: lead }, () => null),
      ...Array.from({ length }, (_, index) => new Date(first.getFullYear(), first.getMonth(), index + 1)),
    ];
    while (cells.length % 7) cells.push(null);
    const weeks = Array.from({ length: cells.length / 7 }, (_, index) => cells.slice(index * 7, index * 7 + 7));
    const headingId = `${id}-m${offset}`;
    const pillIndex = single && single.getMonth() === first.getMonth() && single.getFullYear() === first.getFullYear() ? lead + single.getDate() - 1 : -1;

    return (
      <div key={offset} className="w-[18rem] max-w-full shrink-0">
        <div className="mb-2 flex h-9 items-center justify-between">
          {offset === 0 ? (
            <button type="button" onClick={() => navigate(-1)} aria-label="Previous month" disabled={!!min && monthStart(first) <= monthStart(min)} className={cn("grid size-8 place-items-center rounded-md text-muted-foreground hover:bg-accent hover:text-foreground disabled:opacity-30", ring)}>
              <ChevronLeft className="size-4" aria-hidden="true" />
            </button>
          ) : <span className="size-8" />}
          <h3 id={headingId} aria-live="polite" className="text-sm font-semibold">{monthName(first)}</h3>
          {offset === count - 1 ? (
            <button type="button" onClick={() => navigate(1)} aria-label="Next month" disabled={!!max && monthStart(first) >= monthStart(max)} className={cn("grid size-8 place-items-center rounded-md text-muted-foreground hover:bg-accent hover:text-foreground disabled:opacity-30", ring)}>
              <ChevronRight className="size-4" aria-hidden="true" />
            </button>
          ) : <span className="size-8" />}
        </div>
        <div className="overflow-hidden">
          <div
            key={key(first)}
            role="grid"
            aria-labelledby={headingId}
            aria-multiselectable={range || undefined}
            className={cn(direction === "next" && "motion-safe:animate-[chm-rc-next_.26s_ease-out]", direction === "prev" && "motion-safe:animate-[chm-rc-prev_.26s_ease-out]")}
            onMouseLeave={() => previewing && setHover(null)}
          >
            <div role="row" className="grid grid-cols-7">
              {weekdays.map((weekday) => (
                <div key={weekday.getDay()} role="columnheader" aria-label={new Intl.DateTimeFormat(locale, { weekday: "long" }).format(weekday)} className="pb-1.5 text-center text-[11px] font-medium text-muted-foreground">
                  {new Intl.DateTimeFormat(locale, { weekday: "short" }).format(weekday).slice(0, 2)}
                </div>
              ))}
            </div>
            <div className="relative">
              {!range && (
                <span
                  aria-hidden="true"
                  className={cn(
                    "pointer-events-none absolute left-0 top-0 flex w-[calc(100%/7)] justify-center motion-safe:transition-[transform,opacity] motion-safe:duration-300 motion-safe:ease-[cubic-bezier(.3,1.3,.5,1)]",
                    cellHeight,
                    pillIndex < 0 && "opacity-0",
                  )}
                  style={{ transform: `translate(${(Math.max(pillIndex, 0) % 7) * 100}%, ${Math.floor(Math.max(pillIndex, 0) / 7) * 100}%)` }}
                >
                  <span className="mt-0.5 size-9 rounded-full bg-primary shadow-sm" />
                </span>
              )}
              {weeks.map((week, row) => {
                const firstDay = week.find(Boolean)!;
                return (
                  <div key={row} role="row" aria-label={`Week of ${shortDate(firstDay)}`} className="grid grid-cols-7">
                    {week.map((date, col) => {
                      if (!date) return <div key={col} role="gridcell" className={cellHeight} />;
                      const off = isDisabled(date);
                      const isToday = same(date, today);
                      const chosen = range ? same(date, span?.from) || same(date, span?.to) : same(date, single);
                      const inBand = range && lo && hi && date >= lo && date <= hi;
                      const isLo = same(date, lo);
                      const isHi = same(date, hi);
                      const hoverEnd = previewing && same(date, hover) && !same(date, span?.from);
                      const lastOfMonth = date.getDate() === length;
                      const roundL = col === 0 || date.getDate() === 1;
                      const roundR = col === 6 || lastOfMonth;
                      const note = annotations?.(date);
                      return (
                        <div key={col} role="gridcell" aria-selected={chosen || !!(range && span?.to && inBand)} className={cn("relative", cellHeight)}>
                          {inBand && !(isLo && isHi) && (
                            <span
                              aria-hidden="true"
                              className={cn(
                                "absolute top-0.5 h-9",
                                previewing ? "bg-primary/[0.07]" : "bg-primary/12",
                                isLo ? "left-1/2" : roundL ? "left-1 rounded-l-full" : "left-0",
                                isHi ? "right-1/2" : roundR ? "right-1 rounded-r-full" : "right-0",
                              )}
                            />
                          )}
                          <button
                            type="button"
                            data-day={key(date)}
                            tabIndex={same(date, focusDate) ? 0 : -1}
                            aria-label={`${longDate(date)}${isToday ? ", today" : ""}${range && same(date, span?.from) ? ", start" : ""}${range && same(date, span?.to) ? ", end" : ""}`}
                            aria-disabled={off || undefined}
                            aria-current={isToday ? "date" : undefined}
                            onClick={() => {
                              setFocusDate(date);
                              select(date);
                            }}
                            onKeyDown={(event) => onKey(event, date)}
                            onMouseEnter={() => previewing && !off && setHover(date)}
                            onFocus={() => setFocusDate(date)}
                            className={cn("group relative flex size-full flex-col items-center rounded-full", ring, off && "cursor-not-allowed")}
                          >
                            <span
                              className={cn(
                                "mt-0.5 grid size-9 place-items-center rounded-full text-sm tabular-nums transition-colors duration-200",
                                !chosen && !off && "group-hover:bg-accent",
                                isToday && !chosen && "ring-1 ring-inset ring-foreground/35",
                                chosen && "font-semibold text-primary-foreground",
                                chosen && range && "bg-primary shadow-sm",
                                hoverEnd && "ring-2 ring-inset ring-primary/60",
                                off && "text-muted-foreground/45 line-through decoration-muted-foreground/40",
                              )}
                            >
                              {date.getDate()}
                            </span>
                            {note != null && note !== false && (
                              <span className={cn("relative -mt-0.5 text-[10px] leading-none tabular-nums text-muted-foreground", off && "opacity-0")}>{note}</span>
                            )}
                          </button>
                        </div>
                      );
                    })}
                  </div>
                );
              })}
            </div>
          </div>
        </div>
      </div>
    );
  };

  return (
    <div ref={rootRef} className={cn("@container w-full", className)} role="group" aria-label={label}>
      <style href="chm-range-calendar" precedence="default">{`@keyframes chm-rc-next{from{opacity:0;transform:translateX(18px)}to{opacity:1;transform:none}}@keyframes chm-rc-prev{from{opacity:0;transform:translateX(-18px)}to{opacity:1;transform:none}}`}</style>
      <div className="flex flex-col gap-4 @xl:flex-row @xl:gap-5">
        {presets.length > 0 && (
          <div
            role="group"
            aria-label="Presets"
            className={cn(
              "-mx-1 flex gap-1.5 overflow-x-auto px-1 pb-1 [scrollbar-width:none]",
              railSide && "mx-0 w-40 shrink-0 flex-col gap-0.5 overflow-visible border-r border-border px-0 pb-0 pr-3",
            )}
          >
            {presets.map((preset) => {
              const active = preset === activePreset;
              return (
                <button
                  key={preset.label}
                  type="button"
                  aria-pressed={active}
                  onClick={() => {
                    const next = preset.range();
                    setHover(null);
                    commit(next);
                    const offset = monthDiff(month, next.from);
                    if (offset < 0 || offset >= count) show(next.from);
                    setFocusDate(day(next.from));
                  }}
                  className={cn(
                    "shrink-0 whitespace-nowrap text-sm transition-colors",
                    railSide ? "rounded-md px-2.5 py-1.5 text-left" : "rounded-full border border-border px-3 py-1",
                    active ? (railSide ? "bg-accent font-medium text-foreground" : "border-primary bg-primary text-primary-foreground") : "text-muted-foreground hover:bg-accent hover:text-foreground",
                    ring,
                  )}
                >
                  {preset.label}
                </button>
              );
            })}
          </div>
        )}
        <div className={cn("min-w-0", !railSide && "mx-auto")}>
          <div className="flex flex-wrap justify-center gap-8">{Array.from({ length: count }, (_, index) => renderMonth(index))}</div>
          {range && (
            <p aria-live="polite" className="mt-3 border-t border-border pt-3 text-center text-[13px] text-muted-foreground @xl:text-left">
              {description}
            </p>
          )}
        </div>
      </div>
    </div>
  );
}

export { Calendar as RangeCalendar };