{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "calendar",
  "type": "registry:ui",
  "title": "Calendar",
  "description": "One month of days to pick one from: the date grid of a booking page, a date field's popup, a \"when\" step. Days are plain `YYYY-MM-DD` strings (see `calendar-model`), so the day a reader picks is the day the server stores, in every time zone.",
  "author": "ofri-peretz <https://github.com/ofri-peretz>",
  "categories": [
    "form",
    "primitive"
  ],
  "dependencies": [
    "lucide-react"
  ],
  "registryDependencies": [
    "https://ds.interlace.tools/r/interlace-base.json",
    "https://ds.interlace.tools/r/button.json",
    "https://ds.interlace.tools/r/cn.json",
    "https://ds.interlace.tools/r/motion-token.json",
    "https://ds.interlace.tools/r/use-reduced-motion.json"
  ],
  "files": [
    {
      "path": "registry/interlace-ui/calendar.tsx",
      "target": "components/ui/calendar.tsx",
      "type": "registry:ui",
      "content": "'use client';\n\nimport * as React from 'react';\n\n// @interlace/calendar v1.1.2 — Interlace design system.\n// Docs, props and live preview: https://ds.interlace.tools/c/calendar\n// What changed since: https://ds.interlace.tools/c/calendar#history\n// Generated banner — keep it, the upgrade diff reads this version.\n\n/**\n * @interlace/ui — Calendar\n *\n * One month of days to pick one from: the date grid of a booking page, a\n * date field's popup, a \"when\" step. Days are plain `YYYY-MM-DD` strings\n * (see `calendar-model`), so the day a reader picks is the day the server\n * stores, in every time zone.\n *\n * Base UI ships no calendar, so this is the WAI-ARIA date grid built on a\n * real table: `role=\"grid\"`, one tab stop (roving tabindex), the arrows,\n * Home / End and Page Up / Page Down. The month and the days are named\n * through `Intl.DateTimeFormat` in `locale`, and the week starts where the\n * locale starts it.\n * Pattern: https://www.w3.org/WAI/ARIA/apg/patterns/dialog-modal/examples/datepicker-dialog/\n * Visual canon: shadcn's Calendar, with Cal.com's habit of marking the days\n * that have room.\n *\n * ## Anatomy\n *\n *   Calendar                       (div — data-slot=\"calendar\", data-min-viewport=320)\n *     ├─ header                    (data-slot=\"calendar-header\")\n *     │   ├─ Button                (data-slot=\"calendar-previous\", aria-label)\n *     │   ├─ caption               (data-slot=\"calendar-caption\", aria-live=\"polite\")\n *     │   └─ Button                (data-slot=\"calendar-next\", aria-label)\n *     └─ table role=\"grid\"         (data-slot=\"calendar-grid\", aria-labelledby → caption)\n *         ├─ thead th × 7          (data-slot=\"calendar-weekday\", abbr = full name)\n *         └─ tbody tr × 6          (always six weeks, so the height never changes)\n *             └─ td role=gridcell  (aria-selected on the picked day)\n *                 └─ button        (data-slot=\"calendar-day\", data-state, aria-label = full date)\n *\n * Days of the neighbouring months are empty cells: the reader picks from\n * one month at a time, and the keyboard walks into the next month anyway.\n *\n * ## Keyboard\n *\n * | Key                    | Action                                              |\n * | ---------------------- | --------------------------------------------------- |\n * | Tab                    | Into the grid, on the picked day (else today, else the first open day) |\n * | ← / →                  | Previous / next day, following the reading direction |\n * | ↑ / ↓                  | Same day of the previous / next week                |\n * | Home / End             | First / last day of the week                        |\n * | Page Up / Page Down    | Same day of the previous / next month               |\n * | Shift + Page Up / Down | Same day of the previous / next year                |\n * | Enter / Space          | Pick the focused day                                |\n *\n * Focus never leaves `[min, max]`. An unavailable day can take focus (so the\n * reader hears that it is closed), but cannot be picked.\n *\n * ## Day states\n *\n * | State       | Look                                   | In words (aria-label)        |\n * | ----------- | -------------------------------------- | ---------------------------- |\n * | open        | plain number                           | the full date                |\n * | marked      | a dot under the number                 | + `labels.marked`            |\n * | today       | semibold, `text-primary`, a short bar  | + `labels.today`, `aria-current=\"date\"` |\n * | selected    | `bg-primary` fill                      | `aria-selected` on the cell  |\n * | unavailable | muted and struck through               | + `labels.unavailable`       |\n * | outside     | before `min` / after `max`: faded      | + `labels.unavailable`       |\n *\n * Colour only ever repeats a shape or the words.\n *\n * ## Motion\n *\n * Changing month slides the weeks in from the side they came from (200ms,\n * `--ease-enter`, transform and opacity, Web Animations API), mirrored in\n * RTL. Under reduced motion the new month is simply there. The grid keeps\n * six rows, so nothing below it moves.\n *\n * ## MIN_VIEWPORT — 320\n *\n * The seven columns share the width (`table-fixed`) and each day is a\n * square up to 2.75rem, so the month fits a 288px column and still fits at\n * 150% text.\n *\n * | Rule | Concept                          | Where in this file                                         |\n * | ---- | -------------------------------- | ---------------------------------------------------------- |\n * | R4   | Extends native el                | `React.ComponentProps<'div'>`                              |\n * | R6   | data-slot per part               | calendar / -header / -caption / -grid / -weekday / -day    |\n * | R7   | cn + ...rest                     | `cn(…, className)` + `{...props}`                          |\n * | R9   | Controlled + uncontrolled        | `value` / `defaultValue`, `month` / `defaultMonth`         |\n * | R14  | Declares min viewport            | `data-min-viewport` + exported const                       |\n * | R19  | Tokens only                      | `bg-primary`, `text-muted-foreground`, `ring-ring`, `--ease-enter` |\n * | R25  | Client component                 | focus, keyboard and the month slide                        |\n * | R26  | A11y                             | APG date grid; full date, today and state in words         |\n */\n\nimport { ChevronLeftIcon, ChevronRightIcon } from 'lucide-react';\n\nimport { cn } from '@/lib/utils';\nimport { useReducedMotion } from '@/hooks/use-reduced-motion';\nimport { motionEase } from '@/lib/motion-token';\nimport { Button } from '@/components/ui/button';\nimport {\n  addMonths,\n  type CalendarDate,\n  clampDate,\n  type DateBounds,\n  endOfMonth,\n  firstEnabledInMonth,\n  isDateDisabled,\n  isGridKey,\n  isOutOfRange,\n  isSameMonth,\n  monthGrid,\n  moveFocus,\n  startOfMonth,\n  todayIn,\n  toUtcDate,\n  weekdayOrder,\n  type Weekday,\n  weekStartFor,\n} from '@/components/ui/calendar-model';\n\nexport const MIN_VIEWPORT = 320 as const;\n\nexport interface CalendarLabels {\n  /** @default 'Previous month' */\n  previousMonth?: string;\n  /** @default 'Next month' */\n  nextMonth?: string;\n  /** Said after the date of today. @default 'Today' */\n  today?: string;\n  /** Said after a day that cannot be picked. @default 'Unavailable' */\n  unavailable?: string;\n  /** Said after a marked day, e.g. 'Times available'. @default 'Marked' */\n  marked?: string;\n}\n\nconst DEFAULT_LABELS: Required<CalendarLabels> = {\n  previousMonth: 'Previous month',\n  nextMonth: 'Next month',\n  today: 'Today',\n  unavailable: 'Unavailable',\n  marked: 'Marked',\n};\n\ntype CalendarProps = Omit<React.ComponentProps<'div'>, 'defaultValue' | 'onChange'> & {\n  /** The picked day, controlled. `null` for none. */\n  value?: CalendarDate | null;\n  /** The picked day, uncontrolled. */\n  defaultValue?: CalendarDate | null;\n  /** Fires with the day the reader picks. */\n  onValueChange?: (date: CalendarDate) => void;\n  /** Any day of the month on show, controlled. */\n  month?: CalendarDate;\n  /** Any day of the month to open on. @default the picked day, else today */\n  defaultMonth?: CalendarDate;\n  /** Fires with the first day of the month the reader moved to. */\n  onMonthChange?: (month: CalendarDate) => void;\n  /** First day that can be picked. Days before it are not offered. */\n  min?: CalendarDate;\n  /** Last day that can be picked. */\n  max?: CalendarDate;\n  /** A day inside the range that cannot be picked: full, closed, a holiday. */\n  isDateUnavailable?: (date: CalendarDate) => boolean;\n  /** A day to mark with a dot, e.g. one with open times. */\n  isDateMarked?: (date: CalendarDate) => boolean;\n  /**\n   * Today. Pass it from the server (in the venue's time zone) so the server\n   * HTML and the browser agree. @default today in `timeZone`\n   */\n  today?: CalendarDate;\n  /** Time zone for working out today. @default the browser's */\n  timeZone?: string;\n  /** BCP 47 locale for month, weekday and day names. @default the browser's */\n  locale?: string;\n  /** First column. @default the locale's first day of the week */\n  weekStartsOn?: Weekday;\n  /** Every word the calendar says, for translation. */\n  labels?: CalendarLabels;\n};\n\ntype DayState = 'open' | 'today' | 'selected' | 'unavailable' | 'outside';\n\nfunction dayState(\n  date: CalendarDate,\n  ctx: {\n    bounds: DateBounds;\n    value: CalendarDate | null;\n    today: CalendarDate;\n    isDateMarked?: (date: CalendarDate) => boolean;\n  },\n) {\n  const outside = isOutOfRange(date, ctx.bounds);\n  const disabled = outside || isDateDisabled(date, ctx.bounds);\n  const selected = ctx.value === date;\n  const isToday = date === ctx.today;\n  const marked = !disabled && Boolean(ctx.isDateMarked?.(date));\n  let state: DayState = 'open';\n  if (selected) state = 'selected';\n  else if (outside) state = 'outside';\n  else if (disabled) state = 'unavailable';\n  else if (isToday) state = 'today';\n  return { disabled, selected, isToday, marked, state };\n}\n\n/** Reading direction from the nearest `dir`, as `:dir()` resolves it. */\nfunction isRtl(el: Element): boolean {\n  return el.closest('[dir]')?.getAttribute('dir') === 'rtl';\n}\n\nfunction useControllable<T>(\n  controlled: T | undefined,\n  initial: T,\n  onChange?: (value: T) => void,\n): [T, (next: T) => void] {\n  const [inner, setInner] = React.useState(initial);\n  const value = controlled !== undefined ? controlled : inner;\n  const set = React.useCallback(\n    (next: T) => {\n      if (controlled === undefined) setInner(next);\n      onChange?.(next);\n    },\n    [controlled, onChange],\n  );\n  return [value, set];\n}\n\nconst Calendar = React.forwardRef<HTMLDivElement, CalendarProps>(function Calendar(\n  {\n    value: valueProp,\n    defaultValue = null,\n    onValueChange,\n    month: monthProp,\n    defaultMonth,\n    onMonthChange,\n    min,\n    max,\n    isDateUnavailable,\n    isDateMarked,\n    today: todayProp,\n    timeZone,\n    locale,\n    weekStartsOn: weekStartsOnProp,\n    labels: labelsProp,\n    className,\n    ...props\n  },\n  ref,\n) {\n  const labels = { ...DEFAULT_LABELS, ...labelsProp };\n  const [fallbackToday] = React.useState(() => todayIn(timeZone));\n  const today = todayProp ?? fallbackToday;\n  const weekStartsOn = weekStartsOnProp ?? weekStartFor(locale);\n  const bounds = React.useMemo(\n    () => ({ min, max, isDateUnavailable }),\n    [min, max, isDateUnavailable],\n  );\n\n  const [value, setValue] = useControllable<CalendarDate | null>(valueProp, defaultValue, (d) => {\n    if (d) onValueChange?.(d);\n  });\n  const [monthRaw, setMonthRaw] = useControllable<CalendarDate>(\n    monthProp,\n    startOfMonth(clampDate(defaultMonth ?? value ?? today, min, max)),\n    onMonthChange,\n  );\n  const month = startOfMonth(monthRaw);\n\n  // The day that holds the grid's one tab stop. Kept only while it is in\n  // the month on show; otherwise the stop falls back as documented above.\n  const [focused, setFocused] = React.useState<CalendarDate | null>(null);\n  const focusOnRender = React.useRef(false);\n  const slide = React.useRef<0 | 1 | -1>(0);\n\n  const tabStop = React.useMemo(() => {\n    if (focused && isSameMonth(focused, month)) return focused;\n    if (value && isSameMonth(value, month) && !isOutOfRange(value, bounds)) return value;\n    if (isSameMonth(today, month) && !isDateDisabled(today, bounds)) return today;\n    const firstInRange = clampDate(month, min, max);\n    if (!isSameMonth(firstInRange, month)) return null;\n    return firstEnabledInMonth(firstInRange, bounds) ?? firstInRange;\n  }, [focused, month, value, today, min, max, bounds]);\n\n  const gridRef = React.useRef<HTMLTableElement>(null);\n  const bodyRef = React.useRef<HTMLTableSectionElement>(null);\n  const reduced = useReducedMotion();\n\n  React.useEffect(() => {\n    if (!focusOnRender.current) return;\n    focusOnRender.current = false;\n    const target = gridRef.current?.querySelector<HTMLButtonElement>(`[data-date=\"${tabStop}\"]`);\n    target?.focus();\n  }, [tabStop, month]);\n\n  React.useLayoutEffect(() => {\n    const dir = slide.current;\n    slide.current = 0;\n    const body = bodyRef.current;\n    if (!dir || reduced || !body || typeof body.animate !== 'function') return;\n    const rtl = isRtl(body);\n    const from = `${(rtl ? -dir : dir) * 0.75}rem`;\n    body.animate(\n      [\n        { transform: `translateX(${from})`, opacity: 0 },\n        { transform: 'translateX(0)', opacity: 1 },\n      ],\n      { duration: 200, easing: motionEase(body, 'enter') },\n    );\n  }, [month, reduced]);\n\n  const goToMonth = (next: CalendarDate) => {\n    const target = startOfMonth(next);\n    if (target === month) return;\n    slide.current = target > month ? 1 : -1;\n    setMonthRaw(target);\n  };\n\n  const canGoBack = !min || startOfMonth(min) < month;\n  const canGoForward = !max || endOfMonth(max) > endOfMonth(month);\n\n  // Built once per locale, not on every arrow key.\n  const fmt = React.useMemo(() => {\n    const make = (o: Intl.DateTimeFormatOptions) =>\n      new Intl.DateTimeFormat(locale, { ...o, timeZone: 'UTC' });\n    return {\n      caption: make({ month: 'long', year: 'numeric' }),\n      day: make({ day: 'numeric' }),\n      full: make({ dateStyle: 'full' }),\n      weekdayShort: make({ weekday: 'short' }),\n      weekdayLong: make({ weekday: 'long' }),\n    };\n  }, [locale]);\n  // 2023-01-01 was a Sunday: weekday n is 1 + n January 2023.\n  const weekdayDate = (d: Weekday) => toUtcDate(`2023-01-0${d + 1}`);\n\n  const captionId = React.useId();\n  const weeks = monthGrid(month, weekStartsOn);\n\n  const pick = (date: CalendarDate) => {\n    if (isDateDisabled(date, bounds)) return;\n    setFocused(date);\n    setValue(date);\n  };\n\n  const onDayKeyDown = (event: React.KeyboardEvent<HTMLButtonElement>, date: CalendarDate) => {\n    if (!isGridKey(event.key)) return;\n    event.preventDefault();\n    const rtl = isRtl(event.currentTarget);\n    const next = moveFocus(date, event.key, {\n      weekStartsOn,\n      rtl,\n      shift: event.shiftKey,\n      min,\n      max,\n    });\n    focusOnRender.current = true;\n    setFocused(next);\n    if (!isSameMonth(next, month)) goToMonth(next);\n    else if (next === date) {\n      focusOnRender.current = false;\n    } else {\n      // Same month: move focus now, no re-render of the month needed.\n      gridRef.current?.querySelector<HTMLButtonElement>(`[data-date=\"${next}\"]`)?.focus();\n      focusOnRender.current = false;\n    }\n  };\n\n  return (\n    <div\n      ref={ref}\n      data-slot=\"calendar\"\n      data-min-viewport={String(MIN_VIEWPORT)}\n      className={cn('w-full max-w-96 text-foreground', className)}\n      {...props}\n    >\n      <div data-slot=\"calendar-header\" className=\"flex items-center justify-between gap-2 pb-3\">\n        <Button\n          type=\"button\"\n          variant=\"ghost\"\n          size=\"icon\"\n          data-slot=\"calendar-previous\"\n          aria-label={labels.previousMonth}\n          disabled={!canGoBack}\n          onClick={() => goToMonth(addMonths(month, -1))}\n        >\n          <ChevronLeftIcon aria-hidden=\"true\" className=\"rtl:rotate-180\" />\n        </Button>\n        <div\n          id={captionId}\n          data-slot=\"calendar-caption\"\n          aria-live=\"polite\"\n          className=\"min-w-0 truncate text-center text-sm font-semibold\"\n        >\n          {fmt.caption.format(toUtcDate(month))}\n        </div>\n        <Button\n          type=\"button\"\n          variant=\"ghost\"\n          size=\"icon\"\n          data-slot=\"calendar-next\"\n          aria-label={labels.nextMonth}\n          disabled={!canGoForward}\n          onClick={() => goToMonth(addMonths(month, 1))}\n        >\n          <ChevronRightIcon aria-hidden=\"true\" className=\"rtl:rotate-180\" />\n        </Button>\n      </div>\n      <table\n        ref={gridRef}\n        role=\"grid\"\n        aria-labelledby={captionId}\n        data-slot=\"calendar-grid\"\n        className=\"w-full table-fixed border-collapse\"\n      >\n        <thead>\n          <tr>\n            {weekdayOrder(weekStartsOn).map((d) => (\n              <th\n                key={d}\n                scope=\"col\"\n                abbr={fmt.weekdayLong.format(weekdayDate(d))}\n                data-slot=\"calendar-weekday\"\n                className=\"text-muted-foreground pb-1 text-xs font-normal\"\n              >\n                {fmt.weekdayShort.format(weekdayDate(d))}\n              </th>\n            ))}\n          </tr>\n        </thead>\n        <tbody ref={bodyRef}>\n          {weeks.map((week) => (\n            <tr key={week[0]}>\n              {week.map((date) => {\n                if (!isSameMonth(date, month)) {\n                  return <td key={date} role=\"gridcell\" className=\"p-0.5\" />;\n                }\n                const { disabled, selected, isToday, marked, state } = dayState(date, {\n                  bounds,\n                  value,\n                  today,\n                  isDateMarked,\n                });\n                const name = [\n                  fmt.full.format(toUtcDate(date)),\n                  isToday && labels.today,\n                  disabled && labels.unavailable,\n                  marked && labels.marked,\n                ]\n                  .filter(Boolean)\n                  .join(', ');\n                return (\n                  <td\n                    key={date}\n                    role=\"gridcell\"\n                    aria-selected={selected || undefined}\n                    className=\"p-0.5\"\n                  >\n                    <button\n                      type=\"button\"\n                      data-slot=\"calendar-day\"\n                      data-date={date}\n                      data-state={state}\n                      data-today={isToday || undefined}\n                      data-marked={marked || undefined}\n                      tabIndex={date === tabStop ? 0 : -1}\n                      aria-label={name}\n                      aria-current={isToday ? 'date' : undefined}\n                      aria-disabled={disabled || undefined}\n                      onClick={() => pick(date)}\n                      onKeyDown={(e) => onDayKeyDown(e, date)}\n                      onFocus={() => setFocused(date)}\n                      className={cn(\n                        'relative mx-auto flex aspect-square w-full max-w-11 min-w-0 items-center justify-center rounded-lg text-sm tabular-nums focus-visible:outline-hidden',\n                        'transition-[color,background-color,box-shadow,scale] duration-(--duration-fast) ease-enter',\n                        'focus-visible:ring-ring focus-visible:ring-2 focus-visible:ring-offset-2 focus-visible:ring-offset-background',\n                        state === 'open' && 'hover:bg-accent hover:text-accent-foreground',\n                        state === 'today' &&\n                          'text-primary font-semibold hover:bg-accent hover:text-accent-foreground',\n                        state === 'selected' &&\n                          'bg-primary text-primary-foreground font-semibold motion-safe:active:scale-[0.97]',\n                        state === 'unavailable' &&\n                          'text-muted-foreground cursor-not-allowed line-through decoration-from-font',\n                        state === 'outside' && 'text-muted-foreground cursor-not-allowed opacity-60',\n                        (state === 'open' || state === 'today') && 'motion-safe:active:scale-[0.97]',\n                      )}\n                    >\n                      {fmt.day.format(toUtcDate(date))}\n                      {(marked || isToday) && (\n                        <span\n                          aria-hidden=\"true\"\n                          data-slot=\"calendar-day-mark\"\n                          className={cn(\n                            'absolute bottom-1 start-1/2 h-1 -translate-x-1/2 rounded-full rtl:translate-x-1/2',\n                            isToday && !marked ? 'w-3' : 'w-1',\n                            selected ? 'bg-primary-foreground' : 'bg-primary',\n                          )}\n                        />\n                      )}\n                    </button>\n                  </td>\n                );\n              })}\n            </tr>\n          ))}\n        </tbody>\n      </table>\n    </div>\n  );\n});\n\nexport { Calendar };\nexport type { CalendarProps };\nexport type { CalendarDate, Weekday } from '@/components/ui/calendar-model';\n"
    },
    {
      "path": "registry/interlace-ui/calendar-model.ts",
      "target": "components/ui/calendar-model.ts",
      "type": "registry:ui",
      "content": "export type CalendarDate = string;\n\n/** 0 is Sunday, 1 is Monday … 6 is Saturday, as `Date#getUTCDay`. */\nexport type Weekday = 0 | 1 | 2 | 3 | 4 | 5 | 6;\n\nconst ISO_RE = /^(\\d{4})-(\\d{2})-(\\d{2})$/;\n\n/** True when `value` is a real `YYYY-MM-DD` day (no 31 April). */\nexport function isCalendarDate(value: unknown): value is CalendarDate {\n  if (typeof value !== 'string') return false;\n  const m = ISO_RE.exec(value);\n  if (!m) return false;\n  const [y, mo, d] = [Number(m[1]), Number(m[2]), Number(m[3])];\n  if (mo < 1 || mo > 12 || d < 1) return false;\n  return d <= daysInMonth(y, mo);\n}\n\nfunction parts(date: CalendarDate): [number, number, number] {\n  const m = ISO_RE.exec(date);\n  if (!m) throw new RangeError(`Not a YYYY-MM-DD date: ${date}`);\n  return [Number(m[1]), Number(m[2]), Number(m[3])];\n}\n\nfunction pad(n: number, width = 2): string {\n  return String(n).padStart(width, '0');\n}\n\n/** Build a `YYYY-MM-DD` from a year, a 1-based month and a day. */\nexport function toCalendarDate(year: number, month: number, day: number): CalendarDate {\n  return `${pad(year, 4)}-${pad(month)}-${pad(day)}`;\n}\n\n/** Days in a 1-based month. */\nexport function daysInMonth(year: number, month: number): number {\n  return new Date(Date.UTC(year, month, 0)).getUTCDate();\n}\n\nfunction fromUtc(ms: number): CalendarDate {\n  const d = new Date(ms);\n  return toCalendarDate(d.getUTCFullYear(), d.getUTCMonth() + 1, d.getUTCDate());\n}\n\nfunction toUtc(date: CalendarDate): number {\n  const [y, m, d] = parts(date);\n  return Date.UTC(y, m - 1, d);\n}\n\n/**\n * A UTC-midnight `Date` for the day, for handing to `Intl.DateTimeFormat`\n * with `timeZone: 'UTC'`. Never show it in a local zone.\n */\nexport function toUtcDate(date: CalendarDate): Date {\n  return new Date(toUtc(date));\n}\n\n/** The weekday of a day. */\nexport function weekdayOf(date: CalendarDate): Weekday {\n  return new Date(toUtc(date)).getUTCDay() as Weekday;\n}\n\n/** The day `n` days later (or earlier, for a negative `n`). */\nexport function addDays(date: CalendarDate, n: number): CalendarDate {\n  return fromUtc(toUtc(date) + n * 86_400_000);\n}\n\n/**\n * The same day `n` months later, kept inside the month: 31 January plus one\n * month is 28 or 29 February, never 3 March.\n */\nexport function addMonths(date: CalendarDate, n: number): CalendarDate {\n  const [y, m, d] = parts(date);\n  const index = y * 12 + (m - 1) + n;\n  const year = Math.floor(index / 12);\n  const month = index - year * 12 + 1;\n  return toCalendarDate(year, month, Math.min(d, daysInMonth(year, month)));\n}\n\n/** The first day of the day's month. */\nexport function startOfMonth(date: CalendarDate): CalendarDate {\n  return `${date.slice(0, 7)}-01`;\n}\n\n/** The last day of the day's month. */\nexport function endOfMonth(date: CalendarDate): CalendarDate {\n  const [y, m] = parts(date);\n  return toCalendarDate(y, m, daysInMonth(y, m));\n}\n\n/** Both days fall in the same month of the same year. */\nexport function isSameMonth(a: CalendarDate, b: CalendarDate): boolean {\n  return a.slice(0, 7) === b.slice(0, 7);\n}\n\n/** -1, 0 or 1. `YYYY-MM-DD` sorts as text, so this is a string compare. */\nexport function compareDates(a: CalendarDate, b: CalendarDate): -1 | 0 | 1 {\n  return a < b ? -1 : a > b ? 1 : 0;\n}\n\n/** The day within `[min, max]`; either bound may be left out. */\nexport function clampDate(date: CalendarDate, min?: CalendarDate, max?: CalendarDate): CalendarDate {\n  if (min && date < min) return min;\n  if (max && date > max) return max;\n  return date;\n}\n\n/** The first day of the week that holds `date`. */\nexport function startOfWeek(date: CalendarDate, weekStartsOn: Weekday): CalendarDate {\n  return addDays(date, -((weekdayOf(date) - weekStartsOn + 7) % 7));\n}\n\n/** The last day of the week that holds `date`. */\nexport function endOfWeek(date: CalendarDate, weekStartsOn: Weekday): CalendarDate {\n  return addDays(startOfWeek(date, weekStartsOn), 6);\n}\n\n/**\n * The month as six weeks of seven days, starting on `weekStartsOn`, with the\n * neighbouring months' days filling the edges. Always six rows, so the grid\n * keeps its height from one month to the next and nothing below it moves.\n */\nexport function monthGrid(month: CalendarDate, weekStartsOn: Weekday): CalendarDate[][] {\n  const first = startOfWeek(startOfMonth(month), weekStartsOn);\n  return Array.from({ length: 6 }, (_, w) =>\n    Array.from({ length: 7 }, (_, d) => addDays(first, w * 7 + d)),\n  );\n}\n\n/** The seven weekdays in grid order, starting on `weekStartsOn`. */\nexport function weekdayOrder(weekStartsOn: Weekday): Weekday[] {\n  return Array.from({ length: 7 }, (_, i) => ((weekStartsOn + i) % 7) as Weekday);\n}\n\n/**\n * Regions whose calendars start the week on Sunday or Saturday, for runtimes\n * without `Intl.Locale#getWeekInfo`. Everyone else starts on Monday (ISO 8601).\n * From CLDR's `firstDay` supplemental data.\n */\nconst SUNDAY_REGIONS = new Set([\n  'AG', 'AS', 'BD', 'BR', 'BS', 'BT', 'BW', 'BZ', 'CA', 'CN', 'CO', 'DM', 'DO', 'ET', 'GT', 'GU',\n  'HK', 'HN', 'ID', 'IL', 'IN', 'JM', 'JP', 'KE', 'KH', 'KR', 'LA', 'MH', 'MM', 'MO', 'MT', 'MX',\n  'MZ', 'NI', 'NP', 'PA', 'PE', 'PH', 'PK', 'PR', 'PT', 'PY', 'SA', 'SG', 'SV', 'TH', 'TT', 'TW',\n  'UM', 'US', 'VE', 'VI', 'WS', 'YE', 'ZA', 'ZW',\n]);\nconst SATURDAY_REGIONS = new Set(['AE', 'AF', 'BH', 'DJ', 'DZ', 'EG', 'IQ', 'IR', 'JO', 'KW', 'LY', 'OM', 'QA', 'SD', 'SY']);\n\ninterface WeekInfoLocale {\n  getWeekInfo?: () => { firstDay: number };\n  weekInfo?: { firstDay: number };\n  maximize: () => Intl.Locale;\n}\n\n/**\n * The first day of the week for a locale: `Intl.Locale#getWeekInfo` where the\n * runtime has it, else the CLDR region table above. `en-US` is Sunday,\n * `en-GB` Monday, `ar-EG` Saturday.\n */\nexport function weekStartFor(locale?: string): Weekday {\n  let loc: WeekInfoLocale;\n  try {\n    loc = new Intl.Locale(locale ?? new Intl.DateTimeFormat().resolvedOptions().locale) as unknown as WeekInfoLocale;\n  } catch {\n    return 1;\n  }\n  const info = loc.getWeekInfo?.() ?? loc.weekInfo;\n  if (info) return (info.firstDay % 7) as Weekday;\n  const region = String(loc.maximize().region);\n  if (SUNDAY_REGIONS.has(region)) return 0;\n  if (SATURDAY_REGIONS.has(region)) return 6;\n  return 1;\n}\n\n/** Today as a `YYYY-MM-DD` in a time zone (the runtime's own when left out). */\nexport function todayIn(timeZone?: string, now: Date = new Date()): CalendarDate {\n  const fmt = new Intl.DateTimeFormat('en-CA', {\n    timeZone,\n    year: 'numeric',\n    month: '2-digit',\n    day: '2-digit',\n  });\n  const part = Object.fromEntries(fmt.formatToParts(now).map((p) => [p.type, p.value]));\n  return `${part.year}-${part.month}-${part.day}`;\n}\n\nexport interface DateBounds {\n  min?: CalendarDate;\n  max?: CalendarDate;\n  /** A day that is inside the bounds but cannot be picked: full, closed, a holiday. */\n  isDateUnavailable?: (date: CalendarDate) => boolean;\n}\n\n/** Outside `[min, max]`: not shown as a choice at all. */\nexport function isOutOfRange(date: CalendarDate, { min, max }: DateBounds): boolean {\n  return (min !== undefined && date < min) || (max !== undefined && date > max);\n}\n\n/** The day cannot be picked, for either reason. */\nexport function isDateDisabled(date: CalendarDate, bounds: DateBounds): boolean {\n  return isOutOfRange(date, bounds) || Boolean(bounds.isDateUnavailable?.(date));\n}\n\n/** The first day from `from` (inclusive) to the end of its month that can be picked, or null. */\nexport function firstEnabledInMonth(from: CalendarDate, bounds: DateBounds): CalendarDate | null {\n  const end = endOfMonth(from);\n  for (let d = from; d <= end; d = addDays(d, 1)) {\n    if (!isDateDisabled(d, bounds)) return d;\n  }\n  return null;\n}\n\n/** The keys the date grid answers to. */\nexport type GridKey =\n  | 'ArrowLeft'\n  | 'ArrowRight'\n  | 'ArrowUp'\n  | 'ArrowDown'\n  | 'Home'\n  | 'End'\n  | 'PageUp'\n  | 'PageDown';\n\nconst GRID_KEYS = new Set<string>([\n  'ArrowLeft',\n  'ArrowRight',\n  'ArrowUp',\n  'ArrowDown',\n  'Home',\n  'End',\n  'PageUp',\n  'PageDown',\n]);\n\n/** The key moves focus in the date grid. */\nexport function isGridKey(key: string): key is GridKey {\n  return GRID_KEYS.has(key);\n}\n\nexport interface MoveOptions {\n  weekStartsOn: Weekday;\n  /** Right-to-left: the left arrow goes to the next day. */\n  rtl?: boolean;\n  /** Shift held: Page Up / Page Down move a year, not a month. */\n  shift?: boolean;\n  min?: CalendarDate;\n  max?: CalendarDate;\n}\n\n/**\n * Where focus goes from `date` on `key`, as the WAI-ARIA date picker grid\n * does it: arrows by a day or a week, Home and End to the week's edges,\n * Page Up and Page Down by a month (a year with Shift). Arrows follow the\n * reading direction. The result stays inside `[min, max]`, so focus never\n * lands on a day that is not drawn as a choice.\n */\nexport function moveFocus(date: CalendarDate, key: GridKey, opts: MoveOptions): CalendarDate {\n  const forward = opts.rtl ? 'ArrowLeft' : 'ArrowRight';\n  let next: CalendarDate;\n  switch (key) {\n    case 'ArrowLeft':\n    case 'ArrowRight':\n      next = addDays(date, key === forward ? 1 : -1);\n      break;\n    case 'ArrowUp':\n      next = addDays(date, -7);\n      break;\n    case 'ArrowDown':\n      next = addDays(date, 7);\n      break;\n    case 'Home':\n      next = startOfWeek(date, opts.weekStartsOn);\n      break;\n    case 'End':\n      next = endOfWeek(date, opts.weekStartsOn);\n      break;\n    case 'PageUp':\n      next = addMonths(date, opts.shift ? -12 : -1);\n      break;\n    case 'PageDown':\n      next = addMonths(date, opts.shift ? 12 : 1);\n      break;\n  }\n  return clampDate(next, opts.min, opts.max);\n}\n\n/**\n * @interlace/ui — calendar-model\n *\n * The pure half of `Calendar`: dates as plain `YYYY-MM-DD` strings, the\n * month grid, the keyboard moves of the WAI-ARIA date grid, and the bounds.\n *\n * A calendar day is not an instant. A `Date` carries a time and a zone, and\n * \"the 3rd\" turned into a `Date` at midnight in one zone is the 2nd in the\n * next one west, which is how a booking page ends up a day off for half its\n * visitors. So a day here is the string a form posts and a server stores,\n * and every piece of arithmetic runs on the UTC calendar, where no day is\n * 23 or 25 hours long.\n *\n * Nothing in this file touches the DOM or React, so a server can repeat any\n * of it: the same grid, the same \"is this day bookable\".\n */\n\n/** A calendar day, `YYYY-MM-DD`. */\n\n// @interlace/calendar-model v1.0.0 — Interlace design system.\n// Docs, props and live preview: https://ds.interlace.tools/c/calendar-model\n// What changed since: https://ds.interlace.tools/c/calendar-model#history\n// Generated banner — keep it, the upgrade diff reads this version.\n"
    }
  ],
  "meta": {
    "tier": "primitive",
    "client": true,
    "minViewport": 320,
    "loading": false,
    "version": "1.1.2",
    "since": "2.0.0"
  },
  "docs": "## @interlace/calendar\n\nInstalled to `components/ui/calendar.tsx`.\n\n```tsx\nimport { /* … */ } from '@/components/ui/calendar';\n```\n\nProps, a11y contract, live preview and source: https://ds.interlace.tools/c/calendar\n\nRequires the `@interlace/interlace-base` CSS baseline (installed automatically as a registry dependency). For the Interlace look, also add `@interlace/theme`."
}
