{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "calendar",
  "title": "Calendar",
  "description": "A month grid to pick a day or a range of days, with the arrow keys or a press.",
  "registryDependencies": [
    "@ouro/button",
    "@ouro/lib-class-name-check",
    "@ouro/lib-cn",
    "@ouro/lib-env",
    "@ouro/lib-use-dev-messages"
  ],
  "files": [
    {
      "path": "registry/ouro/components/ouro/calendar/calendar-styles.ts",
      "content": "export {\n  addDays,\n  addMonths,\n  calendarHint,\n  dayClass,\n  firstDayOfWeek,\n  isIsoDate,\n  isoWarning,\n  monthGrid,\n  monthStart,\n  navClass,\n  todayIso,\n  weekdayHeaderClass,\n};\nexport type { DateRange };\n\n// Date math, value lists and class strings for Calendar and DatePicker, apart from the\n// components so each component file exports only components (React Fast Refresh). Dates are\n// ISO `YYYY-MM-DD` strings, the format a native date input submits; the math runs on UTC\n// midnights, so a daylight saving change never shifts a day. Class strings are literal so the\n// app's Tailwind finds them when it compiles.\n\n/** A range of days, both ends included, as ISO dates (`\"2026-10-11\"`). */\ninterface DateRange {\n  /** The first day. */\n  start: string;\n  /** The last day; the same as `start` for a one-day range. */\n  end: string;\n}\n\nconst ISO = /^(\\d{4})-(\\d{2})-(\\d{2})$/;\n\n/** The UTC midnight of an ISO date. */\nfunction toDate(iso: string): Date {\n  const [, year, month, day] = ISO.exec(iso)!;\n  const date = new Date(0);\n  date.setUTCFullYear(Number(year), Number(month) - 1, Number(day));\n  return date;\n}\n\n/** The ISO date of a UTC midnight. */\nfunction toIso(date: Date): string {\n  const year = String(date.getUTCFullYear()).padStart(4, \"0\");\n  const month = String(date.getUTCMonth() + 1).padStart(2, \"0\");\n  const day = String(date.getUTCDate()).padStart(2, \"0\");\n  return `${year}-${month}-${day}`;\n}\n\n/**\n * Whether a value is a real ISO calendar date, `YYYY-MM-DD` (`\"2026-02-30\"` is not).\n *\n * @internal\n */\nfunction isIsoDate(value: unknown): value is string {\n  return typeof value === \"string\" && ISO.test(value) && toIso(toDate(value)) === value;\n}\n\n/**\n * The day `count` days after `iso` (before it when negative).\n *\n * @internal\n */\nfunction addDays(iso: string, count: number): string {\n  const date = toDate(iso);\n  date.setUTCDate(date.getUTCDate() + count);\n  return toIso(date);\n}\n\n/**\n * The same day `count` months later, or that month's last day when it is shorter\n * (January 31 plus one month is February 28).\n *\n * @internal\n * @claim \"The same day `count` months later\" registry/ouro/components/ouro/calendar/calendar.test.tsx verify:testExists(registry/ouro/components/ouro/calendar/calendar.test.tsx::Calendar date math > checks ISO dates, adds months with clamping and lays out months)\n */\nfunction addMonths(iso: string, count: number): string {\n  const date = toDate(iso);\n  const day = date.getUTCDate();\n  date.setUTCDate(1);\n  date.setUTCMonth(date.getUTCMonth() + count);\n  const last = new Date(date);\n  last.setUTCMonth(last.getUTCMonth() + 1, 0);\n  date.setUTCDate(Math.min(day, last.getUTCDate()));\n  return toIso(date);\n}\n\n/**\n * The first day of the month `iso` is in.\n *\n * @internal\n */\nfunction monthStart(iso: string): string {\n  return `${iso.slice(0, 8)}01`;\n}\n\n/**\n * Today in the user's time zone, as an ISO date.\n *\n * @internal\n */\nfunction todayIso(): string {\n  const now = new Date();\n  const date = new Date(0);\n  date.setUTCFullYear(now.getFullYear(), now.getMonth(), now.getDate());\n  return toIso(date);\n}\n\n// Where Intl.Locale has no week information (Firefox), the regions whose week starts on\n// Sunday, Saturday or Friday, from CLDR's weekData; every other region starts on Monday.\nconst sundayRegions = new Set(\n  \"AG AS BD BR BS BT BW BZ CA CN 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\".split(\" \"),\n);\nconst saturdayRegions = new Set(\"AE AF BH DJ DZ EG IQ IR JO KW LY OM QA SD SY\".split(\" \"));\nconst fridayRegions = new Set([\"MV\"]);\n/** The `-u-fw-` day keys, in `Date.getUTCDay()` order. */\nconst weekdayKeys = [\"sun\", \"mon\", \"tue\", \"wed\", \"thu\", \"fri\", \"sat\"];\n\n/** What Intl.Locale says about weeks, in browsers that have it. */\ntype WeekLocale = Intl.Locale & { getWeekInfo?: () => { firstDay: number }; weekInfo?: { firstDay: number } };\n\n/**\n * The day a week starts on in a locale, as `Date.getUTCDay()` numbers it (0 is Sunday). It\n * honors a `-u-fw-` extension (`\"en-US-u-fw-mon\"`) where the browser does.\n *\n * @internal\n * @claim \"The day a week starts on\" registry/ouro/components/ouro/calendar/calendar.test.tsx verify:testExists(registry/ouro/components/ouro/calendar/calendar.test.tsx::Calendar > locale > takes the first day of the week from the locale)\n */\nfunction firstDayOfWeek(locale: string): number {\n  const intl = new Intl.Locale(locale) as WeekLocale;\n  const info = intl.getWeekInfo?.() ?? intl.weekInfo;\n  if (info) return info.firstDay % 7;\n  // A `-u-fw-` extension names the day outright; without week information, read it here.\n  const named = /-u(?:-[a-z0-9]{2,8})*?-fw-(sun|mon|tue|wed|thu|fri|sat)\\b/i.exec(locale);\n  if (named) return weekdayKeys.indexOf(named[1]!.toLowerCase());\n  // Likely-subtags always add a region (\"und\" maximizes to en-Latn-US).\n  const region = intl.maximize().region!;\n  return sundayRegions.has(region) ? 0 : saturdayRegions.has(region) ? 6 : fridayRegions.has(region) ? 5 : 1;\n}\n\n/**\n * A month as weeks of seven ISO dates, starting on `firstDay`; days outside the month are\n * `null`.\n *\n * @internal\n * @claim \"A month as weeks of seven\" registry/ouro/components/ouro/calendar/calendar.test.tsx verify:testExists(registry/ouro/components/ouro/calendar/calendar.test.tsx::Calendar date math > checks ISO dates, adds months with clamping and lays out months)\n */\nfunction monthGrid(month: string, firstDay: number): Array<Array<string | null>> {\n  const start = monthStart(month);\n  const lead = (toDate(start).getUTCDay() - firstDay + 7) % 7;\n  const days: Array<string | null> = Array.from({ length: lead }, () => null);\n  for (let day = start; day.slice(0, 7) === start.slice(0, 7); day = addDays(day, 1)) days.push(day);\n  while (days.length % 7 !== 0) days.push(null);\n  const weeks: Array<Array<string | null>> = [];\n  for (let index = 0; index < days.length; index += 7) weeks.push(days.slice(index, index + 7));\n  return weeks;\n}\n\n/**\n * A day: 44px on a coarse pointer, 36px with a fine one. Selected days fill with the\n * primary color, the days between a range's ends take the accent, today is bold and\n * underlined, and unavailable days fade and strike through.\n *\n * @internal\n * @claim \"A day: 44px on a coarse\" registry/ouro/components/ouro/calendar/calendar.test.tsx verify:testExists(registry/ouro/components/ouro/calendar/calendar.test.tsx::Calendar > lets app layout classes win on the root, and gives days 36px with a fine pointer)\n * @claim \"A day: 44px on a coarse\" registry/ouro/components/ouro/calendar/calendar.touch.test.tsx verify:testExists(registry/ouro/components/ouro/calendar/calendar.touch.test.tsx::gives Calendar's days and month buttons 44px touch targets)\n */\nconst dayClass =\n  \"press relative m-0 box-border inline-flex size-11 items-center justify-center pointer-fine:size-9 \" +\n  \"rounded-ouro-md border-0 bg-transparent p-0 font-[inherit] text-sm leading-none text-foreground tabular-nums \" +\n  \"cursor-pointer select-none touch-manipulation [-webkit-tap-highlight-color:transparent] \" +\n  \"outline-ring outline-offset-2 focus-visible:z-1 focus-visible:outline-2 focus-visible:outline-solid \" +\n  \"not-aria-disabled:not-data-selected:pointer-fine:hover:bg-accent not-aria-disabled:not-data-selected:pointer-fine:hover:text-accent-foreground \" +\n  \"motion-safe:not-aria-disabled:active:scale-(--ouro-press-scale) \" +\n  \"aria-[current=date]:font-semibold aria-[current=date]:underline aria-[current=date]:underline-offset-4 \" +\n  \"data-in-range:bg-accent data-in-range:text-accent-foreground \" +\n  \"data-selected:bg-primary data-selected:text-primary-foreground \" +\n  // Forced colours drop the fills: the chosen days take the system's highlight pair, and the days\n  // between a range's ends a border.\n  \"forced-colors:data-in-range:border forced-colors:data-in-range:border-solid \" +\n  \"forced-colors:data-selected:bg-[Highlight] forced-colors:data-selected:text-[HighlightText] \" +\n  \"aria-disabled:cursor-not-allowed aria-disabled:line-through aria-disabled:opacity-50\";\n\n/**\n * The previous and next month buttons: square, the size of a day.\n *\n * @internal\n */\nconst navClass = \"aspect-square px-0\";\n\n/**\n * The weekday names over the columns.\n *\n * @internal\n */\nconst weekdayHeaderClass = \"m-0 p-0 pb-1 text-xs leading-4 font-normal text-muted-foreground\";\n\n/**\n * The className hint: Calendar has no appearance props, so the fix is the theme.\n *\n * @internal\n * @claim \"The className hint: Calendar has no\" registry/ouro/components/ouro/calendar/calendar.test.tsx verify:testExists(registry/ouro/components/ouro/calendar/calendar.test.tsx::Calendar > development messages > warns when the label is empty, and about appearance classes)\n */\nfunction calendarHint(component: string): string {\n  return `<${component} className=\"mt-4\" />, and set colors in your theme's CSS variables`;\n}\n\n/**\n * The dev message for a date prop that is not an ISO date. Development only.\n *\n * @internal\n */\nfunction isoWarning(component: string, prop: string, value: unknown): readonly [string, string] {\n  return [`${prop}=${JSON.stringify(String(value))} is not an ISO date (YYYY-MM-DD)`, `<${component} ${prop}=\"2026-10-11\">`];\n}\n",
      "type": "registry:ui",
      "target": "@components/ouro/calendar/calendar-styles.ts"
    },
    {
      "path": "registry/ouro/components/ouro/calendar/calendar.tsx",
      "content": "\"use client\";\n\nimport { useEffect, useId, useMemo, useRef, useState, useSyncExternalStore, type JSX, type KeyboardEvent, type ReactNode, type Ref } from \"react\";\nimport { Button } from \"@/registry/ouro/components/ouro/button/button\";\nimport { useAppearanceClassNameCheck } from \"@/registry/ouro/lib/ouro/class-name-check\";\nimport { cn } from \"@/registry/ouro/lib/ouro/cn\";\nimport { useDevWarnings } from \"@/registry/ouro/lib/ouro/use-dev-messages\";\nimport {\n  addDays,\n  addMonths,\n  calendarHint,\n  dayClass,\n  firstDayOfWeek,\n  isIsoDate,\n  isoWarning,\n  monthGrid,\n  monthStart,\n  navClass,\n  todayIso,\n  weekdayHeaderClass,\n  type DateRange,\n} from \"@/registry/ouro/components/ouro/calendar/calendar-styles\";\n\nexport type { DateRange };\n\n/** The props both of Calendar's modes take. */\nexport interface CalendarBaseProps {\n  /**\n   * What the dates are for, read by screen readers as the calendar's name: `\"Delivery date\"`.\n   * Required, because a grid of numbers says nothing on its own. It is not shown; put a\n   * visible heading beside the calendar if the page needs one.\n   */\n  label: string;\n  /** The earliest day the user can pick, as an ISO date: `min=\"2026-10-11\"`. Earlier days are unavailable. */\n  min?: string | undefined;\n  /** The latest day the user can pick, as an ISO date: `max=\"2026-12-31\"`. Later days are unavailable. */\n  max?: string | undefined;\n  /**\n   * Marks single days unavailable: `isDateDisabled={(date) => booked.has(date)}`. It gets each\n   * day as an ISO date. Unavailable days stay in the arrow-key path, so screen readers still\n   * hear them, but cannot be picked.\n   * @claim \"It gets each day as an\" registry/ouro/components/ouro/calendar/calendar.test.tsx verify:testExists(registry/ouro/components/ouro/calendar/calendar.test.tsx::Calendar > unavailable days > marks days outside min and max, and days isDateDisabled names, and never picks them)\n   */\n  isDateDisabled?: ((date: string) => boolean) | undefined;\n  /**\n   * The BCP 47 locale for the month and weekday names, the digits and the first day of the\n   * week: `\"en-GB\"` starts weeks on Monday, `\"en-US\"` on Sunday. Pass your app's locale; the\n   * default is the same on the server and in the browser, so hydration matches.\n   * @default \"en-US\"\n   * @claim \"The BCP 47 locale for the\" registry/ouro/components/ouro/calendar/calendar.test.tsx verify:testExists(registry/ouro/components/ouro/calendar/calendar.test.tsx::Calendar > locale > names months, weekdays and days in the locale's language and digits)\n   * @claim \"The BCP 47 locale for the\" registry/ouro/components/ouro/calendar/calendar.test.tsx verify:testExists(registry/ouro/components/ouro/calendar/calendar.test.tsx::Calendar > locale > takes the first day of the week from the locale)\n   */\n  locale?: string | undefined;\n  /** The month shown first, as any ISO date in it. Without it, the selected date's month, or today's. */\n  defaultMonth?: string | undefined;\n  /**\n   * The previous month button's label. Translate it with your app.\n   * @default \"Previous month\"\n   */\n  previousMonthLabel?: string | undefined;\n  /**\n   * The next month button's label. Translate it with your app.\n   * @default \"Next month\"\n   */\n  nextMonthLabel?: string | undefined;\n  /**\n   * Layout only: margins and grid placement (`mt-4`). Appearance classes warn in\n   * development; the calendar takes its colors from your theme.\n   */\n  className?: string | undefined;\n  /** The calendar's root element. */\n  ref?: Ref<HTMLDivElement> | undefined;\n\n  /** Not a prop. Ouro UI uses `value`: `<Calendar value={date} onValueChange={setDate}>`. */\n  selected?: { 'Use value={date} onValueChange={setDate}': never };\n  /** Not a prop. Ouro UI uses `onValueChange`: `<Calendar value={date} onValueChange={setDate}>`. */\n  onSelect?: { 'Use value={date} onValueChange={setDate}': never };\n  /** Not a prop. Ouro UI uses `onValueChange`, which gets the ISO date: `<Calendar onValueChange={setDate}>`. */\n  onChange?: { 'Use onValueChange={setDate}; it gets the ISO date': never };\n  /** Not a prop. Ouro UI uses `min`: `<Calendar min=\"2026-10-11\">`. */\n  minDate?: { 'Use min=\"2026-10-11\"': never };\n  /** Not a prop. Ouro UI uses `max`: `<Calendar max=\"2026-12-31\">`. */\n  maxDate?: { 'Use max=\"2026-12-31\"': never };\n  /** Not a prop. The locale sets the first day of the week: `<Calendar locale=\"en-GB\">`, or `\"en-US-u-fw-mon\"`. */\n  weekStartsOn?: { 'The locale sets it: locale=\"en-GB\" or \"en-US-u-fw-mon\"': never };\n  /** Not a prop. Ouro UI uses `range` for a range; one day is the default: `<Calendar range>`. */\n  mode?: { 'Use <Calendar range> for a range; one day is the default': never };\n  /** Not a prop. Ouro UI uses `isDateDisabled`: `<Calendar isDateDisabled={(date) => booked.has(date)}>`. */\n  disabled?: { 'Use isDateDisabled={(date) => booked.has(date)}': never };\n}\n\n/** What a Calendar picks: an ISO date, or with `range` a {@link DateRange}. */\nexport type CalendarValue<Range extends boolean> = Range extends true ? DateRange : string;\n\n/**\n * Props for {@link Calendar}. `range` sets the mode: without it the value is one ISO date,\n * with it a `{ start, end }` range. A wrapper component should take `CalendarProps<false>` or\n * `CalendarProps<true>`; `ComponentProps<typeof Calendar>` loses the link between `range` and `value`.\n */\nexport type CalendarProps<Range extends boolean = false> = CalendarBaseProps & {\n  /**\n   * Picks a range: the first press sets the start, the second the end, and Escape drops a\n   * start. A range never spans an unavailable day: the preview and the end stop at the last\n   * available day before it, so a stay cannot include a booked night. Without `range` the\n   * calendar picks one day.\n   * @claim \"A range never spans an unavailable\" registry/ouro/components/ouro/calendar/calendar.test.tsx verify:testExists(registry/ouro/components/ouro/calendar/calendar.test.tsx::Calendar > range > never spans an unavailable day: the preview and the end stop before the first booked night)\n   */\n  range?: Range | undefined;\n  /**\n   * The picked day as an ISO date (`\"2026-10-11\"`, `\"\"` for none). With `range` it is the\n   * picked `{ start, end }` instead (`null` for none), and passing `{ start, end }` without\n   * `range` is a type error. Pass it with `onValueChange` to control the calendar.\n   * @claim \"The picked day as an ISO\" registry/ouro/components/ouro/calendar/calendar.test.tsx verify:testExists(registry/ouro/components/ouro/calendar/calendar.test.tsx::Calendar > one day > picks a pressed day, uncontrolled)\n   * @claim \"With `range` it is the picked\" registry/ouro/components/ouro/calendar/calendar.test.tsx verify:testExists(registry/ouro/components/ouro/calendar/calendar.test.tsx::Calendar > range > follows a controlled range and puts reversed ends in order)\n   * @claim \"With `range` it is the picked\" registry/ouro/components/ouro/calendar/calendar.test-d.ts verify:fileLine(registry/ouro/components/ouro/calendar/calendar.test-d.ts, /value:\\s\\{\\sstart:\\s\"2026-10-11\";\\send:\\s\"2026-10-12\"\\s\\}\\s\\}>\\(\\)\\.not\\.toExtend<CalendarProps>/)\n   */\n  value?: (Range extends true ? DateRange | null : string) | undefined;\n  /** What is picked at first, when you do not control `value`: an ISO date, or with `range` a `{ start, end }`. */\n  defaultValue?: (Range extends true ? DateRange | null : string) | undefined;\n  /** Called when the user picks: with the ISO date, or with `range` the `{ start, end }` in order once both ends are picked. */\n  onValueChange?: ((value: CalendarValue<Range>) => void) | undefined;\n};\n\n/** The calendar reads today once and does not follow midnight, so its subscription does nothing. */\nconst noSubscription = () => () => {};\n/**\n * The server does not know the user's zone, so it knows no today.\n *\n * @claim \"The server does not know the\" registry/ouro/components/ouro/calendar/calendar.test.tsx verify:testExists(registry/ouro/components/ouro/calendar/calendar.test.tsx::Calendar > today across hydration > renders no today on the server, and the browser fills in its own after hydration)\n */\nconst serverToday = (): string | null => null;\n\n/** Arrow keys move by these many days, in a left-to-right layout. */\nconst steps: Record<string, number> = { ArrowLeft: -1, ArrowRight: 1, ArrowUp: -7, ArrowDown: 7 };\n\n/** The range a value or a pending selection covers, ends in order. */\nfunction ordered(a: string, b: string): DateRange {\n  return a <= b ? { start: a, end: b } : { start: b, end: a };\n}\n\n/**\n * Icons drawn in the text color at 16px, like the other Ouro icons.\n *\n * @claim \"Icons drawn in the text color\" registry/ouro/components/ouro/calendar/calendar.tsx verify:fileLine(registry/ouro/components/ouro/calendar/calendar.tsx, /className=\"size-4 rtl:-scale-x-100\"/)\n * @claim \"Icons drawn in the text color\" registry/ouro/components/ouro/calendar/calendar.tsx verify:fileLine(registry/ouro/components/ouro/calendar/calendar.tsx, /stroke=\"currentColor\"/)\n */\nfunction Chevron({ children }: { children: ReactNode }): JSX.Element {\n  return (\n    <svg\n      aria-hidden=\"true\"\n      viewBox=\"0 0 16 16\"\n      fill=\"none\"\n      stroke=\"currentColor\"\n      strokeWidth=\"1.5\"\n      strokeLinecap=\"round\"\n      strokeLinejoin=\"round\"\n      className=\"size-4 rtl:-scale-x-100\"\n    >\n      {children}\n    </svg>\n  );\n}\n\n/**\n * A month grid to pick a day or a range of days, with the arrow keys or a press. It follows\n * the ARIA grid pattern: one Tab stop, arrows move by day and week, Home and End to the\n * week's ends, Page Up and Page Down by month (with Shift, by year), and Enter or Space\n * picks. Month and weekday names, digits and the first day of the week come from `locale`\n * through `Intl.DateTimeFormat`. Values are ISO dates (`\"2026-10-11\"`), the format a date\n * input submits.\n *\n * Use `DatePicker` instead for a date in a form: it is a labeled field that opens this\n * calendar on desktops and the phone's own picker on touch screens.\n *\n * @group Forms\n * @see https://ui.ouroboros.bot/docs/calendar\n *\n * @example\n * <Calendar label=\"Delivery date\" value={date} onValueChange={setDate} min=\"2026-10-11\" />\n * <Calendar label=\"Trip\" range value={trip} onValueChange={setTrip} locale=\"en-GB\" />\n * <Calendar label=\"Booking\" isDateDisabled={(date) => booked.has(date)} />\n */\nexport function Calendar<Range extends boolean = false>(props: CalendarProps<Range>): JSX.Element {\n  const {\n    label,\n    min,\n    max,\n    isDateDisabled,\n    locale = \"en-US\",\n    defaultMonth,\n    previousMonthLabel = \"Previous month\",\n    nextMonthLabel = \"Next month\",\n    className,\n    ref,\n    range,\n    value,\n    defaultValue,\n    onValueChange,\n    // Guard props (hint types), dropped here so they never reach the DOM.\n    selected: selectedGuess,\n    onSelect,\n    onChange,\n    minDate,\n    maxDate,\n    weekStartsOn,\n    mode,\n    disabled,\n  } = props as unknown as CalendarBaseProps & {\n    range?: boolean;\n    value?: string | DateRange | null;\n    defaultValue?: string | DateRange | null;\n    onValueChange?: (value: string | DateRange) => void;\n  };\n\n  useAppearanceClassNameCheck(\n    \"Calendar\",\n    className,\n    process.env.NODE_ENV !== \"production\" ? calendarHint(\"Calendar\") : /* istanbul ignore next @preserve -- production only */ \"\",\n  );\n  useDevWarnings(\n    \"Calendar\",\n    process.env.NODE_ENV !== \"production\"\n      ? () => {\n          const dates: Array<[string, unknown]> = [\n            [\"min\", min],\n            [\"max\", max],\n            [\"defaultMonth\", defaultMonth],\n          ];\n          for (const [prop, given] of [\n            [\"value\", value],\n            [\"defaultValue\", defaultValue],\n          ] as const) {\n            if (given && typeof given === \"object\") dates.push([`${prop}.start`, given.start], [`${prop}.end`, given.end]);\n            else dates.push([prop, given]);\n          }\n          return [\n            !label && [\"label is required; it names the calendar for screen readers\", '<Calendar label=\"Delivery date\">'],\n            ...dates.map(([prop, given]) => given !== undefined && given !== null && given !== \"\" && !isIsoDate(given) && isoWarning(\"Calendar\", prop, given)),\n            range === true && typeof (value ?? defaultValue) === \"string\" && [\n              \"a range takes { start, end }, not one date\",\n              '<Calendar range value={{ start: \"2026-10-11\", end: \"2026-10-14\" }}>',\n            ],\n            selectedGuess !== undefined && [\"selected is not a prop\", \"<Calendar value={date} onValueChange={setDate}>\"],\n            onSelect !== undefined && [\"onSelect is not a prop\", \"<Calendar value={date} onValueChange={setDate}>\"],\n            onChange !== undefined && [\"onChange is not a prop; onValueChange gets the ISO date\", \"<Calendar onValueChange={setDate}>\"],\n            minDate !== undefined && [\"minDate is not a prop\", '<Calendar min=\"2026-10-11\">'],\n            maxDate !== undefined && [\"maxDate is not a prop\", '<Calendar max=\"2026-12-31\">'],\n            weekStartsOn !== undefined && [\"weekStartsOn is not a prop; the locale sets the first day\", '<Calendar locale=\"en-GB\">, or locale=\"en-US-u-fw-mon\"'],\n            mode !== undefined && [\"mode is not a prop\", String(mode) === \"range\" ? \"<Calendar range>\" : \"<Calendar>, which picks one day\"],\n            disabled !== undefined && [\"disabled is not a prop\", \"<Calendar isDateDisabled={(date) => booked.has(date)}>\"],\n          ];\n        }\n      : /* istanbul ignore next @preserve -- production only */ undefined,\n  );\n\n  const isRange = range === true;\n  // Values that are not ISO dates (a dev warning) count as no value.\n  const clean = (given: string | DateRange | null | undefined): string | DateRange | null => {\n    if (isRange) return given && typeof given === \"object\" && isIsoDate(given.start) && isIsoDate(given.end) ? ordered(given.start, given.end) : null;\n    return isIsoDate(given) ? given : null;\n  };\n  const [own, setOwn] = useState(() => clean(defaultValue));\n  const controlled = value !== undefined;\n  const current = controlled ? clean(value) : own;\n  const picked = current === null ? null : typeof current === \"string\" ? { start: current, end: current } : current;\n\n  const low = isIsoDate(min) ? min : undefined;\n  const high = isIsoDate(max) ? max : undefined;\n  const clamp = (iso: string) => (low && iso < low ? low : high && iso > high ? high : iso);\n  const unavailable = (iso: string) => (low !== undefined && iso < low) || (high !== undefined && iso > high) || Boolean(isDateDisabled?.(iso));\n\n  // Today in the browser's zone. The server and hydration see `null`, so the server HTML marks\n  // no day as today and hydration matches wherever the server runs; the browser then fills it in.\n  const today = useSyncExternalStore(noSubscription, todayIso, serverToday);\n  // The day with the Tab stop; the month on show is its month. Without a value or\n  // `defaultMonth` it is today, so the server renders an empty month until hydration.\n  const [chosen, setFocused] = useState<string | null>(() => {\n    const start = isIsoDate(defaultMonth) ? monthStart(defaultMonth) : picked?.start;\n    return start === undefined ? null : clamp(start);\n  });\n  const focused = chosen ?? (today === null ? null : clamp(today));\n  // A new value from the app shows its month.\n  const pickedStart = picked?.start;\n  const [shownStart, setShownStart] = useState(pickedStart);\n  if (pickedStart !== shownStart) {\n    setShownStart(pickedStart);\n    if (pickedStart !== undefined && (focused === null || monthStart(pickedStart) !== monthStart(focused))) setFocused(pickedStart);\n  }\n\n  // A range's first press waits here for the second; the day under the pointer or focus previews the end.\n  const [anchor, setAnchor] = useState<string | null>(null);\n  const [preview, setPreview] = useState<string | null>(null);\n  // The preview is set with the anchor, so it is never null while there is one.\n  const shown = anchor !== null ? ordered(anchor, preview!) : picked;\n\n  const firstDay = useMemo(() => firstDayOfWeek(locale), [locale]);\n  const formats = useMemo(\n    () => ({\n      title: new Intl.DateTimeFormat(locale, { month: \"long\", year: \"numeric\", timeZone: \"UTC\" }),\n      day: new Intl.DateTimeFormat(locale, { day: \"numeric\", timeZone: \"UTC\" }),\n      full: new Intl.DateTimeFormat(locale, { weekday: \"long\", year: \"numeric\", month: \"long\", day: \"numeric\", timeZone: \"UTC\" }),\n      weekdayShort: new Intl.DateTimeFormat(locale, { weekday: \"short\", timeZone: \"UTC\" }),\n      weekdayLong: new Intl.DateTimeFormat(locale, { weekday: \"long\", timeZone: \"UTC\" }),\n    }),\n    [locale],\n  );\n  const utc = (iso: string) => new Date(`${iso}T00:00:00Z`);\n\n  const month = focused === null ? null : monthStart(focused);\n  const weeks = month === null ? [] : monthGrid(month, firstDay);\n  // 2023-01-01 was a Sunday: the header's days, from the first day of the week.\n  const weekdays = Array.from({ length: 7 }, (_, index) => utc(addDays(\"2023-01-01\", (firstDay + index) % 7)));\n  const canGoBack = month !== null && (!low || addDays(month, -1) >= low);\n  const canGoForward = month !== null && (!high || addMonths(month, 1) <= high);\n\n  const id = useId();\n  const titleId = `${id}-title`;\n  const gridRef = useRef<HTMLTableElement>(null);\n  // Set when a key moves the Tab stop, so the effect moves focus with it.\n  const moveFocus = useRef(false);\n  useEffect(() => {\n    if (!moveFocus.current) return;\n    moveFocus.current = false;\n    gridRef.current!.querySelector<HTMLElement>(`[data-ouro-day=\"${focused}\"]`)!.focus();\n  }, [focused]);\n\n  // The month buttons move the Tab stop a month. A button the move disables would drop\n  // focus to the page, so focus goes to the day instead.\n  const turn = (count: number) => {\n    const next = clamp(addMonths(focused!, count));\n    const shownMonth = monthStart(next);\n    if (count < 0 ? low && addDays(shownMonth, -1) < low : high && addMonths(shownMonth, 1) > high) moveFocus.current = true;\n    setFocused(next);\n  };\n\n  // A range never spans an unavailable day: from its start, it reaches toward `to` only up\n  // to the day before the first unavailable one.\n  const reach = (from: string, to: string) => {\n    const step = to >= from ? 1 : -1;\n    for (let day = from; day !== to; day = addDays(day, step)) {\n      if (unavailable(addDays(day, step))) return day;\n    }\n    return to;\n  };\n\n  const pick = (iso: string) => {\n    setFocused(iso);\n    if (unavailable(iso)) return;\n    if (!isRange) {\n      if (!controlled) setOwn(iso);\n      onValueChange?.(iso);\n      return;\n    }\n    if (anchor === null) {\n      setAnchor(iso);\n      setPreview(iso);\n      return;\n    }\n    const next = ordered(anchor, reach(anchor, iso));\n    setAnchor(null);\n    setPreview(null);\n    if (!controlled) setOwn(next);\n    onValueChange?.(next);\n  };\n\n  const onKeyDown = (event: KeyboardEvent<HTMLTableElement>) => {\n    if (event.key === \"Escape\" && anchor !== null) {\n      // Escape drops a range's pending start; with none, it is left to an enclosing popover.\n      event.preventDefault();\n      setAnchor(null);\n      setPreview(null);\n      return;\n    }\n    const day = (event.target as HTMLElement).dataset.ouroDay!;\n    const rtl = getComputedStyle(event.currentTarget).direction === \"rtl\";\n    let next: string | undefined;\n    if (Object.hasOwn(steps, event.key)) {\n      const step = steps[event.key]!;\n      next = addDays(day, rtl && Math.abs(step) === 1 ? -step : step);\n    } else if (event.key === \"Home\" || event.key === \"End\") {\n      const column = (utc(day).getUTCDay() - firstDay + 7) % 7;\n      next = addDays(day, event.key === \"Home\" ? -column : 6 - column);\n    } else if (event.key === \"PageUp\" || event.key === \"PageDown\") {\n      next = addMonths(day, (event.key === \"PageUp\" ? -1 : 1) * (event.shiftKey ? 12 : 1));\n    }\n    if (next === undefined) return;\n    event.preventDefault();\n    const target = clamp(next);\n    if (anchor !== null) setPreview(reach(anchor, target));\n    moveFocus.current = true;\n    setFocused(target);\n  };\n\n  return (\n    <div ref={ref} role=\"group\" aria-label={label} data-ouro=\"calendar\" className={cn(\"box-border inline-grid gap-2\", className)}>\n      <div data-ouro-calendar-header=\"\" className=\"flex items-center justify-between gap-2\">\n        <Button\n          variant=\"plain\"\n          tone=\"secondary\"\n          size=\"sm\"\n          aria-label={previousMonthLabel}\n          data-ouro-control=\"calendar\"\n          data-ouro-part=\"previous\"\n          disabled={!canGoBack}\n          className={navClass}\n          onClick={() => turn(-1)}\n        >\n          <Chevron>\n            <path d=\"M10 3.5L5.5 8l4.5 4.5\" />\n          </Chevron>\n        </Button>\n        <h2 id={titleId} aria-live=\"polite\" className=\"m-0 text-sm leading-5 font-medium text-foreground\">\n          {month === null ? null : formats.title.format(utc(month))}\n        </h2>\n        <Button\n          variant=\"plain\"\n          tone=\"secondary\"\n          size=\"sm\"\n          aria-label={nextMonthLabel}\n          data-ouro-control=\"calendar\"\n          data-ouro-part=\"next\"\n          disabled={!canGoForward}\n          className={navClass}\n          onClick={() => turn(1)}\n        >\n          <Chevron>\n            <path d=\"M6 3.5L10.5 8 6 12.5\" />\n          </Chevron>\n        </Button>\n      </div>\n      <table\n        ref={gridRef}\n        role=\"grid\"\n        aria-labelledby={titleId}\n        aria-multiselectable={isRange || undefined}\n        className=\"m-0 border-collapse border-spacing-0\"\n        onKeyDown={onKeyDown}\n        onPointerLeave={() => anchor !== null && setPreview(anchor)}\n      >\n        <thead>\n          <tr>\n            {weekdays.map((date) => (\n              <th key={date.getUTCDay()} scope=\"col\" abbr={formats.weekdayLong.format(date)} className={weekdayHeaderClass}>\n                {formats.weekdayShort.format(date)}\n              </th>\n            ))}\n          </tr>\n        </thead>\n        <tbody>\n          {weeks.map((week) => (\n            <tr key={week.find(Boolean)!}>\n              {week.map((day, index) => {\n                if (day === null) return <td key={`blank-${index}`} className=\"p-0\" />;\n                const off = unavailable(day);\n                const ends = shown !== null && (day === shown.start || day === shown.end);\n                const inside = shown !== null && day > shown.start && day < shown.end;\n                return (\n                  <td key={day} role=\"gridcell\" aria-selected={ends || inside} className=\"p-0 text-center\">\n                    <button\n                      type=\"button\"\n                      data-ouro-day={day}\n                      data-ouro-control=\"calendar\"\n                      data-ouro-part=\"day\"\n                      tabIndex={day === focused ? 0 : -1}\n                      aria-label={formats.full.format(utc(day))}\n                      aria-current={day === today ? \"date\" : undefined}\n                      aria-disabled={off || undefined}\n                      {...(ends ? { \"data-selected\": \"true\" } : {})}\n                      {...(inside ? { \"data-in-range\": \"\" } : {})}\n                      className={dayClass}\n                      onClick={() => pick(day)}\n                      onPointerEnter={() => anchor !== null && setPreview(reach(anchor, day))}\n                      onFocus={() => anchor !== null && setPreview(reach(anchor, day))}\n                    >\n                      {formats.day.format(utc(day))}\n                    </button>\n                  </td>\n                );\n              })}\n            </tr>\n          ))}\n        </tbody>\n      </table>\n    </div>\n  );\n}\n",
      "type": "registry:ui",
      "target": "@components/ouro/calendar/calendar.tsx"
    }
  ],
  "docs": "A month grid to pick a day or a range of days, with the arrow keys or a press. Import: import { Calendar } from \"@/components/ouro/calendar/calendar\", with @/components replaced by your components alias (aliases.components in components.json, such as ~/components). Also installed: button, the helpers they import in lib/ouro. Needs ouro-base in your stylesheet: add that item once per app, from the same place as this one, if you have not. Docs: https://ui.ouroboros.bot/docs/calendar.md Ouro UI v1.3.257.",
  "type": "registry:ui"
}