{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "calendar",
  "type": "registry:ui",
  "title": "Calendar",
  "description": "The calendar primitive.",
  "dependencies": [
    "lucide-react@^1.49.0"
  ],
  "registryDependencies": [
    "https://ui.klarhimmel.com/r/theme.json",
    "https://ui.klarhimmel.com/r/utils.json"
  ],
  "files": [
    {
      "path": "src/ui/calendar.tsx",
      "type": "registry:file",
      "target": "components/klarhimmel/ui/calendar.tsx",
      "content": "import { useEffect, useId, useMemo, useRef, useState, type KeyboardEvent } from 'react';\nimport { ChevronLeft, ChevronRight } from 'lucide-react';\nimport { cn } from '../lib/utils';\n\n// ---------- Dates as ISO text. No clock, no time zone: \"2026-11-16\" is the same day everywhere. ----------\n\nconst pad = (n: number) => String(n).padStart(2, '0');\nconst utc = (y: number, m: number, d: number) => new Date(Date.UTC(y, m - 1, d));\n/** \"YYYY-MM-DD\" of a UTC date. */\nexport const isoOf = (d: Date) => `${d.getUTCFullYear()}-${pad(d.getUTCMonth() + 1)}-${pad(d.getUTCDate())}`;\n/** The date for \"YYYY-MM-DD\", or null when the text is not a real calendar day (2026-02-30 is not). */\nexport function parseIso(text: string): Date | null {\n  const m = /^(\\d{4})-(\\d{2})-(\\d{2})$/.exec(text.trim());\n  if (!m) return null;\n  const d = utc(Number(m[1]), Number(m[2]), Number(m[3]));\n  return isoOf(d) === `${m[1]}-${m[2]}-${m[3]}` ? d : null;\n}\n/** ISO text from what a person types: \"2026-11-16\", or day first with / . or - (\"16/11/2026\", \"16.11.2026\"). null when it is neither. */\nexport function readDate(text: string): string | null {\n  const t = text.trim();\n  if (parseIso(t)) return t;\n  const m = /^(\\d{1,2})[/.-](\\d{1,2})[/.-](\\d{4})$/.exec(t);\n  return m ? (parseIso(`${m[3]}-${pad(Number(m[2]))}-${pad(Number(m[1]))}`) ? `${m[3]}-${pad(Number(m[2]))}-${pad(Number(m[1]))}` : null) : null;\n}\nexport const addDays = (iso: string, n: number) => isoOf(utc(Number(iso.slice(0, 4)), Number(iso.slice(5, 7)), Number(iso.slice(8, 10)) + n));\n/** Same day of the month `n` months on, held to the end of a shorter month (31 Jan + 1 month = 28 Feb). */\nexport function addMonths(iso: string, n: number): string {\n  const y = Number(iso.slice(0, 4));\n  const m = Number(iso.slice(5, 7));\n  const first = utc(y, m + n, 1);\n  const last = new Date(Date.UTC(first.getUTCFullYear(), first.getUTCMonth() + 1, 0)).getUTCDate();\n  return isoOf(utc(first.getUTCFullYear(), first.getUTCMonth() + 1, Math.min(Number(iso.slice(8, 10)), last)));\n}\nconst monthOf = (iso: string) => iso.slice(0, 7);\nconst fmt = (iso: string, locale: string, o: Intl.DateTimeFormatOptions) => {\n  try {\n    return new Intl.DateTimeFormat(locale, { ...o, timeZone: 'UTC' }).format(parseIso(iso)!);\n  } catch {\n    return iso;\n  }\n};\n/** Whole weeks covering a month, each seven ISO days from Monday or Sunday; days outside the month are null. */\nexport function weeksOf(month: string, first: 'mon' | 'sun'): (string | null)[][] {\n  const [y, m] = month.split('-').map(Number) as [number, number];\n  const start = utc(y, m, 1);\n  const offset = (start.getUTCDay() - (first === 'mon' ? 1 : 0) + 7) % 7;\n  const days = new Date(Date.UTC(y, m, 0)).getUTCDate();\n  const cells = Array.from({ length: Math.ceil((offset + days) / 7) * 7 }, (_, i) => (i >= offset && i < offset + days ? `${month}-${pad(i - offset + 1)}` : null));\n  return Array.from({ length: cells.length / 7 }, (_, w) => cells.slice(w * 7, w * 7 + 7));\n}\n\nexport interface CalendarProps {\n  /** The chosen day, \"YYYY-MM-DD\", or \"\" for none. */\n  value?: string;\n  defaultValue?: string;\n  onValueChange?: (value: string) => void;\n  /** The month shown, \"YYYY-MM\". Defaults to the chosen day's month, then today's, then the month of `today`. */\n  month?: string;\n  onMonthChange?: (month: string) => void;\n  /** The earliest and latest day that can be chosen. Other days are shown but cannot be picked. */\n  min?: string;\n  max?: string;\n  isDisabled?: (iso: string) => boolean;\n  /** Today, \"YYYY-MM-DD\". Marked with a ring and the word. Never read from the clock here, so it renders the same on the server. */\n  today?: string;\n  firstDay?: 'mon' | 'sun';\n  locale?: string;\n  /** Names the grid when there is no other label. */\n  'aria-label'?: string;\n  /** Move focus to the day when it mounts (a calendar opened from a button). */\n  autoFocus?: boolean;\n  /** Button names and the word added to today's name. Pass them translated. */\n  labels?: { previous: string; next: string; today: string };\n  className?: string;\n}\n\n/**\n * A month of days to choose from: the WAI-ARIA date picker grid. One day is the tab stop; arrows move by a day or a week, Home and End\n * to the start and end of the week, Page Up and Page Down by a month (with Shift, a year), Enter or Space chooses. The month is\n * announced when it changes, today is ringed and named, and days that cannot be chosen say so.\n */\nexport function Calendar({\n  value, defaultValue = '', onValueChange, month, onMonthChange, min, max, isDisabled, today, firstDay = 'mon', locale = 'en', autoFocus, className, labels = { previous: 'Previous month', next: 'Next month', today: 'today' }, ...aria\n}: CalendarProps) {\n  const id = useId();\n  const [own, setOwn] = useState(defaultValue);\n  const chosen = value ?? own;\n  const start = chosen && parseIso(chosen) ? chosen : today && parseIso(today) ? today : '2026-01-01';\n  const [focused, setFocused] = useState(start);\n  const [ownMonth, setOwnMonth] = useState(monthOf(start));\n  const shown = month ?? ownMonth;\n  const cells = useRef(new Map<string, HTMLButtonElement>());\n  const [pending, setPending] = useState<string | null>(null);\n  const weeks = useMemo(() => weeksOf(shown, firstDay), [shown, firstDay]);\n  const blocked = (iso: string) => (min !== undefined && iso < min) || (max !== undefined && iso > max) || !!isDisabled?.(iso);\n  const setMonth = (m: string) => {\n    setOwnMonth(m);\n    onMonthChange?.(m);\n  };\n  /** Moves the roving day (and the month, when it leaves the one shown), then focuses it once it is drawn. */\n  const go = (iso: string) => {\n    setFocused(iso);\n    if (monthOf(iso) !== shown) setMonth(monthOf(iso));\n    setPending(iso);\n  };\n  useEffect(() => {\n    if (pending) cells.current.get(pending)?.focus();\n    setPending(null);\n  }, [pending, shown]);\n  useEffect(() => {\n    if (autoFocus) cells.current.get(focused)?.focus();\n  }, []); // eslint-disable-line react-hooks/exhaustive-deps\n  // The roving day must be in the month shown, or there is no tab stop.\n  const stop = monthOf(focused) === shown ? focused : `${shown}-01`;\n  const pick = (iso: string) => {\n    if (blocked(iso)) return;\n    setOwn(iso);\n    onValueChange?.(iso);\n  };\n  const onKey = (e: KeyboardEvent) => {\n    const dow = (parseIso(stop)!.getUTCDay() - (firstDay === 'mon' ? 1 : 0) + 7) % 7;\n    const to: Record<string, string> = {\n      ArrowLeft: addDays(stop, -1), ArrowRight: addDays(stop, 1), ArrowUp: addDays(stop, -7), ArrowDown: addDays(stop, 7),\n      Home: addDays(stop, -dow), End: addDays(stop, 6 - dow),\n      PageUp: addMonths(stop, e.shiftKey ? -12 : -1), PageDown: addMonths(stop, e.shiftKey ? 12 : 1),\n    };\n    if (to[e.key]) {\n      e.preventDefault();\n      go(to[e.key]!);\n    }\n  };\n  const heading = fmt(`${shown}-01`, locale, { month: 'long', year: 'numeric' });\n  const off = (parseIso(`${shown}-01`)!.getUTCDay() - (firstDay === 'mon' ? 1 : 0) + 7) % 7;\n  const weekdayIso = Array.from({ length: 7 }, (_, i) => addDays(`${shown}-01`, i - off));\n  const nav = (by: number, label: string, Icon: typeof ChevronLeft) => (\n    <button\n      type=\"button\"\n      aria-label={label}\n      onClick={() => setMonth(addMonths(`${shown}-01`, by).slice(0, 7))}\n      className=\"inline-flex size-11 items-center justify-center rounded-kh text-kh-ink-2 hover:bg-kh-surface-2 hover:text-kh-ink focus-visible:outline-2 focus-visible:outline-offset-0 focus-visible:outline-(--kh-focus)\"\n    >\n      <Icon aria-hidden className=\"size-4\" />\n    </button>\n  );\n  return (\n    <div className={cn('w-fit max-w-full select-none', className)}>\n      <div className=\"flex items-center justify-between gap-2\">\n        {nav(-1, labels.previous, ChevronLeft)}\n        <h2 id={`${id}-h`} aria-live=\"polite\" className=\"text-kh-small font-semibold\">\n          {heading}\n        </h2>\n        {nav(1, labels.next, ChevronRight)}\n      </div>\n      <table role=\"grid\" aria-labelledby={aria['aria-label'] ? undefined : `${id}-h`} aria-label={aria['aria-label']} onKeyDown={onKey} className=\"mt-2 border-separate border-spacing-0.5 text-center\">\n        <thead>\n          <tr>\n            {weekdayIso.map((d, i) => (\n              <th key={i} scope=\"col\" abbr={fmt(d, locale, { weekday: 'long' })} className=\"size-11 text-kh-caption font-medium text-kh-muted\">\n                {fmt(d, locale, { weekday: 'short' })}\n              </th>\n            ))}\n          </tr>\n        </thead>\n        <tbody>\n          {weeks.map((week, r) => (\n            <tr key={r}>\n              {week.map((iso, c) =>\n                iso === null ? (\n                  <td key={c} className=\"size-11\" />\n                ) : (\n                  <td key={c} role=\"gridcell\" aria-selected={iso === chosen} className=\"p-0\">\n                    <button\n                      type=\"button\"\n                      ref={(el) => {\n                        if (el) cells.current.set(iso, el);\n                      }}\n                      tabIndex={iso === stop ? 0 : -1}\n                      aria-disabled={blocked(iso) || undefined}\n                      aria-current={iso === today ? 'date' : undefined}\n                      aria-label={`${fmt(iso, locale, { weekday: 'long', day: 'numeric', month: 'long', year: 'numeric' })}${iso === today ? `, ${labels.today}` : ''}`}\n                      onFocus={() => setFocused(iso)}\n                      onClick={() => pick(iso)}\n                      className={cn(\n                        'inline-flex size-11 items-center justify-center rounded-kh text-kh-small tabular-nums',\n                        'focus-visible:outline-2 focus-visible:outline-offset-0 focus-visible:outline-(--kh-focus)',\n                        iso === chosen ? 'bg-kh-ink font-semibold text-kh-on-ink' : 'text-kh-ink hover:bg-kh-surface-2',\n                        iso === today && iso !== chosen && 'ring-2 ring-inset ring-kh-ink',\n                        blocked(iso) && 'cursor-not-allowed text-kh-muted line-through hover:bg-transparent',\n                      )}\n                    >\n                      {Number(iso.slice(8))}\n                    </button>\n                  </td>\n                ),\n              )}\n            </tr>\n          ))}\n        </tbody>\n      </table>\n    </div>\n  );\n}\n"
    }
  ]
}
