{
  "name": "calendar",
  "type": "registry:ui",
  "framework": "react",
  "title": "Calendar",
  "description": "A month grid for picking one day, with keyboard navigation and optional first and last selectable dates.",
  "files": [
    {
      "path": "ui/calendar.tsx",
      "content": "\"use client\"\n\nimport * as React from \"react\"\n\nimport { cn } from \"@/lib/utils\"\n\nexport interface CalendarProps extends Omit<\n  React.ComponentProps<\"div\">,\n  \"onChange\" | \"defaultValue\"\n> {\n  /** The chosen day as `YYYY-MM-DD`. Leave undefined to let the calendar own it. */\n  value?: string\n  defaultValue?: string\n  onValueChange?: (value: string) => void\n  /** The first and last day that can be chosen, as `YYYY-MM-DD`. */\n  min?: string\n  max?: string\n  /** A BCP 47 tag for the month and weekday names. */\n  locale?: string\n  /** `0` starts the week on Sunday, `1` on Monday. */\n  weekStartsOn?: 0 | 1\n  /** Accessible names of the two month buttons. */\n  previousLabel?: string\n  nextLabel?: string\n}\n\n/*\n * Dates are `YYYY-MM-DD` strings and all arithmetic is in UTC, so a day never\n * shifts with the reader's time zone and two dates compare as text.\n */\nconst DAY = 86_400_000\nconst pad = (value: number) => String(value).padStart(2, \"0\")\nconst toIso = (date: Date) =>\n  `${date.getUTCFullYear()}-${pad(date.getUTCMonth() + 1)}-${pad(date.getUTCDate())}`\nconst fromIso = (iso: string) => new Date(`${iso}T00:00:00Z`)\n\n/** The same day of the month `amount` months away, or that month's last day. */\nfunction shiftMonth(iso: string, amount: number): string {\n  const from = fromIso(iso)\n  const target = new Date(\n    Date.UTC(from.getUTCFullYear(), from.getUTCMonth() + amount, 1)\n  )\n  const last = new Date(\n    Date.UTC(target.getUTCFullYear(), target.getUTCMonth() + 1, 0)\n  ).getUTCDate()\n  target.setUTCDate(Math.min(from.getUTCDate(), last))\n  return toIso(target)\n}\n\nfunction localToday(): string {\n  const now = new Date()\n  return `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())}`\n}\n\n/* 4 January 1970 was a Sunday, which makes it day zero of a week of names. */\nconst SUNDAY = Date.UTC(1970, 0, 4)\n\nconst navClassName =\n  \"inline-flex h-7 w-7 items-center justify-center rounded-[var(--newt-radius-sm)] text-newt-text-muted hover:bg-newt-bg-hover hover:text-newt-text-primary focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-newt-text-link\"\n\n/*\n * One month as a grid of days. The days are real buttons inside a table with\n * `role=\"grid\"`, so a screen reader announces the weekday column as it moves,\n * and only one day at a time is a tab stop: the arrow keys do the rest, and\n * moving off the edge of the month turns the page. Today is marked by an\n * outline and the chosen day by a fill.\n */\nconst Calendar = React.forwardRef<HTMLDivElement | null, CalendarProps>(\n  (\n    {\n      className,\n      value,\n      defaultValue,\n      onValueChange,\n      min,\n      max,\n      locale = \"en-US\",\n      weekStartsOn = 0,\n      previousLabel = \"Previous month\",\n      nextLabel = \"Next month\",\n      ...props\n    },\n    ref\n  ) => {\n    const root = React.useRef<HTMLDivElement | null>(null)\n    React.useImperativeHandle<HTMLDivElement | null, HTMLDivElement | null>(\n      ref,\n      () => root.current\n    )\n    const [internal, setInternal] = React.useState(defaultValue)\n    const selected = value ?? internal\n    /*\n     * \"Today\" is the reader's, so it is only known in the browser. Until\n     * then a calendar with no value has no month to show and draws none.\n     */\n    const [today, setToday] = React.useState<string | undefined>(undefined)\n    const [cursor, setCursor] = React.useState(selected)\n    const moveFocus = React.useRef(false)\n\n    /* A controlled value changed from outside turns the page to it. */\n    const [seenValue, setSeenValue] = React.useState(value)\n    if (value !== seenValue) {\n      setSeenValue(value)\n      if (value !== undefined) setCursor(value)\n    }\n\n    /* The nearest day that can be chosen; a month jump lands on it too. */\n    const clamp = (iso: string) =>\n      min !== undefined && iso < min\n        ? min\n        : max !== undefined && iso > max\n          ? max\n          : iso\n\n    /*\n     * The one tab stop. It is clamped because a disabled day cannot take\n     * focus: with today or the value outside the range, the grid would\n     * otherwise have no way in from the keyboard.\n     */\n    /* An empty string is how a form says \"no date yet\"; it is not a day. */\n    const anchorDay = cursor === \"\" ? today : (cursor ?? today)\n    const focused = anchorDay === undefined ? undefined : clamp(anchorDay)\n\n    React.useEffect(() => setToday(localToday()), [])\n\n    React.useEffect(() => {\n      if (!moveFocus.current || focused === undefined) return\n      moveFocus.current = false\n      root.current\n        ?.querySelector<HTMLElement>(`[data-date=\"${focused}\"]`)\n        ?.focus()\n    }, [focused])\n\n    const allowed = (iso: string) =>\n      (min === undefined || iso >= min) && (max === undefined || iso <= max)\n\n    const goTo = (iso: string, withFocus: boolean) => {\n      moveFocus.current = withFocus\n      setCursor(iso)\n    }\n\n    const weekdays = Array.from({ length: 7 }, (_, index) => {\n      const date = new Date(SUNDAY + (index + weekStartsOn) * DAY)\n      const name = (weekday: \"long\" | \"short\") =>\n        new Intl.DateTimeFormat(locale, { weekday, timeZone: \"UTC\" }).format(\n          date\n        )\n      return { long: name(\"long\"), short: name(\"short\").slice(0, 2) }\n    })\n\n    const anchor = focused === undefined ? undefined : fromIso(focused)\n    const title =\n      anchor === undefined\n        ? \"\"\n        : new Intl.DateTimeFormat(locale, {\n            month: \"long\",\n            year: \"numeric\",\n            timeZone: \"UTC\",\n          }).format(anchor)\n\n    const weeks: (string | undefined)[][] = []\n    if (anchor !== undefined) {\n      const year = anchor.getUTCFullYear()\n      const month = anchor.getUTCMonth()\n      const lead =\n        (new Date(Date.UTC(year, month, 1)).getUTCDay() - weekStartsOn + 7) % 7\n      const days = new Date(Date.UTC(year, month + 1, 0)).getUTCDate()\n      for (let slot = 0; slot < lead + days; slot += 1) {\n        if (slot % 7 === 0) weeks.push([])\n        weeks\n          .at(-1)\n          ?.push(\n            slot < lead\n              ? undefined\n              : toIso(new Date(Date.UTC(year, month, slot - lead + 1)))\n          )\n      }\n    }\n\n    const onKeyDown = (\n      event: React.KeyboardEvent<HTMLButtonElement>,\n      iso: string\n    ) => {\n      const forward =\n        getComputedStyle(event.currentTarget).direction === \"rtl\" ? -1 : 1\n      const at = fromIso(iso)\n      const column = (at.getUTCDay() - weekStartsOn + 7) % 7\n      let next: string\n      switch (event.key) {\n        case \"ArrowLeft\":\n          next = toIso(new Date(at.getTime() - forward * DAY))\n          break\n        case \"ArrowRight\":\n          next = toIso(new Date(at.getTime() + forward * DAY))\n          break\n        case \"ArrowUp\":\n          next = toIso(new Date(at.getTime() - 7 * DAY))\n          break\n        case \"ArrowDown\":\n          next = toIso(new Date(at.getTime() + 7 * DAY))\n          break\n        case \"Home\":\n          next = toIso(new Date(at.getTime() - column * DAY))\n          break\n        case \"End\":\n          next = toIso(new Date(at.getTime() + (6 - column) * DAY))\n          break\n        case \"PageUp\":\n          next = clamp(shiftMonth(iso, -1))\n          break\n        case \"PageDown\":\n          next = clamp(shiftMonth(iso, 1))\n          break\n        default:\n          return\n      }\n      event.preventDefault()\n      if (allowed(next)) goTo(next, true)\n    }\n\n    return (\n      <div\n        ref={root}\n        className={cn(\n          \"inline-flex flex-col gap-2 rounded-[var(--newt-radius-md)] border border-newt-border bg-newt-bg-surface p-3 text-newt-text-primary\",\n          className\n        )}\n        {...props}\n      >\n        <div className=\"flex items-center justify-between gap-2\">\n          <button\n            type=\"button\"\n            aria-label={previousLabel}\n            disabled={focused === undefined}\n            onClick={() => {\n              if (focused !== undefined) goTo(shiftMonth(focused, -1), false)\n            }}\n            className={navClassName}\n          >\n            <svg\n              viewBox=\"0 0 16 16\"\n              aria-hidden=\"true\"\n              className=\"h-3.5 w-3.5 -scale-x-100 rtl:scale-x-100\"\n            >\n              <path\n                fill=\"currentColor\"\n                d=\"M5.3 3.3a1 1 0 0 1 1.4 0l4 4a1 1 0 0 1 0 1.4l-4 4a1 1 0 0 1-1.4-1.4L8.6 8 5.3 4.7a1 1 0 0 1 0-1.4Z\"\n              />\n            </svg>\n          </button>\n          <div aria-live=\"polite\" className=\"text-sm font-semibold leading-5\">\n            {title}\n          </div>\n          <button\n            type=\"button\"\n            aria-label={nextLabel}\n            disabled={focused === undefined}\n            onClick={() => {\n              if (focused !== undefined) goTo(shiftMonth(focused, 1), false)\n            }}\n            className={navClassName}\n          >\n            <svg\n              viewBox=\"0 0 16 16\"\n              aria-hidden=\"true\"\n              className=\"h-3.5 w-3.5 rtl:-scale-x-100\"\n            >\n              <path\n                fill=\"currentColor\"\n                d=\"M5.3 3.3a1 1 0 0 1 1.4 0l4 4a1 1 0 0 1 0 1.4l-4 4a1 1 0 0 1-1.4-1.4L8.6 8 5.3 4.7a1 1 0 0 1 0-1.4Z\"\n              />\n            </svg>\n          </button>\n        </div>\n        <table role=\"grid\" aria-label={title} className=\"border-collapse\">\n          <thead>\n            <tr>\n              {weekdays.map((weekday) => (\n                <th\n                  key={weekday.long}\n                  scope=\"col\"\n                  abbr={weekday.long}\n                  className=\"h-7 w-9 p-0 text-center text-[11px] font-bold uppercase text-newt-text-muted\"\n                >\n                  {weekday.short}\n                </th>\n              ))}\n            </tr>\n          </thead>\n          <tbody>\n            {weeks.map((week) => (\n              <tr key={week.find((iso) => iso !== undefined)}>\n                {week.map((iso, column) =>\n                  iso === undefined ? (\n                    <td key={`blank-${column}`} className=\"p-px\" />\n                  ) : (\n                    <td\n                      key={iso}\n                      role=\"gridcell\"\n                      aria-selected={iso === selected}\n                      className=\"p-px\"\n                    >\n                      <button\n                        type=\"button\"\n                        data-date={iso}\n                        tabIndex={iso === focused ? 0 : -1}\n                        disabled={!allowed(iso)}\n                        aria-current={iso === today ? \"date\" : undefined}\n                        onClick={() => {\n                          if (value === undefined) setInternal(iso)\n                          onValueChange?.(iso)\n                          goTo(iso, true)\n                        }}\n                        onKeyDown={(event) => onKeyDown(event, iso)}\n                        className={cn(\n                          \"flex h-[34px] w-[34px] items-center justify-center rounded-[var(--newt-radius-sm)] p-0 font-[family-name:var(--newt-font-sans)] text-[13px] tabular-nums focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-newt-text-link disabled:cursor-not-allowed disabled:opacity-35\",\n                          iso === selected\n                            ? \"bg-newt-brand font-bold text-newt-on-accent\"\n                            : \"text-newt-text-secondary enabled:hover:bg-newt-bg-hover enabled:hover:text-newt-text-primary\",\n                          iso === today &&\n                            iso !== selected &&\n                            \"text-newt-text-primary shadow-[inset_0_0_0_1px_var(--newt-text-muted)]\"\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)\nCalendar.displayName = \"Calendar\"\n\nexport { Calendar }\n",
      "type": "registry:ui"
    }
  ]
}