{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "calendar",
  "type": "registry:ui",
  "title": "Calendar",
  "description": "A month grid for choosing a day, several days or a range of days, with days that can be unavailable for a stated reason and days that carry a mark. Days are plain \"YYYY-MM-DD\" strings, so no time zone can move them.",
  "categories": [
    "ui"
  ],
  "dependencies": [
    "lucide-react"
  ],
  "registryDependencies": [
    "@rivier-ui/theme",
    "@rivier-ui/announce",
    "@rivier-ui/cn",
    "@rivier-ui/direction",
    "@rivier-ui/use-controllable-state"
  ],
  "files": [
    {
      "path": "registry/ui/calendar.tsx",
      "type": "registry:ui",
      "target": "components/ui/calendar.tsx",
      "content": "\"use client\";\n/**\n * @name calendar\n * @category ui\n * @description A month grid for choosing a day, several days or a range of days, with days that can be unavailable for a stated reason and days that carry a mark. Days are plain \"YYYY-MM-DD\" strings, so no time zone can move them.\n * @when Choosing dates where seeing the month matters: a booking, a stay, a deadline. It stays on the page; to open it from a field use date-picker. Never use the browser's native date input beside it. For a date far in the past that the person knows by heart (a birthday) three plain fields are quicker. Pass `locale` (the page's language) so that names, numerals and the first day of the week are right; without it the calendar is in English.\n * @example\n * // One day (uncontrolled), with days that cannot be chosen and days that carry a word\n * <Calendar\n *   locale=\"en-GB\"\n *   defaultValue=\"2026-11-14\"\n *   min=\"2026-11-01\"\n *   disabled={(day) => (closed.has(day) ? \"nothing open\" : false)}\n *   marks={(day) => (busy.has(day) ? \"busy\" : undefined)}\n * />\n *\n * // A range (controlled), two months where there is room\n * const [stay, setStay] = useState<CalendarRange>({ start: null, end: null });\n * <Calendar mode=\"range\" value={stay} onValueChange={setStay} numberOfMonths={2} locale=\"en-GB\" />\n *\n * // Several days, and its own layout with a footer\n * <Calendar mode=\"multiple\" defaultValue={[\"2026-11-03\", \"2026-11-05\"]}>\n *   <CalendarPrevious />\n *   <CalendarNext />\n *   <CalendarMonths />\n *   <p className=\"px-1 pt-2 text-sm text-muted-foreground\">A dot marks a busy day.</p>\n * </Calendar>\n */\nimport { ChevronLeft, ChevronRight } from \"lucide-react\";\nimport { createContext, use, useEffect, useId, useMemo, useState, useSyncExternalStore, type ComponentProps, type KeyboardEvent, type ReactNode } from \"react\";\nimport { announce } from \"@/lib/announce\";\nimport { cn } from \"@/lib/cn\";\nimport { inlineStep } from \"@/lib/direction\";\nimport { useControllableState } from \"@/lib/use-controllable-state\";\n\n/* Days as text. All arithmetic is done in UTC, where every day has 24 hours, and never touches local time. */\n\nconst DAY_MS = 86_400_000;\nconst pad = (value: number, length = 2): string => String(value).padStart(length, \"0\");\n\nfunction toUtc(day: string): number {\n  const [year = 1970, month = 1, date = 1] = day.split(\"-\").map(Number);\n  return Date.UTC(year, month - 1, date);\n}\n\nfunction fromUtc(time: number): string {\n  const date = new Date(time);\n  return `${pad(date.getUTCFullYear(), 4)}-${pad(date.getUTCMonth() + 1)}-${pad(date.getUTCDate())}`;\n}\n\nconst daysInMonth = (year: number, month: number): number => new Date(Date.UTC(year, month, 0)).getUTCDate();\n\n/** The day `count` days after (or, negative, before) a \"YYYY-MM-DD\" day. */\nexport function addDays(day: string, count: number): string {\n  return fromUtc(toUtc(day) + count * DAY_MS);\n}\n\n/** The same day of the month `count` months later (or earlier), or that month's last day when it is shorter. */\nexport function addMonths(day: string, count: number): string {\n  const [year = 1970, month = 1, date = 1] = day.split(\"-\").map(Number);\n  const total = year * 12 + (month - 1) + count;\n  const nextYear = Math.floor(total / 12);\n  const nextMonth = (((total % 12) + 12) % 12) + 1;\n  return `${pad(nextYear, 4)}-${pad(nextMonth)}-${pad(Math.min(date, daysInMonth(nextYear, nextMonth)))}`;\n}\n\n/** Today in the device's own time zone, as \"YYYY-MM-DD\". Only meaningful in the browser. */\nexport function todayISO(): string {\n  const now = new Date();\n  return `${pad(now.getFullYear(), 4)}-${pad(now.getMonth() + 1)}-${pad(now.getDate())}`;\n}\n\n/** A day written out for people (\"14 Nov 2026\"). `options` are Intl.DateTimeFormat's; the default is the medium date style. */\nexport function formatDay(day: string, locale = \"en\", options: Intl.DateTimeFormatOptions = { dateStyle: \"medium\" }): string {\n  return new Intl.DateTimeFormat(locale, { ...options, timeZone: \"UTC\" }).format(toUtc(day));\n}\n\nconst monthOf = (day: string): string => day.slice(0, 7);\nconst shiftMonth = (month: string, count: number): string => monthOf(addMonths(`${month}-01`, count));\nconst weekdayOf = (day: string): number => new Date(toUtc(day)).getUTCDay();\n\n/*\n * The first day of the week by region (CLDR). A table, not Intl's week info, because the server and the\n * browser must agree and not every runtime has that API. Everywhere not listed starts on Monday.\n */\nconst WEEK_STARTS: Record<number, string> = {\n  0: \"AG AS BD BR BS BT BW BZ CA CO DM DO ET GT GU HK HN ID IL IN JM JP KE KH KR LA MH MM MO MT MX MZ NI NP PA PE PH PK PR PT PY SA SG SV TH TT TW UM US VE VI WS YE ZA ZW\",\n  5: \"MV\",\n  6: \"AE AF BH DJ DZ EG IQ IR JO KW LY OM QA SD SY\",\n};\n\n/** The first day of the week for a language tag: 0 is Sunday, 1 Monday, … 6 Saturday. */\nexport function weekStartOf(locale: string): number {\n  try {\n    const region = new Intl.Locale(locale).maximize().region ?? \"\";\n    for (const [day, regions] of Object.entries(WEEK_STARTS)) {\n      if (regions.split(\" \").includes(region)) return Number(day);\n    }\n  } catch {\n    // An unknown tag: Monday.\n  }\n  return 1;\n}\n\nexport type CalendarRange = { start: string | null; end: string | null };\nexport type CalendarMode = \"single\" | \"multiple\" | \"range\";\ntype CalendarValue = string | null | string[] | CalendarRange;\n\nexport type CalendarLabels = {\n  previousMonth: string;\n  nextMonth: string;\n  /** Said after today's date. */\n  today: string;\n  /** Said after a chosen day. */\n  selected: string;\n  rangeStart: string;\n  rangeEnd: string;\n  /** Said after a day between the start and the end of a range. */\n  inRange: string;\n};\n\nconst LABELS: CalendarLabels = {\n  previousMonth: \"Previous month\",\n  nextMonth: \"Next month\",\n  today: \"today\",\n  selected: \"selected\",\n  rangeStart: \"start of the range\",\n  rangeEnd: \"end of the range\",\n  inRange: \"in the range\",\n};\n\ntype CalendarSelection =\n  | { mode?: \"single\"; value?: string | null; defaultValue?: string | null; onValueChange?: (value: string | null) => void }\n  | { mode: \"multiple\"; value?: string[]; defaultValue?: string[]; onValueChange?: (value: string[]) => void }\n  | { mode: \"range\"; value?: CalendarRange; defaultValue?: CalendarRange; onValueChange?: (value: CalendarRange) => void };\n\nexport type CalendarOptions = {\n  /** The month shown (the first one, when two are shown), as \"YYYY-MM\". Controlled. */\n  month?: string;\n  /** The month shown at first. Default: the month of the chosen day, else of today. */\n  defaultMonth?: string;\n  onMonthChange?: (month: string) => void;\n  /** The first and the last day that can be chosen or reached. */\n  min?: string;\n  max?: string;\n  /**\n   * Days that cannot be chosen. Return true, or the reason as a few words (\"nothing open\"): the reason is\n   * part of the day's accessible name, and the day can still be focused so that it can be read.\n   */\n  disabled?: (day: string) => boolean | string;\n  /** A word for a day that carries a mark (\"busy\"). It is drawn as a dot and said in the day's name. */\n  marks?: (day: string) => string | undefined;\n  /** The language tag for names, numerals and the first day of the week. Default \"en\". */\n  locale?: string;\n  /** The first day of the week, when the locale's is not wanted: 0 is Sunday, 1 Monday. */\n  weekStartsOn?: number;\n  /** 2 shows a second month beside the first where the calendar is wide enough for both. */\n  numberOfMonths?: 1 | 2;\n  /** Today as \"YYYY-MM-DD\", when the product's \"today\" is not the device's (another time zone). Default: the device's, known after mounting. */\n  today?: string;\n  /** The words the calendar says itself. Translate them with the interface. */\n  labels?: Partial<CalendarLabels>;\n};\n\nexport type CalendarProps = Omit<ComponentProps<\"div\">, \"defaultValue\" | \"onChange\"> & CalendarOptions & CalendarSelection & { children?: ReactNode };\n\ntype DayState = {\n  selected: boolean;\n  /** Its place in a range, also while the end is being chosen (`preview`). */\n  range: \"start\" | \"end\" | \"middle\" | \"only\" | null;\n  preview: boolean;\n  today: boolean;\n  /** false, true, or the reason. */\n  disabled: boolean | string;\n  mark: string | undefined;\n  tabStop: boolean;\n  label: string;\n  text: string;\n};\n\ntype CalendarContextValue = {\n  /** The first month shown; null on the server when nothing says which month it is. */\n  month: string | null;\n  numberOfMonths: 1 | 2;\n  weekStart: number;\n  labels: CalendarLabels;\n  monthTitle: (month: string) => string;\n  weekdays: { short: string; long: string }[];\n  dayState: (day: string) => DayState;\n  choose: (day: string) => void;\n  focusDay: (day: string) => void;\n  hoverDay: (day: string | null) => void;\n  onKeyDown: (event: KeyboardEvent<HTMLElement>) => void;\n  go: (count: number, from: Element) => void;\n  canGo: (count: number) => boolean;\n};\n\nconst CalendarContext = createContext<CalendarContextValue | null>(null);\n\n/** The calendar's state, for a part of your own inside <Calendar> (a \"Today\" button, a legend). */\nexport function useCalendar(): CalendarContextValue {\n  const context = use(CalendarContext);\n  if (!context) throw new Error(\"Calendar parts must be used inside <Calendar>.\");\n  return context;\n}\n\nconst noSubscription = (): (() => void) => () => {};\nconst noToday = (): null => null;\n\n/** The months that are on screen now inside this calendar (the second one is hidden where there is no room). */\nfunction visibleMonths(from: Element): number {\n  const root = from.closest(\"[data-slot=calendar]\");\n  if (!root) return 1;\n  return Math.max(1, [...root.querySelectorAll(\"[data-slot=calendar-month]\")].filter((month) => month.getClientRects().length > 0).length);\n}\n\n/**\n * The date grid pattern. One day is in the Tab order; from it, arrow keys move by a day (Left and Right the\n * other way round in right-to-left pages) or a week, Home and End go to the ends of the week, Page Up and\n * Page Down move by a month and, with Shift, by a year; Enter or Space chooses. Focus carries on into the\n * next or the previous month. In \"range\" mode the first press sets the start and the second the end; while\n * the end is being chosen the days in between are shown as a preview.\n */\nexport function Calendar(allProps: CalendarProps) {\n  const {\n    className,\n    mode = \"single\",\n    value,\n    defaultValue,\n    onValueChange,\n    month: monthProp,\n    defaultMonth,\n    onMonthChange,\n    min,\n    max,\n    disabled,\n    marks,\n    locale = \"en\",\n    weekStartsOn,\n    numberOfMonths = 1,\n    today: todayProp,\n    labels: labelsProp,\n    children,\n    ...props\n  } = allProps;\n  const id = useId();\n  const labels = useMemo(() => ({ ...LABELS, ...labelsProp }), [labelsProp]);\n\n  const [current, setCurrent] = useControllableState<CalendarValue>({\n    value,\n    defaultValue: defaultValue ?? (mode === \"multiple\" ? [] : mode === \"range\" ? { start: null, end: null } : null),\n    onChange: onValueChange as ((value: CalendarValue) => void) | undefined,\n  });\n  const single = mode === \"single\" ? (current as string | null) : null;\n  const several = mode === \"multiple\" ? (current as string[]) : null;\n  const range = mode === \"range\" ? (current as CalendarRange) : null;\n\n  // The device's day is only known in the browser: null on the server and while hydrating.\n  const deviceToday = useSyncExternalStore(noSubscription, todayISO, noToday);\n  const today = todayProp ?? deviceToday;\n\n  const [ownMonth, setOwnMonth] = useControllableState<string | null>({\n    value: monthProp,\n    defaultValue: defaultMonth ?? null,\n    onChange: (next) => {\n      if (next) onMonthChange?.(next);\n    },\n  });\n  const anchor = single ?? several?.toSorted()[0] ?? range?.start ?? range?.end ?? today;\n  const month = ownMonth ?? (anchor ? monthOf(anchor) : null);\n\n  /** The day the keyboard is on, and a counter that asks for it to be focused once it is on screen. */\n  const [focused, setFocused] = useState<string | null>(null);\n  const [focusRequest, setFocusRequest] = useState(0);\n  /** The day under the pointer or the keyboard while a range is waiting for its end. */\n  const [hovered, setHovered] = useState<string | null>(null);\n\n  useEffect(() => {\n    if (focusRequest === 0 || !focused) return;\n    document.querySelector<HTMLElement>(`[data-calendar=\"${id}\"] [data-day=\"${focused}\"]`)?.focus();\n  }, [focusRequest, focused, id]);\n\n  const formats = useMemo(\n    () => ({\n      month: new Intl.DateTimeFormat(locale, { month: \"long\", year: \"numeric\", timeZone: \"UTC\" }),\n      full: new Intl.DateTimeFormat(locale, { weekday: \"long\", day: \"numeric\", month: \"long\", year: \"numeric\", timeZone: \"UTC\" }),\n      day: new Intl.DateTimeFormat(locale, { day: \"numeric\", timeZone: \"UTC\" }),\n      short: new Intl.DateTimeFormat(locale, { weekday: \"short\", timeZone: \"UTC\" }),\n      long: new Intl.DateTimeFormat(locale, { weekday: \"long\", timeZone: \"UTC\" }),\n    }),\n    [locale],\n  );\n  const weekStart = (((weekStartsOn ?? weekStartOf(locale)) % 7) + 7) % 7;\n  const weekdays = useMemo(\n    () =>\n      Array.from({ length: 7 }, (_, index) => {\n        // 4 January 1970 was a Sunday.\n        const time = Date.UTC(1970, 0, 4 + weekStart + index);\n        return { short: formats.short.format(time), long: formats.long.format(time) };\n      }),\n    [formats, weekStart],\n  );\n  const monthTitle = (which: string): string => formats.month.format(toUtc(`${which}-01`));\n\n  const outOfRange = (day: string): boolean => (min !== undefined && day < min) || (max !== undefined && day > max);\n  const disabledOf = (day: string): boolean | string => (outOfRange(day) ? true : (disabled?.(day) ?? false));\n  const clamp = (day: string): string => (min !== undefined && day < min ? min : max !== undefined && day > max ? max : day);\n\n  // The range as it is drawn: the chosen one, or the start with the day under the pointer while the end is open.\n  const previewing = range !== null && range.start !== null && range.end === null && hovered !== null && hovered !== range.start;\n  const drawn: { start: string; end: string } | null =\n    range?.start && range.end\n      ? { start: range.start, end: range.end }\n      : range?.start && previewing && hovered\n        ? { start: range.start < hovered ? range.start : hovered, end: range.start < hovered ? hovered : range.start }\n        : null;\n\n  const isSelected = (day: string): boolean => (range ? day === range.start || day === range.end : several ? several.includes(day) : day === single);\n\n  // The one day in the Tab order: the day the keyboard was last on, else a chosen day, else today, else the first of the month.\n  const shown = month ? Array.from({ length: numberOfMonths }, (_, index) => shiftMonth(month, index)) : [];\n  const candidates = [focused, single, ...(several?.toSorted() ?? []), range?.start, range?.end, today].filter((day): day is string => typeof day === \"string\");\n  const tabStop =\n    (focused && shown.includes(monthOf(focused)) ? focused : undefined) ??\n    candidates.find((day) => monthOf(day) === month) ??\n    candidates.find((day) => shown.includes(monthOf(day))) ??\n    (month ? clamp(`${month}-01`).slice(0, 7) === month ? clamp(`${month}-01`) : `${month}-01` : null);\n\n  const dayState = (day: string): DayState => {\n    const selected = isSelected(day);\n    const place: DayState[\"range\"] = !range\n      ? null\n      : drawn\n        ? drawn.start === drawn.end && day === drawn.start\n          ? \"only\"\n          : day === drawn.start\n            ? \"start\"\n            : day === drawn.end\n              ? \"end\"\n              : day > drawn.start && day < drawn.end\n                ? \"middle\"\n                : null\n        : selected\n          ? \"only\"\n          : null;\n    const isToday = day === today;\n    const reason = disabledOf(day);\n    const mark = marks?.(day);\n    const said = [\n      formats.full.format(toUtc(day)),\n      isToday ? labels.today : null,\n      range\n        ? day === range.start && day === range.end\n          ? labels.selected\n          : day === range.start\n            ? labels.rangeStart\n            : day === range.end\n              ? labels.rangeEnd\n              : place === \"middle\" && !previewing\n                ? labels.inRange\n                : null\n        : selected\n          ? labels.selected\n          : null,\n      mark ?? null,\n      typeof reason === \"string\" ? reason : null,\n    ].filter((part): part is string => Boolean(part));\n    return { selected, range: place, preview: previewing && place !== null, today: isToday, disabled: reason, mark, tabStop: day === tabStop, label: said.join(\", \"), text: formats.day.format(toUtc(day)) };\n  };\n\n  const choose = (day: string): void => {\n    setFocused(day);\n    if (disabledOf(day) !== false) return;\n    if (range) {\n      if (!range.start || range.end) setCurrent({ start: day, end: null });\n      else setCurrent(day < range.start ? { start: day, end: range.start } : { start: range.start, end: day });\n      setHovered(null);\n    } else if (several) {\n      setCurrent(several.includes(day) ? several.filter((other) => other !== day) : [...several, day].sort());\n    } else {\n      setCurrent(day);\n    }\n  };\n\n  const moveTo = (target: string, from: Element): void => {\n    if (!month) return;\n    const day = clamp(target);\n    const count = Math.min(numberOfMonths, visibleMonths(from));\n    const last = shiftMonth(month, count - 1);\n    if (monthOf(day) < month) setOwnMonth(monthOf(day));\n    else if (monthOf(day) > last) setOwnMonth(shiftMonth(monthOf(day), -(count - 1)));\n    setFocused(day);\n    setFocusRequest((request) => request + 1);\n  };\n\n  const onKeyDown = (event: KeyboardEvent<HTMLElement>): void => {\n    const day = (event.target as HTMLElement).closest<HTMLElement>(\"[data-day]\")?.dataset[\"day\"];\n    if (!day || event.altKey || event.ctrlKey || event.metaKey) return;\n    const sideways = inlineStep(event.key, event.currentTarget);\n    const fromWeekStart = (weekdayOf(day) - weekStart + 7) % 7;\n    const target =\n      sideways !== 0\n        ? addDays(day, sideways)\n        : event.key === \"ArrowUp\"\n          ? addDays(day, -7)\n          : event.key === \"ArrowDown\"\n            ? addDays(day, 7)\n            : event.key === \"Home\"\n              ? addDays(day, -fromWeekStart)\n              : event.key === \"End\"\n                ? addDays(day, 6 - fromWeekStart)\n                : event.key === \"PageUp\"\n                  ? addMonths(day, event.shiftKey ? -12 : -1)\n                  : event.key === \"PageDown\"\n                    ? addMonths(day, event.shiftKey ? 12 : 1)\n                    : null;\n    if (!target) return;\n    event.preventDefault();\n    moveTo(target, event.currentTarget);\n  };\n\n  const canGo = (count: number): boolean => {\n    if (!month) return false;\n    if (count < 0) return min === undefined || addDays(`${month}-01`, -1) >= min;\n    return max === undefined || `${shiftMonth(month, 1)}-01` <= max;\n  };\n\n  const go = (count: number, from: Element): void => {\n    if (!month || !canGo(count)) return;\n    const next = shiftMonth(month, count);\n    setOwnMonth(next);\n    // No focus moves, so the new month is said. Two months are named when two are on screen.\n    const visible = Math.min(numberOfMonths, visibleMonths(from));\n    announce(Array.from({ length: visible }, (_, index) => monthTitle(shiftMonth(next, index))).join(\" – \"));\n  };\n\n  return (\n    <CalendarContext\n      value={{\n        month,\n        numberOfMonths,\n        weekStart,\n        labels,\n        monthTitle,\n        weekdays,\n        dayState,\n        choose,\n        focusDay: setFocused,\n        hoverDay: (day) => {\n          if (range?.start && !range.end) setHovered(day);\n        },\n        onKeyDown,\n        go,\n        canGo,\n      }}\n    >\n      <div\n        data-slot=\"calendar\"\n        data-calendar={id}\n        data-mode={mode}\n        aria-busy={month === null || undefined}\n        className={cn(\"relative p-3 text-sm text-foreground\", numberOfMonths === 2 ? \"@container w-full\" : \"w-fit max-w-full\", className)}\n        {...props}\n      >\n        {children ?? (\n          <>\n            <CalendarPrevious />\n            <CalendarNext />\n            <CalendarMonths />\n          </>\n        )}\n      </div>\n    </CalendarContext>\n  );\n}\n\nconst navClass =\n  \"absolute top-3 z-10 inline-flex size-9 items-center justify-center rounded-control text-muted-foreground transition-[background-color,color,opacity] duration-instant ease-out hover:bg-accent hover:text-foreground disabled:pointer-events-none disabled:opacity-40 motion-reduce:transition-none pointer-coarse:size-10 [&_svg]:size-4 rtl:[&_svg]:rotate-180\";\n\nexport type CalendarNavProps = Omit<ComponentProps<\"button\">, \"type\">;\n\n/** Goes back a month. It sits at the start of the heading row; the new month is announced. */\nexport function CalendarPrevious({ className, children, onClick, ...props }: CalendarNavProps) {\n  const calendar = useCalendar();\n  return (\n    <button\n      type=\"button\"\n      data-slot=\"calendar-previous\"\n      aria-label={calendar.labels.previousMonth}\n      disabled={!calendar.canGo(-1)}\n      onClick={(event) => {\n        onClick?.(event);\n        if (!event.defaultPrevented) calendar.go(-1, event.currentTarget);\n      }}\n      className={cn(navClass, \"start-3\", className)}\n      {...props}\n    >\n      {children ?? <ChevronLeft aria-hidden=\"true\" strokeWidth={1.5} />}\n    </button>\n  );\n}\n\n/** Goes on a month. It sits at the end of the heading row; the new month is announced. */\nexport function CalendarNext({ className, children, onClick, ...props }: CalendarNavProps) {\n  const calendar = useCalendar();\n  return (\n    <button\n      type=\"button\"\n      data-slot=\"calendar-next\"\n      aria-label={calendar.labels.nextMonth}\n      disabled={!calendar.canGo(1)}\n      onClick={(event) => {\n        onClick?.(event);\n        if (!event.defaultPrevented) calendar.go(1, event.currentTarget);\n      }}\n      className={cn(navClass, \"end-3\", className)}\n      {...props}\n    >\n      {children ?? <ChevronRight aria-hidden=\"true\" strokeWidth={1.5} />}\n    </button>\n  );\n}\n\n/** The months side by side: one, or two where `numberOfMonths` is 2 and the calendar is wide enough. */\nexport function CalendarMonths({ className, ...props }: ComponentProps<\"div\">) {\n  const { numberOfMonths } = useCalendar();\n  return (\n    <div data-slot=\"calendar-months\" className={cn(\"flex justify-center gap-6\", className)} {...props}>\n      <CalendarMonth offset={0} />\n      {numberOfMonths === 2 ? <CalendarMonth offset={1} className=\"hidden @[38rem]:block\" /> : null}\n    </div>\n  );\n}\n\nconst cellSize = \"size-9 pointer-coarse:size-10\";\n\nexport type CalendarMonthProps = ComponentProps<\"div\"> & {\n  /** Which month, counted from the first one shown: 0 or 1. */\n  offset?: number;\n};\n\n/** One month: its name and its grid. Always six rows tall, so the calendar keeps its height from month to month. */\nexport function CalendarMonth({ offset = 0, className, ...props }: CalendarMonthProps) {\n  const calendar = useCalendar();\n  const headingId = useId();\n  const month = calendar.month ? shiftMonth(calendar.month, offset) : null;\n\n  const cells: (string | null)[] = [];\n  if (month) {\n    const [year = 1970, number = 1] = month.split(\"-\").map(Number);\n    const lead = (weekdayOf(`${month}-01`) - calendar.weekStart + 7) % 7;\n    const length = daysInMonth(year, number);\n    for (let index = 0; index < 42; index++) {\n      const date = index - lead + 1;\n      cells.push(date >= 1 && date <= length ? `${month}-${pad(date)}` : null);\n    }\n  } else {\n    for (let index = 0; index < 42; index++) cells.push(null);\n  }\n  const weeks = Array.from({ length: 6 }, (_, week) => cells.slice(week * 7, week * 7 + 7));\n\n  return (\n    <div data-slot=\"calendar-month\" data-month={month ?? undefined} className={cn(\"min-w-0\", className)} {...props}>\n      <div id={headingId} data-slot=\"calendar-heading\" className=\"flex h-9 items-center justify-center px-10 text-center font-medium pointer-coarse:h-10\">\n        {month ? calendar.monthTitle(month) : \" \"}\n      </div>\n      <table\n        role=\"grid\"\n        aria-labelledby={headingId}\n        data-slot=\"calendar-grid\"\n        className=\"mx-auto border-separate border-spacing-x-0 border-spacing-y-0.5\"\n        onKeyDown={calendar.onKeyDown}\n        onPointerLeave={() => calendar.hoverDay(null)}\n      >\n        <thead>\n          <tr>\n            {calendar.weekdays.map((weekday) => (\n              <th key={weekday.long} scope=\"col\" abbr={weekday.long} className=\"h-8 w-9 p-0 text-center text-xs font-normal text-muted-foreground pointer-coarse:w-10\">\n                <span aria-hidden=\"true\">{weekday.short}</span>\n                <span className=\"sr-only\">{weekday.long}</span>\n              </th>\n            ))}\n          </tr>\n        </thead>\n        <tbody>\n          {weeks.map((week, index) => (\n            <tr key={index}>{week.map((day, column) => (day ? <CalendarDay key={day} day={day} /> : <td key={column} className={cn(\"p-0\", cellSize)} />))}</tr>\n          ))}\n        </tbody>\n      </table>\n    </div>\n  );\n}\n\n/**\n * One day. Its accessible name is the full date followed by what is true of it: today, chosen (or its place\n * in a range), its mark, and why it cannot be chosen. A day that cannot be chosen keeps its place in the\n * keyboard order (`aria-disabled`, not `disabled`) so that the reason can be reached and read.\n */\nfunction CalendarDay({ day }: { day: string }) {\n  const calendar = useCalendar();\n  const state = calendar.dayState(day);\n  const unavailable = state.disabled !== false;\n  const filled = state.selected || state.range === \"start\" || state.range === \"end\" || state.range === \"only\";\n  return (\n    <td\n      role=\"gridcell\"\n      aria-selected={state.selected || (state.range !== null && !state.preview)}\n      data-range={state.range ?? undefined}\n      data-preview={state.preview ? \"\" : undefined}\n      className={cn(\n        \"p-0\",\n        // The band of a range: square in the middle, capped at its two ends. A preview is an outline, not a ground.\n        \"data-[range=end]:rounded-e-control data-[range=start]:rounded-s-control\",\n        \"not-data-preview:data-[range=end]:bg-highlight-soft not-data-preview:data-[range=middle]:bg-highlight-soft not-data-preview:data-[range=start]:bg-highlight-soft\",\n        \"data-preview:data-[range=end]:outline data-preview:data-[range=middle]:outline data-preview:data-[range=start]:outline data-preview:outline-dashed data-preview:-outline-offset-1 data-preview:outline-border-strong\",\n      )}\n    >\n      <button\n        type=\"button\"\n        data-slot=\"calendar-day\"\n        data-day={day}\n        data-today={state.today ? \"\" : undefined}\n        data-selected={filled ? \"\" : undefined}\n        data-unavailable={unavailable ? \"\" : undefined}\n        tabIndex={state.tabStop ? 0 : -1}\n        aria-label={state.label}\n        aria-current={state.today ? \"date\" : undefined}\n        aria-disabled={unavailable || undefined}\n        onClick={() => calendar.choose(day)}\n        onFocus={() => {\n          calendar.focusDay(day);\n          calendar.hoverDay(day);\n        }}\n        onPointerEnter={() => calendar.hoverDay(day)}\n        className={cn(\n          \"relative inline-flex items-center justify-center rounded-control tabular-nums transition-[background-color,color] duration-instant ease-out select-none hover:bg-accent motion-reduce:transition-none\",\n          cellSize,\n          \"data-today:font-semibold data-today:underline data-today:decoration-2 data-today:underline-offset-4\",\n          \"data-selected:bg-primary data-selected:font-semibold data-selected:text-primary-foreground data-selected:hover:bg-primary\",\n          \"data-unavailable:cursor-not-allowed data-unavailable:text-muted-foreground data-unavailable:line-through data-unavailable:hover:bg-transparent\",\n        )}\n      >\n        <span aria-hidden=\"true\">{state.text}</span>\n        {state.mark ? <span aria-hidden=\"true\" data-slot=\"calendar-mark\" className=\"absolute bottom-1 size-1 rounded-full bg-current\" /> : null}\n      </button>\n    </td>\n  );\n}\n"
    }
  ],
  "meta": {
    "category": "ui",
    "when": "Choosing dates where seeing the month matters: a booking, a stay, a deadline. It stays on the page; to open it from a field use date-picker. Never use the browser's native date input beside it. For a date far in the past that the person knows by heart (a birthday) three plain fields are quicker. Pass `locale` (the page's language) so that names, numerals and the first day of the week are right; without it the calendar is in English.",
    "example": "// One day (uncontrolled), with days that cannot be chosen and days that carry a word\n<Calendar\n  locale=\"en-GB\"\n  defaultValue=\"2026-11-14\"\n  min=\"2026-11-01\"\n  disabled={(day) => (closed.has(day) ? \"nothing open\" : false)}\n  marks={(day) => (busy.has(day) ? \"busy\" : undefined)}\n/>\n\n// A range (controlled), two months where there is room\nconst [stay, setStay] = useState<CalendarRange>({ start: null, end: null });\n<Calendar mode=\"range\" value={stay} onValueChange={setStay} numberOfMonths={2} locale=\"en-GB\" />\n\n// Several days, and its own layout with a footer\n<Calendar mode=\"multiple\" defaultValue={[\"2026-11-03\", \"2026-11-05\"]}>\n  <CalendarPrevious />\n  <CalendarNext />\n  <CalendarMonths />\n  <p className=\"px-1 pt-2 text-sm text-muted-foreground\">A dot marks a busy day.</p>\n</Calendar>",
    "client": true
  }
}
