# Calendar

A board of date tiles. Pick one day or a range; marked days get a dot. Full keyboard support and no date library.

Docs: https://cozy-ui.solo.engineer/docs/components/calendar/

Install: `npx shadcn@latest add @cozy/calendar`

### Usage

```tsx
import { Calendar } from "@/components/ui/calendar"

const [day, setDay] = useState<Date>()
<Calendar mode="single" selected={day} onSelect={setDay} />
```

### Props

| Prop | Type | Default | Description |
|---|---|---|---|
| mode | `"single" \| "range"` | `"single"` | One day, or a from–to range. |
| selected | `Date \| { from?: Date; to?: Date }` | – | The picked day or range (controlled). |
| onSelect | `(value) => void` | – | Called with the new day (or undefined when unpicked), or the new range. |
| disabled | `(day: Date) => boolean` | – | Return true to disable a day, e.g. past days or Sundays. |
| marked | `Date[]` | – | Days that get a small dot: events, market days, harvests. |
| month / defaultMonth / onMonthChange | `Date` | `selected or today` | The month shown. |
| weekStartsOn | `0 \| 1` | `1` | Sunday or Monday. |
| locale | `string` | `browser` | BCP 47 locale for month and weekday names, e.g. "vi-VN". |

Keyboard: arrows move a day or a week, Home and End go to the week's start and end, PageUp and PageDown change the month (with Shift, the year), Enter or Space picks.

Uses the native Date in local time; bring your own date library only for formatting if you like.

### Example

```tsx
import { useState } from "react";
import { Calendar } from "@/components/ui/calendar";

export default function CalendarDemo() {
  const [day, setDay] = useState<Date | undefined>(() => new Date());
  const t = new Date();
  // market days: every 5th day of the month, like a village market
  const market = [5, 10, 15, 20, 25, 30].map((d) => new Date(t.getFullYear(), t.getMonth(), d));
  return (
    <div className="grid justify-items-center gap-3">
      <Calendar mode="single" selected={day} onSelect={setDay} marked={market} aria-label="Pick a day" />
      <p className="m-0 text-sm text-text-muted" aria-live="polite">
        {day ? `Picked ${day.toLocaleDateString(undefined, { weekday: "long", day: "numeric", month: "long" })}` : "No day picked"} · dots are market days
      </p>
    </div>
  );
}
```

### Source (components/ui/calendar.tsx)

```tsx
import * as React from "react";
import { cn } from "@/lib/utils";
import { ChevronGlyph } from "@/components/ui/glyphs";

/* A month of chunky date tiles. No date library: plain Date in local time.
   Keyboard: arrows move a day/week, Home/End the week, PageUp/PageDown the month
   (with Shift: the year), Enter or Space selects. */

export type DateRange = { from?: Date; to?: Date };

type Common = {
  /** Month shown (controlled). */
  month?: Date;
  defaultMonth?: Date;
  onMonthChange?: (month: Date) => void;
  /** Return true to disable a day. */
  disabled?: (day: Date) => boolean;
  /** Dates with a small marker under the number, e.g. harvest days. */
  marked?: Date[];
  /** 0 = Sunday, 1 = Monday. Default 1. */
  weekStartsOn?: 0 | 1;
  /** BCP 47 locale for month and weekday names. Default: the browser's. */
  locale?: string;
  className?: string;
  "aria-label"?: string;
};
type SingleProps = Common & { mode?: "single"; selected?: Date; onSelect?: (day: Date | undefined) => void };
type RangeProps = Common & { mode: "range"; selected?: DateRange; onSelect?: (range: DateRange) => void };
export type CalendarProps = SingleProps | RangeProps;

const day0 = (d: Date) => new Date(d.getFullYear(), d.getMonth(), d.getDate());
const same = (a?: Date, b?: Date) => !!a && !!b && a.getFullYear() === b.getFullYear() && a.getMonth() === b.getMonth() && a.getDate() === b.getDate();
const addDays = (d: Date, n: number) => new Date(d.getFullYear(), d.getMonth(), d.getDate() + n);
const addMonths = (d: Date, n: number) => {
  const t = new Date(d.getFullYear(), d.getMonth() + n, 1);
  return new Date(t.getFullYear(), t.getMonth(), Math.min(d.getDate(), new Date(t.getFullYear(), t.getMonth() + 1, 0).getDate()));
};
const key = (d: Date) => `${d.getFullYear()}-${d.getMonth()}-${d.getDate()}`;

function Calendar(props: CalendarProps) {
  const { month: monthProp, defaultMonth, onMonthChange, disabled, marked, weekStartsOn = 1, locale, className } = props;
  const today = React.useMemo(() => day0(new Date()), []);
  const initial = monthProp ?? defaultMonth ?? (props.mode === "range" ? props.selected?.from : props.selected) ?? today;
  const [monthState, setMonthState] = React.useState(() => new Date(initial.getFullYear(), initial.getMonth(), 1));
  const month = monthProp ? new Date(monthProp.getFullYear(), monthProp.getMonth(), 1) : monthState;
  const [focus, setFocus] = React.useState<Date>(() => day0(initial));
  const [hover, setHover] = React.useState<Date | undefined>();
  const grid = React.useRef<HTMLDivElement>(null);
  const wantFocus = React.useRef(false);
  const titleId = React.useId();

  const setMonth = (m: Date) => {
    const first = new Date(m.getFullYear(), m.getMonth(), 1);
    if (!monthProp) setMonthState(first);
    onMonthChange?.(first);
  };
  const moveFocus = (d: Date) => {
    setFocus(d);
    if (d.getMonth() !== month.getMonth() || d.getFullYear() !== month.getFullYear()) setMonth(d);
    wantFocus.current = true;
  };
  React.useEffect(() => {
    if (!wantFocus.current) return;
    wantFocus.current = false;
    grid.current?.querySelector<HTMLButtonElement>(`[data-day="${key(focus)}"]`)?.focus();
  });

  const fmtMonth = new Intl.DateTimeFormat(locale, { month: "long", year: "numeric" });
  const fmtDay = new Intl.DateTimeFormat(locale, { weekday: "long", day: "numeric", month: "long", year: "numeric" });
  const fmtWeekday = new Intl.DateTimeFormat(locale, { weekday: "short" });
  const fmtWeekdayLong = new Intl.DateTimeFormat(locale, { weekday: "long" });

  const start = addDays(month, -((month.getDay() - weekStartsOn + 7) % 7));
  const days = Array.from({ length: 42 }, (_, i) => addDays(start, i));
  const weeks = Array.from({ length: 6 }, (_, w) => days.slice(w * 7, w * 7 + 7));
  const weekdays = days.slice(0, 7);
  const markedKeys = React.useMemo(() => new Set((marked ?? []).map((d) => key(d))), [marked]);
  // keep the roving tab stop inside the shown month
  const tabDay = focus.getMonth() === month.getMonth() && focus.getFullYear() === month.getFullYear() ? focus : month;

  const range = props.mode === "range" ? props.selected ?? {} : undefined;
  const previewTo = range?.from && !range.to ? hover : undefined;
  const inRange = (d: Date) => {
    if (!range?.from) return false;
    const end = range.to ?? previewTo;
    if (!end) return false;
    const [a, b] = range.from <= end ? [range.from, end] : [end, range.from];
    return d > a && d < b;
  };

  const choose = (d: Date) => {
    if (disabled?.(d)) return;
    setFocus(d);
    if (props.mode === "range") {
      const r = props.selected ?? {};
      if (!r.from || r.to) props.onSelect?.({ from: d, to: undefined });
      else if (same(d, r.from)) props.onSelect?.({ from: undefined, to: undefined });
      else props.onSelect?.(d < r.from ? { from: d, to: r.from } : { from: r.from, to: d });
    } else {
      props.onSelect?.(same(d, props.selected) ? undefined : d);
    }
    if (d.getMonth() !== month.getMonth()) setMonth(d);
  };

  const onKeyDown = (e: React.KeyboardEvent) => {
    const d = focus;
    const dow = (d.getDay() - weekStartsOn + 7) % 7;
    const map: Record<string, () => Date> = {
      ArrowLeft: () => addDays(d, -1),
      ArrowRight: () => addDays(d, 1),
      ArrowUp: () => addDays(d, -7),
      ArrowDown: () => addDays(d, 7),
      Home: () => addDays(d, -dow),
      End: () => addDays(d, 6 - dow),
      PageUp: () => addMonths(d, e.shiftKey ? -12 : -1),
      PageDown: () => addMonths(d, e.shiftKey ? 12 : 1),
    };
    if (map[e.key]) { e.preventDefault(); moveFocus(map[e.key]()); }
    else if (e.key === "Enter" || e.key === " ") { e.preventDefault(); choose(d); }
  };

  return (
    <div className={cn("cz-calendar", className)} data-mode={props.mode ?? "single"}>
      <div className="cz-calendar__head">
        <button type="button" className="cz-calendar__nav" aria-label="Previous month" onClick={() => setMonth(addMonths(month, -1))}>
          <ChevronGlyph style={{ rotate: "180deg" }} />
        </button>
        <div id={titleId} className="cz-calendar__title" aria-live="polite">{fmtMonth.format(month)}</div>
        <button type="button" className="cz-calendar__nav" aria-label="Next month" onClick={() => setMonth(addMonths(month, 1))}>
          <ChevronGlyph />
        </button>
      </div>
      <div ref={grid} role="grid" aria-labelledby={props["aria-label"] ? undefined : titleId} aria-label={props["aria-label"]} className="cz-calendar__grid" onKeyDown={onKeyDown} onMouseLeave={() => setHover(undefined)}>
        <div role="row" className="cz-calendar__row">
          {weekdays.map((d) => (
            <div key={d.getDay()} role="columnheader" aria-label={fmtWeekdayLong.format(d)} className="cz-calendar__weekday">{fmtWeekday.format(d).slice(0, 2)}</div>
          ))}
        </div>
        {weeks.map((w, i) => (
          <div key={i} role="row" className="cz-calendar__row">
            {w.map((d) => {
              const outside = d.getMonth() !== month.getMonth();
              const isDisabled = disabled?.(d) ?? false;
              const isStart = range ? same(d, range.from) : false;
              const isEnd = range ? same(d, range.to ?? previewTo) : false;
              const selected = range ? isStart || same(d, range.to) : same(d, props.selected as Date | undefined);
              return (
                <div key={key(d)} role="gridcell" aria-selected={selected || inRange(d) || undefined} className="cz-calendar__cell" data-in-range={inRange(d) || undefined} data-range-start={(isStart && !!(range?.to ?? previewTo)) || undefined} data-range-end={(isEnd && !!range?.from && !same(range.from, range.to ?? previewTo)) || undefined}>
                  <button
                    type="button"
                    data-day={key(d)}
                    className="cz-calendar__day"
                    tabIndex={same(d, tabDay) ? 0 : -1}
                    disabled={isDisabled}
                    data-selected={selected || undefined}
                    data-today={same(d, today) || undefined}
                    data-outside={outside || undefined}
                    data-marked={markedKeys.has(key(d)) || undefined}
                    aria-label={fmtDay.format(d) + (markedKeys.has(key(d)) ? ", marked" : "")}
                    aria-current={same(d, today) ? "date" : undefined}
                    onClick={() => choose(d)}
                    onFocus={() => setFocus(d)}
                    onMouseEnter={() => range?.from && !range.to && setHover(d)}
                  >
                    {d.getDate()}
                  </button>
                </div>
              );
            })}
          </div>
        ))}
      </div>
    </div>
  );
}

export { Calendar };
```

npm: `import { Calendar } from "@0xtrou/cozy-ui"` (after `npm install @0xtrou/cozy-ui` and `import "@0xtrou/cozy-ui/styles.css"`).
