{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "calendar",
  "title": "Calendar",
  "description": "ui-sdk's Calendar: a month of days to pick one day, several or a range from, by pointer or by the WAI-ARIA date grid's keys. A backdrop glides under the pointer and a pill slides to the pick, a range grows along each week, and each month's name opens a popover of months and years. To the month or the year, it picks one of twelve. Every date comes from the dates lib.",
  "dependencies": [
    "@ui-sdk/react",
    "@ui-sdk/core"
  ],
  "registryDependencies": [
    "https://kinoui.com/r/cut.json",
    "https://kinoui.com/r/dates.json",
    "https://kinoui.com/r/button.json",
    "https://kinoui.com/r/controllable.json",
    "https://kinoui.com/r/field-control.json",
    "https://kinoui.com/r/popover.json",
    "https://kinoui.com/r/highlight.json",
    "https://kinoui.com/r/pill.json",
    "https://kinoui.com/r/swap.json",
    "https://kinoui.com/r/refs.json",
    "https://kinoui.com/r/theme.json"
  ],
  "files": [
    {
      "path": "registry/components/kino/calendar.tsx",
      "content": "'use client'\n\nimport { Button } from '@/registry/components/kino/button'\nimport {\n  Popover,\n  PopoverContent,\n  PopoverTrigger,\n} from '@/registry/components/kino/popover'\nimport { IconPlaceholder } from '@/registry/icons/icon-placeholder'\nimport { CalendarChoices } from '@/registry/lib/calendar-choices'\nimport {\n  bandClassName,\n  CALENDAR_LABELS,\n  calendarClassName,\n  calendarHeadingClassName,\n  type CalendarLabels,\n  type CalendarLook,\n  CalendarLookContext,\n  calendarNextPlace,\n  CalendarPending,\n  calendarPreviousPlace,\n  chevrons,\n  columnLayout,\n  DAY,\n  dayClassName,\n  type DayContent,\n  dayLayout,\n  followBands,\n  type GridWeeks,\n  MonthSlide,\n  useCalendarLook,\n  useTurnPlaces,\n  weekdaysClassName,\n  weekLayout,\n  weekNumberClassName,\n} from '@/registry/lib/calendar-grid'\nimport {\n  CHOICES,\n  type ChoiceLevel,\n  choicePage,\n  choicePageTurn,\n  firstShownFor,\n  fullDays,\n} from '@/registry/lib/calendar-model'\nimport { useControllable } from '@/registry/lib/controllable'\nimport { CutTooltip } from '@/registry/lib/cut'\nimport {\n  boundDay,\n  type DateMatchers,\n  type DateRange,\n  dayLabel,\n  isISODate,\n  isISOMonth,\n  isISOYear,\n  monthLabel,\n  monthOf,\n  monthParts,\n  useLocale,\n  useToday,\n  type Weekday,\n  weekOfYear,\n  weekStart,\n  yearMonth,\n  yearPage,\n} from '@/registry/lib/dates'\nimport {\n  FieldCheck,\n  FieldValues,\n  keptOnReset,\n  useFieldProps,\n  useLabelFocus,\n} from '@/registry/lib/field-control'\nimport {\n  followPick,\n  followPointer,\n  highlightClassName,\n  itemMatching,\n  pickClassName,\n} from '@/registry/lib/highlight'\nimport { pillBackdropClassName, pillClassName } from '@/registry/lib/pill'\nimport { markMounted, mergeRefs } from '@/registry/lib/refs'\nimport { Swap } from '@/registry/lib/swap'\nimport type { ChangeDetails } from '@ui-sdk/core'\nimport {\n  type CalendarDayState,\n  type CalendarValueChangeReason,\n  Calendar as CalendarPrimitive,\n  CalendarDay as CalendarDayPrimitive,\n  CalendarGrid as CalendarGridPrimitive,\n  CalendarHeading as CalendarHeadingPrimitive,\n  CalendarNext as CalendarNextPrimitive,\n  CalendarPrevious as CalendarPreviousPrimitive,\n  CalendarWeekday,\n  createCalendarController,\n} from '@ui-sdk/react/calendar'\nimport {\n  type ComponentProps,\n  createContext,\n  type ReactNode,\n  use,\n  useCallback,\n  useEffect,\n  useMemo,\n  useId,\n  useLayoutEffect,\n  useRef,\n  useState,\n} from 'react'\n\nimport { cn } from '@/lib/utils'\n\n/*\n * ui-sdk's Calendar in Kino's look: ui-sdk holds which month shows, what is\n * picked, a range in progress and the keys of the WAI-ARIA date grid; Kino\n * draws it. A backdrop glides under the pointer and a pill slides to the\n * pick, as on the Tabs; a range is a band that grows along each week. The\n * arrows turn the months, which slide a short way in the direction of\n * travel, and each month's name opens a popover of the year's twelve months,\n * whose year's name steps out to twelve years. The ready-made `Calendar`\n * renders every part; its parts compose a calendar of the buyer's own.\n */\n\n/** How far the months and choices slide and zoom; a buyer's `--calendar-slide` and `--calendar-zoom` win. */\nconst motion =\n  '[--swap-slide:var(--calendar-slide,1.5rem)] [--swap-zoom:var(--calendar-zoom,0.92)]'\n\n/** Why the value changed, as `onValueChange` hears it. */\ntype CalendarChangeDetails = ChangeDetails<CalendarValueChangeReason>\n\n/* --------------------------------------------------------------------------\n * The parts\n * ------------------------------------------------------------------------ */\n\n/** One backdrop under every month on screen, so it glides from one to the next; a grid on its own draws its own. */\nconst SharedBackdropContext = createContext(false)\n\n/** ui-sdk's Previous or Next, on a ghost Button, named in the Calendar's words. */\nfunction CalendarTurn({\n  direction,\n  className,\n  ...props\n}: Omit<ComponentProps<typeof CalendarPreviousPrimitive>, 'className'> & {\n  direction: 'previous' | 'next'\n  className?: string\n}) {\n  const { labels } = useCalendarLook()\n  const Part =\n    direction === 'previous' ? CalendarPreviousPrimitive : CalendarNextPrimitive\n  return (\n    <Part\n      aria-label={direction === 'previous' ? labels.previousMonth : labels.nextMonth}\n      render={\n        <Button\n          variant='ghost'\n          size='icon-sm'\n          {...{ [`data-calendar-${direction}`]: '' }}\n          className={className}\n        />\n      }\n      {...props}\n    >\n      {chevrons[direction]}\n    </Part>\n  )\n}\n\nfunction CalendarPrevious(props: Omit<ComponentProps<typeof CalendarTurn>, 'direction'>) {\n  return <CalendarTurn direction='previous' {...props} />\n}\n\nfunction CalendarNext(props: Omit<ComponentProps<typeof CalendarTurn>, 'direction'>) {\n  return <CalendarTurn direction='next' {...props} />\n}\n\n/** The months on screen, named; the ready-made Calendar keeps it for screen readers, which hear each turn. */\nfunction CalendarHeading({\n  className,\n  ...props\n}: Omit<ComponentProps<typeof CalendarHeadingPrimitive>, 'className'> & {\n  className?: string\n}) {\n  return (\n    <CalendarHeadingPrimitive\n      className={cn('text-center text-sm font-medium', className)}\n      {...props}\n    />\n  )\n}\n\n/** A day's own content: its number in Latin digits, as the Date input writes it, or the buyer's. */\nfunction dayText(look: CalendarLook, date: string) {\n  return look.dayContent ? look.dayContent(date) : dayLabel(date, look.locale)\n}\n\n/**\n * One of ui-sdk's days, in the Calendar's look. With content of the buyer's,\n * its name is the full date and then what they show.\n */\nfunction CalendarDay({\n  className,\n  ...props\n}: Omit<\n  ComponentProps<typeof CalendarDayPrimitive>,\n  'className' | 'render' | 'children'\n> & {\n  className?: string\n}) {\n  const look = useCalendarLook()\n  return (\n    <CalendarDayPrimitive\n      {...props}\n      render={(own: Record<string, unknown>, state: CalendarDayState) => {\n        const full = look.full?.(state.date) === true\n        return (\n          <span\n            {...own}\n            aria-label={look.dayContent ? undefined : (own['aria-label'] as string)}\n            aria-disabled={full ? 'true' : (own['aria-disabled'] as 'true' | undefined)}\n            data-full={full ? '' : undefined}\n          >\n            {look.dayContent && (\n              <span className='sr-only'>{own['aria-label'] as string}</span>\n            )}\n            {own.children as ReactNode}\n          </span>\n        )\n      }}\n      className={cn(dayClassName, className)}\n    >\n      {dayText(look, props.value)}\n    </CalendarDayPrimitive>\n  )\n}\n\n/** A week's number, which heads its row. */\nfunction WeekNumber({ date }: { date: string }) {\n  const look = useCalendarLook()\n  const week = weekOfYear(date, look.weekStartsOn)\n  return (\n    <span\n      role='rowheader'\n      aria-label={look.labels.week(week)}\n      className={weekNumberClassName}\n    >\n      {week}\n    </span>\n  )\n}\n\n/** A month's weeks: the weekday row, then a row a week, each with its band, its number and its days. */\nfunction MonthWeeks({ month, weeks }: { month: string; weeks: GridWeeks }) {\n  const look = useCalendarLook()\n  const shared = use(SharedBackdropContext)\n  const areaRef = useRef<HTMLDivElement>(null)\n  const areaRefs = useMemo(() => mergeRefs(areaRef, markMounted), [])\n  const pillRef = useRef<HTMLSpanElement>(null)\n  const backdropRef = useRef<HTMLSpanElement>(null)\n\n  useEffect(() => {\n    const area = areaRef.current\n    const pill = pillRef.current\n    if (!area || !pill) return\n    const stopPick = followPick(area, pill, {\n      picked: () =>\n        area.querySelector<HTMLElement>(`${DAY}[data-selected]:not([data-outside])`),\n      attributes: ['data-selected'],\n    })\n    const backdrop = backdropRef.current\n    const stopHover = backdrop\n      ? followPointer(area, backdrop, { itemOf: itemMatching(area, DAY), focus: true })\n      : () => {}\n    return () => {\n      stopPick()\n      stopHover()\n    }\n  }, [])\n\n  // Before the first paint, so a month's bands show in place as it arrives.\n  useLayoutEffect(() => {\n    const area = areaRef.current\n    return area ? followBands(area) : undefined\n  }, [])\n\n  return (\n    <div\n      ref={areaRefs}\n      data-calendar-month={month}\n      className='relative isolate flex w-full flex-col'\n    >\n      {shared ? null : (\n        <span\n          ref={backdropRef}\n          aria-hidden\n          className={cn(highlightClassName, pillBackdropClassName)}\n        />\n      )}\n      <div\n        role='row'\n        className={cn(weekLayout, weekdaysClassName, 'text-xs text-muted-foreground')}\n      >\n        {look.showWeekNumbers && (\n          <span role='columnheader'>\n            <span className='sr-only'>{look.labels.weekNumbers}</span>\n          </span>\n        )}\n        {Array.from({ length: 7 }, (_, index) => (\n          <CalendarWeekday\n            // oxlint-disable-next-line react/no-array-index-key -- a week's columns keep their order\n            key={index}\n            index={index}\n            render={<span />}\n            className='flex items-center justify-center font-normal'\n          />\n        ))}\n      </div>\n      {weeks.map((week) => (\n        <div key={week[0].date} role='row' data-calendar-week='' className={weekLayout}>\n          <span\n            aria-hidden\n            data-calendar-band=''\n            data-empty=''\n            className={bandClassName}\n          />\n          {look.showWeekNumbers && <WeekNumber date={week[0].date} />}\n          {week.map((cell) =>\n            cell.hidden ? (\n              // Holds the day's square, so a week of hidden days keeps its height.\n              // oxlint-disable-next-line jsx-a11y/control-has-associated-label -- an empty cell, as ui-sdk's own grid draws a hidden day's <td>\n              <span\n                key={cell.date}\n                role='gridcell'\n                data-calendar-empty=''\n                className='m-px aspect-square'\n              />\n            ) : (\n              <CalendarDay key={cell.date} value={cell.date} />\n            ),\n          )}\n        </div>\n      ))}\n      <span\n        ref={pillRef}\n        aria-hidden\n        inert\n        className={cn(\n          pickClassName,\n          pillClassName,\n          'z-10 hidden group-data-[mode=single]/calendar:block group-data-disabled/calendar:data-[highlight=shown]:opacity-50',\n        )}\n      >\n        <span className='flex flex-col'>\n          <span className={weekdaysClassName} />\n          {weeks.map((week) => (\n            <span key={week[0].date} className={weekLayout}>\n              {look.showWeekNumbers && <span />}\n              {week.map((cell) => (\n                <span\n                  key={cell.date}\n                  data-today={look.today === cell.date ? '' : undefined}\n                  className={dayLayout}\n                >\n                  {cell.hidden ? null : dayText(look, cell.date)}\n                </span>\n              ))}\n            </span>\n          ))}\n        </span>\n      </span>\n    </div>\n  )\n}\n\n/**\n * ui-sdk's grid of one month's days, `offset` months after the first on\n * screen, as a column whose weeks slide the way the months travel. Without\n * children it draws the weekday row and the weeks; a function of the grid's\n * state draws what it returns. `heading` draws above the grid, outside it,\n * for the month it shows, since a grid holds only its rows.\n */\nfunction CalendarGrid({\n  offset = 0,\n  heading,\n  className,\n  children,\n  ...props\n}: Omit<ComponentProps<typeof CalendarGridPrimitive>, 'className' | 'children'> & {\n  heading?: (month: string) => ReactNode\n  className?: string\n  children?: ComponentProps<typeof CalendarGridPrimitive>['children']\n}) {\n  const column = cn(columnLayout, 'gap-1', className)\n  return (\n    <CalendarGridPrimitive\n      offset={offset}\n      render={(own: ComponentProps<'span'>, grid: { month: string }) =>\n        heading ? (\n          <span data-calendar-column='' className={column}>\n            {heading(grid.month)}\n            <span {...own} className='w-full' />\n          </span>\n        ) : (\n          <span {...own} data-calendar-column='' className={column} />\n        )\n      }\n      {...props}\n    >\n      {children ??\n        ((grid) => (\n          <MonthSlide month={grid.month} block className='w-full'>\n            <MonthWeeks month={grid.month} weeks={grid.weeks} />\n          </MonthSlide>\n        ))}\n    </CalendarGridPrimitive>\n  )\n}\n\n/* --------------------------------------------------------------------------\n * Choices of months and years\n * ------------------------------------------------------------------------ */\n\n/** How a picker of months or years moved to its page: a turn slides, a change of level zooms. */\ntype ChoiceMove = { slide?: 1 | -1; zoom?: 'in' | 'out' }\n\n/** The buttons that turn a page of choices, on a ghost Button. */\nfunction ChoiceTurn({\n  direction,\n  ...props\n}: Omit<ComponentProps<typeof Button>, 'children' | 'variant' | 'size'> & {\n  direction: 'previous' | 'next'\n}) {\n  return (\n    <Button\n      variant='ghost'\n      size='icon-sm'\n      {...{ [`data-calendar-${direction}`]: '' }}\n      {...props}\n    >\n      {chevrons[direction]}\n    </Button>\n  )\n}\n\n/**\n * A year's months, or twelve years, to pick from: arrows either side turn\n * the page, and a year's name steps out to its twelve years, whose pick\n * steps back in to that year's months. A month's heading opens one in a\n * popover; to the month or the year, the Calendar is one.\n */\nfunction ChoicePicker({\n  labels,\n  locale,\n  bounds,\n  today,\n  picked,\n  opensOn,\n  final,\n  disabled,\n  readOnly,\n  focusOn: firstFocus = null,\n  name = {},\n  onLevelChange,\n  onPick,\n}: {\n  labels: CalendarLabels\n  locale: string\n  /** The first and last days that can be chosen from, as `yyyy-mm-dd`. */\n  bounds: { min?: string; max?: string }\n  today: string | null\n  /** The month marked as picked, as `yyyy-mm` (a year's first month for a year), or null. */\n  picked: string | null\n  /** The level and year it opens on. */\n  opensOn: { level: ChoiceLevel; year: number }\n  /** The level whose pick is the value: a year picked among years steps in to its months until `months` is reached. */\n  final: ChoiceLevel\n  disabled?: boolean\n  readOnly?: boolean\n  /** The choice to focus once it first draws, or `stop` for its tab stop. */\n  focusOn?: string | null\n  /** The calendar's name, which names its grid before the page's title. */\n  name?: { 'aria-label'?: string; 'aria-labelledby'?: string }\n  /** The level it shows now, once it steps out or in. */\n  onLevelChange?: (level: ChoiceLevel) => void\n  onPick: (value: string, event: Event | undefined) => void\n}) {\n  const titleId = useId()\n  // What it shows: a year's months, or a page of years from `year`.\n  const [view, setView] = useState(opensOn)\n  const [moved, setMoved] = useState<ChoiceMove>({})\n  const [focusOn, setFocusOn] = useState<string | null>(firstFocus)\n  const { level, year } = view\n  const pageAt = (at: ChoiceLevel, start: number) =>\n    choicePage(at, start, { shown: picked, today, rules: bounds, locale })\n\n  const show = (next: ChoiceLevel, at: number, how: ChoiceMove, focus: string | null) => {\n    setView({ level: next, year: at })\n    setMoved(how)\n    setFocusOn(focus)\n    if (next !== level) onLevelChange?.(next)\n  }\n\n  const page = pageAt(level, year)\n  const { title } = page\n  /**\n   * Turns to the page `direction`, if it has anything to choose. A key past\n   * the grid's edge lands on the choice at `landing` once the page is drawn;\n   * a button that then has nowhere to go hands focus to the grid.\n   */\n  const turn = (direction: 1 | -1, landing: number | null = null) => {\n    const target = direction === 1 ? page.next : page.previous\n    if (target === null) return\n    const lands =\n      landing === null ? undefined : pageAt(level, target).choices[landing]?.value\n    const last =\n      landing === null && choicePageTurn(level, target, direction, bounds) === null\n    show(level, target, { slide: direction }, lands ?? (last ? 'stop' : null))\n  }\n  const choices = disabled\n    ? page.choices.map((choice) => ({ ...choice, disabled: true }))\n    : page.choices\n  const valueAt = (index: number) => (index >= 0 ? page.choices[index].value : null)\n\n  return (\n    <>\n      <span id={titleId} aria-live='polite' className='sr-only'>\n        {title}\n      </span>\n      <div className='flex items-center justify-between gap-1'>\n        <ChoiceTurn\n          direction='previous'\n          aria-label={level === 'months' ? labels.previousYear : labels.previousYears}\n          disabled={disabled || page.previous === null}\n          onClick={() => turn(-1)}\n        />\n        {/* The title moves with the choices below it, button and all. */}\n        <Swap\n          slide={moved.slide}\n          zoom={moved.zoom}\n          id={`${level}:${year}`}\n          className='flex min-w-0 flex-1 justify-center'\n        >\n          {level === 'months' ? (\n            <Button\n              variant='ghost'\n              size='sm'\n              data-calendar-heading=''\n              aria-label={labels.chooseYear(title)}\n              disabled={disabled}\n              onClick={() => {\n                const first = yearPage(year, CHOICES)\n                show('years', first, { zoom: 'out' }, String(year))\n              }}\n              className='min-w-0 tabular-nums'\n            >\n              {title}\n            </Button>\n          ) : (\n            <span className='flex h-(--control-height-sm) items-center text-sm font-medium tabular-nums'>\n              {title}\n            </span>\n          )}\n        </Swap>\n        <ChoiceTurn\n          direction='next'\n          aria-label={level === 'months' ? labels.nextYear : labels.nextYears}\n          disabled={disabled || page.next === null}\n          onClick={() => turn(1)}\n        />\n      </div>\n      <Swap\n        slide={moved.slide}\n        zoom={moved.zoom}\n        id={`${level}:${year}`}\n        className='w-full'\n      >\n        <CalendarChoices\n          choices={choices}\n          current={valueAt(page.current)}\n          today={valueAt(page.today)}\n          label={name['aria-label'] ? `${name['aria-label']}, ${title}` : title}\n          labelledBy={\n            name['aria-labelledby'] ? `${name['aria-labelledby']} ${titleId}` : undefined\n          }\n          focusOn={focusOn}\n          readOnly={readOnly}\n          disabled={disabled}\n          onPage={(direction, index) => turn(direction, index)}\n          onPick={(value, event) => {\n            if (level === 'years' && final === 'months') {\n              const at = Number(value)\n              const month = picked ? monthParts(picked).month : 1\n              show('months', at, { zoom: 'in' }, yearMonth(at, month))\n              return\n            }\n            onPick(level === 'years' ? value.padStart(4, '0') : value, event)\n          }}\n        />\n      </Swap>\n    </>\n  )\n}\n\n/** A month's name, which opens a popover of its year's months. */\nfunction MonthPopover({ month, offset }: { month: string; offset: number }) {\n  const look = useCalendarLook()\n  const [open, setOpen] = useState(false)\n  // Each opening starts afresh on the shown month's year, even while the last one still fades out.\n  const [opened, setOpened] = useState(0)\n  const [level, setLevel] = useState<ChoiceLevel>('months')\n  // The month just picked, which keeps the pill while the popover closes.\n  const [picked, setPicked] = useState<string | null>(null)\n  const triggerRef = useRef<HTMLButtonElement>(null)\n  // Where the popover hangs from: its heading, until a pick turns the months\n  // and the heading slides away with them; from then it stays where it was,\n  // so the popover folds back into the place it came from.\n  const [trigger, setTrigger] = useState<HTMLButtonElement | null>(null)\n  const triggerRefs = useMemo(() => mergeRefs(triggerRef, setTrigger), [])\n  const left = useRef<DOMRect | null>(null)\n  const anchor = useMemo(\n    () =>\n      trigger && {\n        getBoundingClientRect: () => left.current ?? trigger.getBoundingClientRect(),\n        contextElement: trigger,\n      },\n    [trigger],\n  )\n  const name = monthLabel(month, look.locale, look.monthFormat)\n\n  return (\n    <Popover\n      open={open}\n      onOpenChange={(next) => {\n        setOpen(next)\n        if (!next) return\n        left.current = null\n        setPicked(null)\n        setLevel('months')\n        setOpened((count) => count + 1)\n      }}\n    >\n      <CutTooltip\n        render={\n          <PopoverTrigger\n            disabled={look.disabled}\n            ref={triggerRefs}\n            render={\n              <Button\n                variant='ghost'\n                size='sm'\n                data-calendar-heading=''\n                aria-label={look.labels.chooseMonth(name)}\n                className='min-w-0'\n              />\n            }\n          >\n            <span data-cut className='truncate'>\n              {name}\n            </span>\n            <IconPlaceholder\n              lucide='ChevronDownIcon'\n              tabler='IconChevronDown'\n              hugeicons='ArrowDown01Icon'\n              phosphor='CaretDownIcon'\n              remixicon='RiArrowDownSLine'\n              aria-hidden\n              className='text-muted-foreground'\n            />\n          </PopoverTrigger>\n        }\n      />\n      <PopoverContent\n        aria-label={level === 'months' ? look.labels.months : look.labels.years}\n        anchor={anchor}\n        className={`w-[calc(var(--control-height)*7)] gap-1 ${motion}`}\n        initialFocus='[data-slot=calendar-choices-choice][tabindex=\"0\"]'\n      >\n        <ChoicePicker\n          key={opened}\n          labels={look.labels}\n          locale={look.locale}\n          bounds={look.bounds}\n          today={look.today}\n          picked={picked ?? month}\n          opensOn={{ level: 'months', year: monthParts(month).year }}\n          final='months'\n          onLevelChange={setLevel}\n          onPick={(value) => {\n            left.current = triggerRef.current?.getBoundingClientRect() ?? null\n            const first = firstShownFor(value, offset, look.months, look.bounds)\n            look.showMonth(first)\n            // This heading leaves with the months it named, and the popover\n            // with it: focus goes to the heading that takes its place.\n            setPicked(value)\n            setOpen(false)\n            focusHeadingAfter(triggerRef.current, offset)\n          }}\n        />\n      </PopoverContent>\n    </Popover>\n  )\n}\n\n/**\n * Once the months that `from` sat in have turned, focuses the heading at\n * `offset` among the new ones, since the one that had focus left with its\n * months.\n */\nfunction focusHeadingAfter(from: HTMLElement | null, offset: number) {\n  const calendar = from?.closest<HTMLElement>('[data-calendar-months]')\n  requestAnimationFrame(() => {\n    const columns = [\n      ...(calendar?.querySelectorAll<HTMLElement>('[data-calendar-column]') ?? []),\n    ]\n    const headings = [\n      ...(columns[offset]?.querySelectorAll<HTMLElement>('[data-calendar-heading]') ??\n        []),\n    ].filter((heading) => !heading.closest('[inert]'))\n    headings[0]?.focus()\n  })\n}\n\n/**\n * The months on screen in a row that wraps into a column when there isn't\n * room, each under a heading that opens its months, with the arrows on the\n * first and last month's heading and one backdrop under every month. What\n * the ready-made Calendar and the Date picker's popup draw.\n */\nfunction CalendarMonths({ className }: { className?: string }) {\n  const look = useCalendarLook()\n  const [root, setRoot] = useState<HTMLDivElement | null>(null)\n  useTurnPlaces(root)\n  const areaRef = useRef<HTMLSpanElement>(null)\n  const backdropRef = useRef<HTMLSpanElement>(null)\n  useEffect(() => {\n    const area = areaRef.current\n    const backdrop = backdropRef.current\n    if (!area || !backdrop) return\n    return followPointer(area, backdrop, { itemOf: itemMatching(area, DAY), focus: true })\n  }, [])\n\n  return (\n    <div\n      ref={setRoot}\n      data-calendar-months=''\n      data-mode={look.mode}\n      data-disabled={look.disabled ? '' : undefined}\n      data-week-numbers={look.showWeekNumbers ? '' : undefined}\n      className={cn('group/calendar relative w-full', motion, className)}\n    >\n      <CalendarHeading className='sr-only' />\n      <CalendarPrevious className={calendarPreviousPlace} />\n      <CalendarNext className={calendarNextPlace} />\n      <span\n        ref={areaRef}\n        className='relative isolate flex w-full flex-wrap gap-x-(--surface-padding-lg) gap-y-(--surface-gap)'\n      >\n        <span\n          ref={backdropRef}\n          aria-hidden\n          className={cn(highlightClassName, pillBackdropClassName)}\n        />\n        <SharedBackdropContext value>\n          {Array.from({ length: look.months }, (_, offset) => (\n            <CalendarGrid\n              // oxlint-disable-next-line react/no-array-index-key -- a grid is its place among the months\n              key={offset}\n              offset={offset}\n              heading={(month) => (\n                <span className={calendarHeadingClassName}>\n                  <MonthSlide\n                    month={month}\n                    still={false}\n                    className='flex min-w-0 justify-center'\n                  >\n                    <MonthPopover month={month} offset={offset} />\n                  </MonthSlide>\n                </span>\n              )}\n            />\n          ))}\n        </SharedBackdropContext>\n      </span>\n    </div>\n  )\n}\n\n/* --------------------------------------------------------------------------\n * The Calendar\n * ------------------------------------------------------------------------ */\n\n/**\n * The naming a calendar takes in a Field: its label names it and focuses\n * its tab stop, and its description and error describe it. `props` go on the\n * calendar's root, with `ref`. ui-sdk's Calendar doesn't join a Field, so the\n * Field control lib joins it.\n */\nfunction useCalendarNaming(\n  {\n    id: ownId,\n    'aria-label': ariaLabel,\n    'aria-labelledby': ariaLabelledBy,\n    'aria-describedby': ariaDescribedBy,\n  }: Pick<\n    ComponentProps<'div'>,\n    'id' | 'aria-label' | 'aria-labelledby' | 'aria-describedby'\n  >,\n  disabled: boolean,\n  focus: () => void,\n) {\n  const { field, invalid, props } = useFieldProps(\n    {\n      id: ownId,\n      'aria-labelledby': ariaLabelledBy,\n      'aria-describedby': ariaDescribedBy,\n    },\n    { id: ownId },\n  )\n  const {\n    ref,\n    id,\n    'aria-labelledby': labelledBy,\n    'aria-describedby': describedBy,\n  } = props\n  useLabelFocus(ariaLabelledBy ? undefined : labelledBy?.split(' ')[0], disabled, focus)\n  return {\n    field,\n    invalid,\n    ref,\n    props: {\n      id,\n      'aria-label': ariaLabel,\n      'aria-labelledby': ariaLabelledBy ?? (ariaLabel ? undefined : labelledBy),\n      'aria-describedby': describedBy,\n    },\n  }\n}\n\n/** Invalid, the calendar takes a destructive outline, dashed in forced colours. */\nconst invalidClassName =\n  'rounded-(--surface-radius) outline-offset-4 data-invalid:outline-1 data-invalid:outline-destructive forced-colors:data-invalid:outline-2 forced-colors:data-invalid:outline-dashed'\n\n/** What a calendar sends with a form, each date under `name`, and its check: `required` turns it down while nothing is picked. */\nfunction CalendarForm({\n  name,\n  form,\n  required,\n  dates,\n  many = false,\n  disabled,\n  focus,\n  reset,\n}: {\n  name: string | undefined\n  form: string | undefined\n  required: boolean\n  /** What the form sends, each under `name`. */\n  dates: readonly string[]\n  /** Whether it picks several dates, so a Form's values hold a list under `name`. */\n  many?: boolean\n  disabled: boolean\n  /** Focuses the calendar's tab stop, when the form reports it. */\n  focus: () => void\n  /** Puts the calendar back to its default when the form is reset. */\n  reset: (event: Event) => void\n}) {\n  return (\n    <>\n      <FieldValues\n        name={disabled ? undefined : name}\n        form={form}\n        values={dates}\n        many={many}\n      />\n      <FieldCheck\n        value={dates.join(' ')}\n        form={form}\n        required={required}\n        disabled={disabled}\n        onFocus={focus}\n        onReset={reset}\n      />\n    </>\n  )\n}\n\n/** The dates a value holds, in order. */\nfunction datesOf(value: unknown): string[] {\n  if (typeof value === 'string') return isISODate(value) ? [value] : []\n  if (Array.isArray(value)) return value.filter((date): date is string => isISODate(date))\n  return []\n}\n\ninterface CalendarSingle {\n  mode?: 'single'\n  /** The picked day, as `yyyy-mm-dd`. */\n  value?: string | null\n  defaultValue?: string | null\n  onValueChange?: (value: string | null, details: CalendarChangeDetails) => void\n}\n\ninterface CalendarMultiple {\n  mode: 'multiple'\n  /** The picked days, sorted. */\n  value?: string[]\n  defaultValue?: string[]\n  onValueChange?: (value: string[], details: CalendarChangeDetails) => void\n  /** The most days that can be picked. */\n  maxDays?: number\n}\n\ninterface CalendarRange {\n  mode: 'range'\n  /** The picked range, start first; null until both ends are picked. */\n  value?: DateRange | null\n  defaultValue?: DateRange | null\n  onValueChange?: (value: DateRange | null, details: CalendarChangeDetails) => void\n  /** The fewest days a range can span, counting both ends. */\n  minDays?: number\n  /** The most days a range can span, counting both ends. */\n  maxDays?: number\n}\n\ntype CalendarPrimitiveProps = ComponentProps<typeof CalendarPrimitive>\n\n/** What the Calendar to the day takes besides its value. */\ntype CalendarDayOptions = Omit<\n  CalendarPrimitiveProps,\n  | 'mode'\n  | 'value'\n  | 'defaultValue'\n  | 'onValueChange'\n  | 'minDays'\n  | 'maxDays'\n  | 'unavailable'\n  | 'weekStartsOn'\n  | 'className'\n  | 'children'\n> & {\n  /** Picks days (`yyyy-mm-dd`); `month` and `year` are the choice calendar's. */\n  granularity?: 'day'\n  /** Days that can't be picked: a date, `{ from, to }`, `{ weekday: [0, 6] }`, `{ before }`, `{ after }`, a function, or a list of these. */\n  unavailable?: DateMatchers\n  /** The first day of the week, 0 for Sunday. The locale's by default. */\n  weekStartsOn?: Weekday\n  /** Shows each week's number before its days. */\n  showWeekNumbers?: boolean\n  /** What each day shows, under its full date, which a screen reader hears first. */\n  dayContent?: DayContent\n  /** Sends the picked dates with a form, each under this name. */\n  name?: string\n  /** The form the value goes with, when the calendar sits outside it. */\n  form?: string\n  /** A form can't be sent until a date is picked. */\n  required?: boolean\n  /** Marks the calendar as holding a value that isn't allowed; in a Field, its validity decides. */\n  invalid?: boolean\n  labels?: Partial<CalendarLabels>\n  className?: string\n  /** Its parts, for a calendar of your own; the months with their headings and arrows by default. */\n  children?: ReactNode\n}\n\n/** The Calendar to the day: one day, several or a range, picked from its months. */\ntype CalendarDayProps = CalendarDayOptions &\n  (CalendarSingle | CalendarMultiple | CalendarRange)\n\ninterface CalendarChoiceOptions {\n  /** The smallest unit picked: a month (`yyyy-mm`) from a year's twelve, or a year (`yyyy`) from twelve years. */\n  granularity: 'month' | 'year'\n  /** One month or year is picked at a time. */\n  mode?: 'single'\n  /** The picked month as `yyyy-mm`, or year as `yyyy`. */\n  value?: string | null\n  defaultValue?: string | null\n  onValueChange?: (\n    value: string | null,\n    details: { reason: 'item-press' | 'reset'; event?: Event },\n  ) => void\n  /** The earliest month or year that can be picked: a year, a month or a day, in any of whose months or years it falls. */\n  min?: string\n  /** The latest month or year that can be picked: a year, a month or a day. */\n  max?: string\n  /** A press on the picked month or year clears it. */\n  deselectable?: boolean\n  disabled?: boolean\n  /** The pages still turn; the value doesn't change. */\n  readOnly?: boolean\n  /** Sets the names of the months. The browser's language by default. */\n  locale?: string\n  /** The day whose month or year is marked as now, as `yyyy-mm-dd`; by default the visitor's, in `timeZone`. */\n  today?: string\n  /** The time zone that decides which day is today. The visitor's own by default. */\n  timeZone?: string\n  /** Sends the picked month or year with a form, under this name. */\n  name?: string\n  /** The form the value goes with, when the calendar sits outside it. */\n  form?: string\n  /** A form can't be sent until a month or year is picked. */\n  required?: boolean\n  /** Marks the calendar as holding a value that isn't allowed; in a Field, its validity decides. */\n  invalid?: boolean\n  labels?: Partial<CalendarLabels>\n}\n\n/** The Calendar to the month or the year: one picked from a page of twelve. */\ntype CalendarChoiceProps = Omit<\n  ComponentProps<'div'>,\n  keyof CalendarChoiceOptions | 'children'\n> &\n  CalendarChoiceOptions\n\n/** A calendar's props: its days', or with `granularity`, its months' or years'. */\ntype CalendarProps = CalendarDayProps | CalendarChoiceProps\n\nfunction picksChoices(props: CalendarProps): props is CalendarChoiceProps {\n  return props.granularity === 'month' || props.granularity === 'year'\n}\n\n/**\n * A calendar, ready-made: its months with their headings and arrows, or with\n * `granularity`, a year's months or twelve years. Its parts compose a\n * calendar of your own inside it.\n */\nfunction Calendar(props: CalendarProps) {\n  return picksChoices(props) ? <ChoiceCalendar {...props} /> : <DayCalendar {...props} />\n}\n\nfunction DayCalendar(allProps: CalendarDayProps) {\n  const {\n    className,\n    children,\n    dayContent,\n    showWeekNumbers = false,\n    labels: labelsProp,\n    name: nameProp,\n    form,\n    required = false,\n    invalid: invalidProp,\n    granularity,\n    mode = 'single',\n    value,\n    defaultValue,\n    onValueChange,\n    min: minProp,\n    max: maxProp,\n    unavailable,\n    disabled: disabledProp,\n    readOnly = false,\n    locale: localeProp,\n    weekStartsOn,\n    months = 1,\n    fixedWeeks = true,\n    monthFormat = 'long',\n    today: todayProp,\n    timeZone,\n    month,\n    defaultMonth,\n    controller: controllerProp,\n    minDays,\n    maxDays,\n    ref,\n    'aria-label': ariaLabel,\n    'aria-labelledby': ariaLabelledBy,\n    'aria-describedby': ariaDescribedBy,\n    ...rest\n  } = allProps as CalendarDayOptions & {\n    mode?: 'single' | 'multiple' | 'range'\n    value?: unknown\n    defaultValue?: unknown\n    onValueChange?: unknown\n    minDays?: number\n    maxDays?: number\n  }\n  // Only ever to the day here, and not an attribute of the root.\n  // oxlint-disable-next-line typescript/no-meaningless-void-operator -- marks a prop kept out of the rest\n  void granularity\n\n  const [own] = useState(createCalendarController)\n  const controller = controllerProp ?? own\n  const locale = useLocale(localeProp)\n  const clock = useToday(timeZone)\n  const today = isISODate(todayProp) ? todayProp : clock\n  const first = weekStartsOn ?? weekStart(locale)\n  const labels = useMemo(() => ({ ...CALENDAR_LABELS, ...labelsProp }), [labelsProp])\n  const bounds = useMemo(\n    () => ({ min: boundDay(minProp, 'start'), max: boundDay(maxProp, 'end') }),\n    [minProp, maxProp],\n  )\n\n  const focus = useCallback(() => controller.focus(), [controller])\n  const naming = useCalendarNaming(\n    {\n      id: rest.id,\n      'aria-label': ariaLabel,\n      'aria-labelledby': ariaLabelledBy,\n      'aria-describedby': ariaDescribedBy,\n    },\n    disabledProp === true,\n    focus,\n  )\n  const disabled = disabledProp === true || naming.field?.disabled === true\n  const name = nameProp ?? naming.field?.name\n  const invalid = invalidProp ?? naming.invalid\n  const rootRef = useMemo(() => mergeRefs(ref, naming.ref), [ref, naming.ref])\n\n  // Several picks stop at `maxDays`: every other day fades until one is taken\n  // out, and a change to more days than that is turned down, so a reset or\n  // an agent can still replace the whole set.\n  const full = useMemo(\n    () =>\n      mode === 'multiple' && maxDays !== undefined\n        ? (date: string) =>\n            fullDays(datesOf(controller.getValue()), maxDays)?.(date) ?? false\n        : null,\n    [mode, maxDays, controller],\n  )\n  const onPick = useMemo(() => {\n    const own = onValueChange as\n      | ((next: unknown, details: ChangeDetails) => void)\n      | undefined\n    if (mode !== 'multiple' || maxDays === undefined) return own\n    return (next: unknown, details: ChangeDetails) => {\n      if (datesOf(next).length > maxDays) return details.cancel()\n      own?.(next, details)\n    }\n  }, [mode, maxDays, onValueChange])\n\n  const look: CalendarLook = {\n    mode,\n    disabled,\n    locale,\n    labels,\n    weekStartsOn: first,\n    months,\n    monthFormat,\n    showWeekNumbers,\n    dayContent,\n    full,\n    bounds,\n    today,\n    showMonth: (shown: string) => controller.setMonth(shown),\n  }\n\n  // With nothing picked and no month given, the first month is today's,\n  // which the server can't know: it shows no month until the visitor's\n  // clock is read, so the server and the page agree.\n  const waits =\n    today === null &&\n    month === undefined &&\n    defaultMonth === undefined &&\n    datesOf(value ?? defaultValue).length === 0\n\n  return (\n    <CalendarLookContext value={look}>\n      <CalendarPrimitive\n        {...rest}\n        {...naming.props}\n        // Every calendar's root is found by this, to the day or to the month or year alike.\n        data-calendar=''\n        // A group, so its name, description and error reach a screen reader with the day in focus.\n        role='group'\n        ref={rootRef}\n        controller={controller}\n        mode={mode}\n        value={value as CalendarPrimitiveProps['value']}\n        defaultValue={defaultValue as CalendarPrimitiveProps['defaultValue']}\n        onValueChange={onPick as CalendarPrimitiveProps['onValueChange']}\n        min={bounds.min}\n        max={bounds.max}\n        unavailable={unavailable}\n        minDays={mode === 'range' ? minDays : undefined}\n        maxDays={mode === 'range' ? maxDays : undefined}\n        disabled={disabled}\n        readOnly={readOnly}\n        locale={locale}\n        weekStartsOn={first}\n        months={months}\n        fixedWeeks={fixedWeeks}\n        monthFormat={monthFormat}\n        today={today ?? undefined}\n        timeZone={timeZone}\n        month={month}\n        defaultMonth={defaultMonth}\n        data-invalid={invalid ? '' : undefined}\n        className={cn(\n          calendarClassName,\n          'relative gap-1',\n          invalidClassName,\n          motion,\n          className,\n        )}\n      >\n        {(state) => (\n          <>\n            <CalendarForm\n              name={name}\n              form={form}\n              required={required}\n              dates={datesOf(state.value)}\n              many={mode === 'multiple'}\n              disabled={disabled}\n              focus={focus}\n              reset={() => {\n                if (keptOnReset(value, defaultValue)) return\n                const initial = defaultValue ?? (mode === 'multiple' ? [] : null)\n                controller.setValue(initial as never)\n              }}\n            />\n            {waits ? <CalendarPending /> : (children ?? <CalendarMonths />)}\n          </>\n        )}\n      </CalendarPrimitive>\n    </CalendarLookContext>\n  )\n}\n\n/**\n * The Calendar to the month or the year: a year's twelve months, or twelve\n * years, drawn as the day calendar's heading draws them in its popover. To\n * the month, the year's name steps out to twelve years, and a year picked\n * there steps back in to its months.\n */\nfunction ChoiceCalendar({\n  granularity,\n  value: valueProp,\n  defaultValue,\n  onValueChange,\n  min: minProp,\n  max: maxProp,\n  deselectable,\n  disabled: disabledProp,\n  readOnly = false,\n  locale: localeProp,\n  today: todayProp,\n  timeZone,\n  name: nameProp,\n  form,\n  required = false,\n  invalid: invalidProp,\n  labels: labelsProp,\n  className,\n  ref,\n  'aria-label': ariaLabel,\n  'aria-labelledby': ariaLabelledBy,\n  'aria-describedby': ariaDescribedBy,\n  mode,\n  ...rest\n}: CalendarChoiceProps) {\n  // Only ever single here, and not an attribute of the root.\n  // oxlint-disable-next-line typescript/no-meaningless-void-operator -- marks a prop kept out of the rest\n  void mode\n  const locale = useLocale(localeProp)\n  const clock = useToday(timeZone)\n  const today = isISODate(todayProp) ? todayProp : clock\n  const labels = { ...CALENDAR_LABELS, ...labelsProp }\n  const bounds = { min: boundDay(minProp, 'start'), max: boundDay(maxProp, 'end') }\n  const final: ChoiceLevel = granularity === 'month' ? 'months' : 'years'\n  const fits = granularity === 'month' ? isISOMonth : isISOYear\n\n  const [given, pick] = useControllable<\n    string | null,\n    [{ reason: 'item-press' | 'reset'; event?: Event }]\n  >(valueProp, defaultValue ?? null, onValueChange)\n  const value = fits(given) ? given : null\n\n  // The picked month, as the picker marks it: a year's first month for a year.\n  const picked = value === null ? null : granularity === 'month' ? value : `${value}-01`\n  const around = monthParts(picked ?? (today ? monthOf(today) : '2000-01')).year\n  const opensOn =\n    final === 'months'\n      ? { level: final, year: around }\n      : { level: final, year: yearPage(around, CHOICES) }\n\n  const [root, setRoot] = useState<HTMLDivElement | null>(null)\n  const focus = useCallback(() => {\n    root\n      ?.querySelector<HTMLElement>('[data-slot=calendar-choices-choice][tabindex=\"0\"]')\n      ?.focus({ preventScroll: true })\n  }, [root])\n  const naming = useCalendarNaming(\n    {\n      id: rest.id,\n      'aria-label': ariaLabel,\n      'aria-labelledby': ariaLabelledBy,\n      'aria-describedby': ariaDescribedBy,\n    },\n    disabledProp === true,\n    focus,\n  )\n  const disabled = disabledProp === true || naming.field?.disabled === true\n  const name = nameProp ?? naming.field?.name\n  const invalid = invalidProp ?? naming.invalid\n  const rootRef = useMemo(\n    () => mergeRefs<HTMLDivElement>(ref, setRoot, naming.ref),\n    [ref, naming.ref],\n  )\n\n  return (\n    <div\n      role='group'\n      data-calendar=''\n      data-calendar-granularity={granularity}\n      data-disabled={disabled ? '' : undefined}\n      data-readonly={readOnly ? '' : undefined}\n      data-invalid={invalid ? '' : undefined}\n      {...rest}\n      {...naming.props}\n      ref={rootRef}\n      className={cn(calendarClassName, 'gap-1', invalidClassName, motion, className)}\n    >\n      <CalendarForm\n        name={name}\n        form={form}\n        required={required}\n        dates={value === null ? [] : [value]}\n        disabled={disabled}\n        focus={focus}\n        reset={(event) => {\n          if (keptOnReset(valueProp, defaultValue)) return\n          const initial = fits(defaultValue) ? defaultValue : null\n          if (initial !== value) pick(initial, { reason: 'reset', event })\n        }}\n      />\n      {today === null && todayProp === undefined ? (\n        // The server can't know the visitor's today, which the page opens around.\n        <CalendarPending />\n      ) : (\n        <ChoicePicker\n          labels={labels}\n          locale={locale}\n          bounds={bounds}\n          today={today}\n          picked={picked}\n          opensOn={opensOn}\n          final={final}\n          disabled={disabled}\n          readOnly={readOnly}\n          name={naming.props}\n          onPick={(next, event) => {\n            if (readOnly) return\n            const details = { reason: 'item-press' as const, event }\n            if (next === value) {\n              if (deselectable) pick(null, details)\n              return\n            }\n            pick(next, details)\n          }}\n        />\n      )}\n    </div>\n  )\n}\n\nexport {\n  Calendar,\n  CalendarDay,\n  CalendarGrid,\n  CalendarHeading,\n  CalendarMonths,\n  CalendarNext,\n  CalendarPrevious,\n}\nexport type {\n  CalendarChangeDetails,\n  CalendarChoiceProps,\n  CalendarDayProps,\n  CalendarProps,\n}\n",
      "type": "registry:component",
      "target": "@components/kino/calendar.tsx"
    },
    {
      "path": "registry/lib/calendar-model.ts",
      "content": "import {\n  monthName,\n  monthOf,\n  monthParts,\n  monthsBetween,\n  shiftMonth,\n  yearLabel,\n  yearMonth,\n} from '@/registry/lib/dates'\n\n/*\n * What the Calendar decides around ui-sdk's, as pure functions of plain\n * values: the pages of months and years its heading opens, where a month\n * picked there puts the months on screen, which way they travel, and which\n * days several picks have no room left for. The dates themselves are worked\n * out in `registry/lib/dates.ts`.\n */\n\n/** The first and last days that can be picked, as `yyyy-mm-dd`. */\nexport interface CalendarBounds {\n  min?: string\n  max?: string\n}\n\n/**\n * The days a multiple pick has no room left for once `maxDays` are picked:\n * every day not picked, so a picked one can still be taken out. Null while\n * there is room, or with no limit.\n */\nexport function fullDays(\n  picked: readonly string[],\n  maxDays: number | undefined,\n): ((date: string) => boolean) | null {\n  if (maxDays === undefined || picked.length < maxDays) return null\n  return (date) => !picked.includes(date)\n}\n\n/**\n * The first month on screen so that the month at `offset` (0 for the first\n * of `count`) is `target`, held as paging holds it: no month on screen lies\n * wholly before `min` or after `max`, so near an end `target` shows in\n * another place.\n */\nexport function firstShownFor(\n  target: string,\n  offset: number,\n  count: number,\n  rules: CalendarBounds,\n): string {\n  let first = shiftMonth(target, -offset)\n  const lowest = rules.min ? monthOf(rules.min) : null\n  const highest = rules.max ? shiftMonth(monthOf(rules.max), -(count - 1)) : null\n  if (highest !== null && first > highest) first = highest\n  if (lowest !== null && first < lowest) first = lowest\n  return first\n}\n\n/** A month or year to choose from, as a picker of months or years lists it. */\nexport interface CalendarChoice {\n  /** The month as `yyyy-mm`, or the year as its number. */\n  value: string\n  label: string\n  /** Wholly before `min` or after `max`, or outside years 1 to 9999. */\n  disabled: boolean\n}\n\n/** The twelve months of `year`, named in `locale`. */\nexport function monthChoices(\n  year: number,\n  rules: CalendarBounds,\n  locale: string,\n): CalendarChoice[] {\n  // A year before 1 or after 9999 has no months to name or choose.\n  if (year < 1 || year > 9999)\n    return Array.from({ length: 12 }, (_, index) => ({\n      value: `${year}:${index + 1}`,\n      label: '',\n      disabled: true,\n    }))\n  return Array.from({ length: 12 }, (_, index) => {\n    const value = yearMonth(year, index + 1)\n    return {\n      value,\n      label: monthName(value, locale, 'short'),\n      disabled:\n        (!!rules.min && value < monthOf(rules.min)) ||\n        (!!rules.max && value > monthOf(rules.max)),\n    }\n  })\n}\n\n/** `count` years from `from`, written in `locale`; a year outside 1 to 9999 has no name and can't be chosen. */\nexport function yearChoices(\n  from: number,\n  count: number,\n  rules: CalendarBounds,\n  locale: string,\n): CalendarChoice[] {\n  const lowest = rules.min ? monthParts(monthOf(rules.min)).year : 1\n  const highest = rules.max ? monthParts(monthOf(rules.max)).year : 9999\n  return Array.from({ length: count }, (_, index) => {\n    const year = from + index\n    const real = year >= 1 && year <= 9999\n    return {\n      value: String(year),\n      label: real ? yearLabel(year, locale) : '',\n      disabled: !real || year < lowest || year > highest,\n    }\n  })\n}\n\n/** A picker of months shows a year's twelve; a picker of years, twelve years. */\nexport type ChoiceLevel = 'months' | 'years'\n\n/** How many months or years a page of choices holds. */\nexport const CHOICES = 12\n\n/** The first and last years that hold a day between `min` and `max`, within years 1 to 9999. */\nfunction yearBounds(rules: CalendarBounds) {\n  return {\n    lowest: Math.max(1, rules.min ? monthParts(monthOf(rules.min)).year : 1),\n    highest: Math.min(9999, rules.max ? monthParts(monthOf(rules.max)).year : 9999),\n  }\n}\n\n/**\n * The page of choices `direction` from the one at `start` (a year, or the\n * first of twelve years), or null when it holds nothing that can be chosen,\n * so the arrows and keys never land on a page of faded choices.\n */\nexport function choicePageTurn(\n  level: ChoiceLevel,\n  start: number,\n  direction: 1 | -1,\n  rules: CalendarBounds,\n): number | null {\n  const next = start + direction * (level === 'months' ? 1 : CHOICES)\n  const last = level === 'months' ? next : next + CHOICES - 1\n  const { lowest, highest } = yearBounds(rules)\n  return next <= highest && last >= lowest ? next : null\n}\n\n/** What a picker of months or years shows on the page at `start`, around the month `shown`, if any. */\nexport interface ChoicePage {\n  choices: CalendarChoice[]\n  /** The year, or the first and last of the twelve. */\n  title: string\n  /** The index of `shown`'s month or year, or -1. */\n  current: number\n  /** The index of today's month or year, or -1. */\n  today: number\n  /** The pages either side, or null where there is nothing to choose. */\n  previous: number | null\n  next: number | null\n}\n\nexport function choicePage(\n  level: ChoiceLevel,\n  start: number,\n  {\n    shown,\n    today,\n    rules,\n    locale,\n  }: {\n    shown: string | null\n    today: string | null\n    rules: CalendarBounds\n    locale: string\n  },\n): ChoicePage {\n  const name = (year: number) => (year < 1 || year > 9999 ? '' : yearLabel(year, locale))\n  const at = shown ? monthParts(shown) : null\n  const now = today ? monthParts(monthOf(today)) : null\n  const index = (target: { year: number; month: number } | null) => {\n    if (!target) return -1\n    if (level === 'months') return target.year === start ? target.month - 1 : -1\n    const offset = target.year - start\n    return offset >= 0 && offset < CHOICES ? offset : -1\n  }\n  return {\n    choices:\n      level === 'months'\n        ? monthChoices(start, rules, locale)\n        : yearChoices(start, CHOICES, rules, locale),\n    title:\n      level === 'months'\n        ? name(start)\n        : [name(Math.max(start, 1)), name(Math.min(start + CHOICES - 1, 9999))]\n            .filter(Boolean)\n            .join(' – '),\n    current: index(at),\n    today: index(now),\n    previous: choicePageTurn(level, start, -1, rules),\n    next: choicePageTurn(level, start, 1, rules),\n  }\n}\n\n/** Which way the months moved from `from` to `to`: 1 forward, -1 back, and `last` when there is nothing to compare. */\nexport function travelTrend(\n  from: string | null,\n  to: string | null,\n  last: 1 | -1,\n): 1 | -1 {\n  if (!from || !to || from === to) return last\n  return monthsBetween(from, to) < 0 ? -1 : 1\n}\n",
      "type": "registry:lib",
      "target": "@lib/calendar-model.ts"
    },
    {
      "path": "registry/lib/calendar-grid.tsx",
      "content": "'use client'\n\nimport { IconPlaceholder } from '@/registry/icons/icon-placeholder'\nimport { travelTrend } from '@/registry/lib/calendar-model'\nimport type { Weekday } from '@/registry/lib/dates'\nimport { Swap } from '@/registry/lib/swap'\nimport { isRTL } from '@ui-sdk/core'\nimport { Component, createContext, type ReactNode, use, useEffect, useState } from 'react'\n\nimport { cn } from '@/lib/utils'\n\n/*\n * How the Calendar looks around ui-sdk's parts, wherever they sit: in the\n * Calendar or in the Date picker's popup. The look is the Tabs' and the Date\n * input's: a backdrop glides under the pointer, a pill in the primary colour\n * slides to the picked day, and a range is a band from its start to its end\n * that grows and shrinks along each week. The arrows turn the months, which\n * slide a short way the way they travel.\n */\n\n/** What the Calendar's own words say, in English unless a buyer passes their own. */\ninterface CalendarLabels {\n  previousMonth: string\n  nextMonth: string\n  /** The button on a month's name, which opens its months: \"November 2026, choose a month\". */\n  chooseMonth: (month: string) => string\n  /** The button on a year's name, which opens its years: \"2026, choose a year\". */\n  chooseYear: (year: string) => string\n  months: string\n  years: string\n  /** The column of week numbers. */\n  weekNumbers: string\n  previousYear: string\n  nextYear: string\n  previousYears: string\n  nextYears: string\n  /** A week's number, as a screen reader hears it: \"Week 46\". */\n  week: (week: number) => string\n}\n\nconst CALENDAR_LABELS: CalendarLabels = {\n  previousMonth: 'Previous month',\n  nextMonth: 'Next month',\n  chooseMonth: (month) => `${month}, choose a month`,\n  chooseYear: (year) => `${year}, choose a year`,\n  months: 'Choose a month',\n  years: 'Choose a year',\n  weekNumbers: 'Week',\n  previousYear: 'Previous year',\n  nextYear: 'Next year',\n  previousYears: 'Previous years',\n  nextYears: 'Next years',\n  week: (week) => `Week ${week}`,\n}\n\n/** What a day shows under its full date, which a screen reader hears first: its number, or the buyer's own content for it. */\ntype DayContent = (date: string) => ReactNode\n\n/** What the parts around ui-sdk's need to know, from the Calendar or the Date picker. */\ninterface CalendarLook {\n  mode: 'single' | 'multiple' | 'range'\n  disabled: boolean\n  locale: string\n  labels: CalendarLabels\n  weekStartsOn: Weekday\n  months: number\n  showWeekNumbers: boolean\n  dayContent?: DayContent\n  /** How a month's name is written in its heading. */\n  monthFormat: 'long' | 'short' | 'narrow'\n  /** Days several picks have no room left for, which fade rather than strike through. */\n  full: ((date: string) => boolean) | null\n  /** The first and last days that can be picked, as `yyyy-mm-dd`. */\n  bounds: { min?: string; max?: string }\n  /** Today, as `yyyy-mm-dd`; null while the server renders. */\n  today: string | null\n  /** Shows `month` (`yyyy-mm`) first, as a pick in a heading's popover does. */\n  showMonth: (month: string) => void\n}\n\nconst CalendarLookContext = createContext<CalendarLook | null>(null)\n\nfunction useCalendarLook(): CalendarLook {\n  const look = use(CalendarLookContext)\n  if (!look)\n    throw new Error('Calendar parts must be used inside <Calendar> or <DatePicker>.')\n  return look\n}\n\nconst DAY = '[data-slot=calendar-day]'\n\n/**\n * Seven columns, each as wide as a control is tall, so a day is square and,\n * in the Round shape, a circle. In a narrower column they shrink together.\n */\nconst weekLayout =\n  'relative grid w-full grid-cols-[repeat(7,minmax(0,var(--control-height)))] group-data-week-numbers/calendar:grid-cols-[var(--calendar-week-width)_repeat(7,minmax(0,var(--control-height)))]'\n\n/** The weekdays' row, shared by the row and the pill's copy of it, so the copy's weeks sit on the days below it. */\nconst weekdaysClassName = 'mb-1 h-[calc(var(--control-height)*0.75)]'\n\n/** A week's number, in the column before its days. */\nconst weekNumberClassName =\n  'flex items-center justify-center text-xs text-muted-foreground tabular-nums'\n\n/** A day's box, shared by the day and the pill's copy of it, so each label sits on its twin. Each sits 1px in from its column, so days stand 2px apart across and down alike. */\nconst dayLayout =\n  'relative m-px flex aspect-square min-w-0 items-center justify-center rounded-(--control-radius) text-sm tabular-nums select-none data-today:font-medium'\n\n/**\n * A day's colours. Days of the months either side are quieter, an\n * unavailable day is struck through, one several picks have no room for and\n * one that can't be picked fade. A range's ends and the days of a multiple\n * pick fill with the primary colour; in single mode the pill does that, and\n * draws the pick itself until the page hydrates.\n */\nconst dayClassName = cn(\n  dayLayout,\n  'text-foreground transition-[color,background-color,box-shadow] duration-(--motion-press-duration) ease-(--motion-press-fade-easing) focus-visible:z-10 focus-visible:ring-3 focus-visible:ring-ring/50 focus-visible:outline-hidden',\n  'data-outside:text-muted-foreground data-unavailable:text-muted-foreground data-unavailable:line-through data-full:no-underline data-full:text-foreground/30 [&[data-disabled]]:text-foreground/30 data-outside:[&[data-disabled]]:text-foreground/30',\n  // Over the backdrop or inside a range, a quiet day darkens so it still reads at 4.5:1.\n  'data-outside:not-data-disabled:data-glided:text-foreground/70 data-outside:not-data-disabled:data-range-middle:text-foreground/70',\n  'group-data-[mode=multiple]/calendar:data-[selected]:bg-primary group-data-[mode=multiple]/calendar:data-[selected]:text-primary-foreground',\n  'data-range-start:bg-primary data-range-start:text-primary-foreground data-range-end:bg-primary data-range-end:text-primary-foreground',\n  // A pick that can't be taken again (a range's start, when no stay that short is allowed) keeps its pick's colours.\n  'data-range-start:[&[data-disabled]]:text-primary-foreground data-range-end:[&[data-disabled]]:text-primary-foreground group-data-[mode=multiple]/calendar:data-[selected]:[&[data-disabled]]:text-primary-foreground forced-colors:data-range-start:[&[data-disabled]]:text-[HighlightText] forced-colors:data-range-end:[&[data-disabled]]:text-[HighlightText] forced-colors:group-data-[mode=multiple]/calendar:data-[selected]:[&[data-disabled]]:text-[HighlightText]',\n  '[[data-calendar-month]:not([data-mounted])_&]:data-[selected]:not-data-outside:bg-primary [[data-calendar-month]:not([data-mounted])_&]:data-[selected]:not-data-outside:text-primary-foreground',\n  'forced-colors:data-range-start:forced-color-adjust-none forced-colors:data-range-end:forced-color-adjust-none forced-colors:group-data-[mode=multiple]/calendar:data-[selected]:forced-color-adjust-none forced-colors:data-range-start:bg-[Highlight] forced-colors:data-range-start:text-[HighlightText] forced-colors:data-range-end:bg-[Highlight] forced-colors:data-range-end:text-[HighlightText] forced-colors:group-data-[mode=multiple]/calendar:data-[selected]:bg-[Highlight] forced-colors:group-data-[mode=multiple]/calendar:data-[selected]:text-[HighlightText] forced-colors:data-range-middle:outline-1 forced-colors:data-range-middle:-outline-offset-4 forced-colors:data-range-middle:outline-dashed',\n  // Those picks keep their own colours, so their focus outline needs a system colour; a range's middle trades its dashes for the outline.\n  'forced-colors:data-range-start:focus-visible:outline-[CanvasText] forced-colors:data-range-end:focus-visible:outline-[CanvasText] forced-colors:group-data-[mode=multiple]/calendar:data-[selected]:focus-visible:outline-[CanvasText] forced-colors:data-range-middle:focus-visible:outline-2 forced-colors:data-range-middle:focus-visible:outline-offset-0 forced-colors:data-range-middle:focus-visible:outline-solid',\n)\n\n/**\n * The band behind a week's days in a range, from the first column the range\n * covers in that week to the last. It is as large as the week and clipped to\n * those columns, so it grows and shrinks on `layout` as the end moves; a\n * week the range leaves closes towards the side the range comes from. A\n * month that has just come in draws its bands in place, with no move.\n */\nconst bandClassName =\n  'pointer-events-none absolute inset-y-0 start-0 end-0 -z-10 group-data-week-numbers/calendar:start-(--calendar-week-width) rounded-(--control-radius) bg-primary/12 transition-none [--band-from:0] [--band-to:0] [clip-path:inset(1px_calc((7-var(--band-to))/7*100%+1px)_1px_calc(var(--band-from)/7*100%+1px)_round_var(--control-radius-capped))] rtl:[clip-path:inset(1px_calc(var(--band-from)/7*100%+1px)_1px_calc((7-var(--band-to))/7*100%+1px)_round_var(--control-radius-capped))] duration-(--motion-layout-duration) ease-(--motion-layout-easing) data-empty:opacity-0 data-empty:duration-(--motion-exit-duration) data-preview:bg-primary/8 [[data-calendar-month][data-mounted]_&]:transition-[opacity,clip-path] motion-reduce:[[data-calendar-month][data-mounted]_&]:transition-[opacity]'\n\n/** A day as its week's band reads it. */\ninterface BandCell {\n  /** An empty cell: an outside day that's hidden, or one another month beside shows. */\n  hidden: boolean\n  rangeStart: boolean\n  rangeMiddle: boolean\n  rangeEnd: boolean\n  /** Part of a range still being picked. */\n  preview: boolean\n}\n\n/** The columns a week's band covers, from and to (exclusive); an empty band sits at zero width where the range enters. */\nfunction bandColumns(week: readonly BandCell[]): {\n  from: number\n  to: number\n  empty: boolean\n  preview: boolean\n} {\n  const covered = week.flatMap((cell, column) =>\n    !cell.hidden && (cell.rangeStart || cell.rangeMiddle || cell.rangeEnd)\n      ? [column]\n      : [],\n  )\n  if (covered.length === 0) return { from: 0, to: 0, empty: true, preview: false }\n  return {\n    from: covered[0],\n    to: covered[covered.length - 1] + 1,\n    // One day alone is the start's own pill: no band shows around it.\n    empty: covered.length === 1 && !week[covered[0]].rangeMiddle,\n    preview: week.some((cell) => cell.preview),\n  }\n}\n\n/** A week's cells as the band reads them from the page: ui-sdk marks each day, and an empty cell is ours. */\nfunction bandCellsOf(row: Element): BandCell[] {\n  return [...row.querySelectorAll<HTMLElement>(`${DAY}, [data-calendar-empty]`)].map(\n    (cell) => ({\n      hidden: cell.hasAttribute('data-calendar-empty'),\n      rangeStart: cell.hasAttribute('data-range-start'),\n      rangeMiddle: cell.hasAttribute('data-range-middle'),\n      rangeEnd: cell.hasAttribute('data-range-end'),\n      preview: cell.hasAttribute('data-preview'),\n    }),\n  )\n}\n\n/** Keeps each week's band on the days ui-sdk marks as the range, as they change. */\nfunction followBands(area: HTMLElement): () => void {\n  const draw = () => {\n    for (const row of area.querySelectorAll<HTMLElement>('[data-calendar-week]')) {\n      const band = row.querySelector<HTMLElement>('[data-calendar-band]')\n      if (!band) continue\n      const { from, to, empty, preview } = bandColumns(bandCellsOf(row))\n      band.style.setProperty('--band-from', String(from))\n      band.style.setProperty('--band-to', String(empty ? from : to))\n      band.toggleAttribute('data-empty', empty)\n      band.toggleAttribute('data-preview', preview)\n    }\n  }\n  draw()\n  const observer = new MutationObserver(draw)\n  observer.observe(area, {\n    subtree: true,\n    childList: true,\n    attributeFilter: [\n      'data-range-start',\n      'data-range-middle',\n      'data-range-end',\n      'data-preview',\n    ],\n  })\n  return () => observer.disconnect()\n}\n\ntype GridWeeks = readonly (readonly { date: string; hidden: boolean }[])[]\n\n/** The month a grid shows now, which tells a month leaving from the one in place. */\nconst ShownMonthContext = createContext<string | null>(null)\n\n/**\n * A month's grid that slides away as a still picture of itself: ui-sdk's\n * days follow their grid's month, so a copy left to render would show the\n * new month twice. The picture is the page as it last showed, without its\n * ids or tab stops.\n */\nclass Still extends Component<{ live: boolean; children: ReactNode }> {\n  private box: HTMLDivElement | null = null\n  private picture: Node | null = null\n\n  getSnapshotBeforeUpdate(previous: { live: boolean }) {\n    // Back in place, the picture makes way for the month itself.\n    if (!previous.live && this.props.live) this.box?.replaceChildren()\n    if (previous.live && !this.props.live && this.box) {\n      const copy = this.box.cloneNode(true) as HTMLElement\n      for (const element of copy.querySelectorAll('[id], [tabindex]')) {\n        element.removeAttribute('id')\n        element.removeAttribute('tabindex')\n      }\n      this.picture = copy\n    }\n    return null\n  }\n\n  componentDidUpdate() {\n    if (!this.props.live && this.box && this.picture) {\n      this.box.replaceChildren(...this.picture.childNodes)\n      this.picture = null\n    }\n  }\n\n  render() {\n    return (\n      <div\n        ref={(element) => {\n          this.box = element\n        }}\n        className='contents'\n      >\n        {this.props.live ? this.props.children : null}\n      </div>\n    )\n  }\n}\n\n/** What leaves a Swap as a still picture once its month is no longer the grid's. */\nfunction MonthStill({ month, children }: { month: string; children: ReactNode }) {\n  const shown = use(ShownMonthContext)\n  return <Still live={shown === month}>{children}</Still>\n}\n\n/** The way the months travel, from the last month to this one: 1 forward, -1 back. */\nfunction useTrend(month: string): 1 | -1 {\n  const [seen, setSeen] = useState({ month, trend: 1 as 1 | -1 })\n  if (seen.month !== month) {\n    const trend = travelTrend(seen.month, month, seen.trend)\n    setSeen({ month, trend })\n    return trend\n  }\n  return seen.trend\n}\n\n/** A month's column: as wide as seven days, shrinking together where there isn't room. */\nconst columnLayout =\n  'flex max-w-[calc(var(--control-height)*7)] min-w-0 flex-[1_1_calc(var(--control-height)*7)] flex-col group-data-week-numbers/calendar:max-w-[calc(var(--control-height)*7+var(--calendar-week-width))] group-data-week-numbers/calendar:flex-[1_1_calc(var(--control-height)*7+var(--calendar-week-width))]'\n\n/** A month's heading row, with room at either end for the arrows that turn the months. */\nconst calendarHeadingClassName =\n  'flex h-(--control-height-sm) min-w-0 items-center justify-center gap-1 px-[calc(var(--control-height-sm)+0.25rem)] text-sm font-medium'\n\ntype Edges = Pick<DOMRect, 'top' | 'left' | 'right'>\n\n/** Where the arrows sit, in px from the months' edges: Previous on the first month's heading, Next on the last's. */\nfunction turnInsets(root: Edges, first: Edges, last: Edges, rtl: boolean) {\n  return {\n    previousStart: rtl ? root.right - first.right : first.left - root.left,\n    nextEnd: rtl ? last.left - root.left : root.right - last.right,\n    nextTop: last.top - root.top,\n  }\n}\n\n/**\n * Where `element` sits inside `root`'s padding box, as laid out: unlike its\n * bounding box, this ignores the transforms of months sliding in, so the\n * arrows go straight to where the months come to rest.\n */\nfunction layoutEdges(element: HTMLElement, root: HTMLElement): Edges {\n  let left = 0\n  let top = 0\n  let node: HTMLElement | null = element\n  while (node && node !== root) {\n    left += node.offsetLeft\n    top += node.offsetTop\n    const parent = node.offsetParent as HTMLElement | null\n    if (parent && parent !== root) {\n      left += parent.clientLeft\n      top += parent.clientTop\n    }\n    node = parent\n  }\n  return { left, top, right: left + element.offsetWidth }\n}\n\n/**\n * Keeps the arrows on the first and last month's headings, wherever the\n * months wrap to, by writing their places as CSS variables on `root`. They\n * sit outside the months, so they never leave with a month that turns.\n */\nfunction useTurnPlaces(root: HTMLElement | null) {\n  useEffect(() => {\n    if (!root) return\n    const place = () => {\n      const columns = [...root.querySelectorAll<HTMLElement>('[data-calendar-column]')]\n      const first = columns[0]\n      const last = columns.at(-1)\n      if (!first || !last) return\n      const insets = turnInsets(\n        { left: 0, top: 0, right: root.clientWidth },\n        layoutEdges(first, root),\n        layoutEdges(last, root),\n        isRTL(root),\n      )\n      root.style.setProperty('--calendar-previous-start', `${insets.previousStart}px`)\n      root.style.setProperty('--calendar-next-end', `${insets.nextEnd}px`)\n      root.style.setProperty('--calendar-next-top', `${insets.nextTop}px`)\n    }\n    place()\n    const sized = new ResizeObserver(place)\n    sized.observe(root)\n    return () => sized.disconnect()\n  }, [root])\n}\n\n/** The arrows' places, as `useTurnPlaces` writes them. */\nconst calendarPreviousPlace = 'absolute start-(--calendar-previous-start,0px) top-0 z-10'\nconst calendarNextPlace =\n  'absolute end-(--calendar-next-end,0px) top-(--calendar-next-top,0px) z-10'\n\n/** Where the months go while the server renders: it can't know the visitor's today, so it draws none. */\nfunction CalendarPending() {\n  return (\n    <div\n      aria-hidden\n      data-calendar-pending=''\n      className='aspect-[7/6] w-[calc(var(--control-height)*7)] max-w-full'\n    />\n  )\n}\n\nconst chevrons = {\n  previous: (\n    <IconPlaceholder\n      lucide='ChevronLeftIcon'\n      tabler='IconChevronLeft'\n      hugeicons='ArrowLeft01Icon'\n      phosphor='CaretLeftIcon'\n      remixicon='RiArrowLeftSLine'\n      className='rtl:-scale-x-100'\n      aria-hidden\n    />\n  ),\n  next: (\n    <IconPlaceholder\n      lucide='ChevronRightIcon'\n      tabler='IconChevronRight'\n      hugeicons='ArrowRight01Icon'\n      phosphor='CaretRightIcon'\n      remixicon='RiArrowRightSLine'\n      className='rtl:-scale-x-100'\n      aria-hidden\n    />\n  ),\n}\n\n/** The calendar's root classes, sized by its days. Disabled, its days fade and its names stay readable. */\nconst calendarClassName =\n  'group/calendar flex w-full max-w-fit min-w-0 flex-col gap-(--surface-gap) [--calendar-week-width:calc(var(--control-height)*0.75)]'\n\n/**\n * Content of one month that slides away, the way the months travel, when\n * its grid moves to another month: the old month leaves as a still picture\n * and the new one comes in from the other side.\n */\nfunction MonthSlide({\n  month,\n  block = false,\n  still = true,\n  className,\n  children,\n}: {\n  month: string\n  /** Holds a block, such as the weeks, whose height follows on `layout`. */\n  block?: boolean\n  /**\n   * Leaves as a still picture, for content whose ui-sdk parts follow the\n   * grid's month. Off, the old content stays itself as it leaves, so a\n   * popover in it closes in its own time.\n   */\n  still?: boolean\n  className?: string\n  children: ReactNode\n}) {\n  const trend = useTrend(month)\n  return (\n    <ShownMonthContext value={month}>\n      <Swap slide={trend} id={month} block={block} className={className}>\n        {still ? <MonthStill month={month}>{children}</MonthStill> : children}\n      </Swap>\n    </ShownMonthContext>\n  )\n}\n\nexport {\n  bandClassName,\n  bandColumns,\n  CALENDAR_LABELS,\n  calendarClassName,\n  calendarHeadingClassName,\n  CalendarLookContext,\n  calendarNextPlace,\n  CalendarPending,\n  calendarPreviousPlace,\n  chevrons,\n  columnLayout,\n  DAY,\n  dayClassName,\n  dayLayout,\n  followBands,\n  MonthSlide,\n  turnInsets,\n  useCalendarLook,\n  useTurnPlaces,\n  weekdaysClassName,\n  weekLayout,\n  weekNumberClassName,\n}\nexport type { BandCell, CalendarLabels, CalendarLook, DayContent, GridWeeks }\n",
      "type": "registry:lib",
      "target": "@lib/calendar-grid.tsx"
    },
    {
      "path": "registry/lib/calendar-choices.tsx",
      "content": "'use client'\n\nimport type { CalendarChoice } from '@/registry/lib/calendar-model'\nimport {\n  followPick,\n  followPointer,\n  highlightClassName,\n  itemMatching,\n  pickClassName,\n} from '@/registry/lib/highlight'\nimport { pillBackdropClassName, pillClassName } from '@/registry/lib/pill'\nimport { markMounted } from '@/registry/lib/refs'\nimport {\n  type ChangeDetails,\n  createChange,\n  createRovingFocus,\n  definePrimitive,\n} from '@ui-sdk/core'\nimport { type PrimitiveHandle, usePart, usePrimitive } from '@ui-sdk/react/primitive'\nimport { useEffect, useRef } from 'react'\n\nimport { cn } from '@/lib/utils'\n\n/*\n * Twelve months or twelve years to pick from, drawn as the Calendar draws\n * its days: a backdrop under the pointer, a pill on the current one, and the\n * arrow keys of a grid. A key that moves past an edge turns the page. Three\n * to a row in a month's width; in a taller box its rows spread out to fill it.\n */\n\n/** Three choices to a row, in a month's width. */\nconst COLUMNS = 3\n\n/**\n * Where a key sends focus in a grid of `count` cells, `columns` wide: the\n * arrows a cell or a row (left and right swapped in right to left), Home and\n * End the row's ends. Null for a key the grid doesn't handle; a number below\n * 0 or from `count` up is a move past its edge, which turns the page.\n */\nfunction cellTarget(\n  index: number,\n  key: string,\n  { columns, rtl = false }: { columns: number; rtl?: boolean },\n): number | null {\n  const side = rtl ? -1 : 1\n  const row = index - (index % columns)\n  const moves: Record<string, number> = {\n    ArrowLeft: index - side,\n    ArrowRight: index + side,\n    ArrowUp: index - columns,\n    ArrowDown: index + columns,\n    Home: row,\n    End: row + columns - 1,\n  }\n  return key in moves ? moves[key] : null\n}\n\n/** A choice as the grid holds it: `value` is its key. */\ntype Choice = Pick<CalendarChoice, 'label' | 'disabled'> & { value: string }\n\ninterface CalendarChoicesOptions {\n  /** The choices on this page, in order. */\n  choices?: readonly Choice[]\n  /** The value of the one on screen now, or null. */\n  value?: string | null\n  /** A choice was picked. */\n  onValueChange?: (value: string, details: ChangeDetails<'item-press'>) => void\n  /**\n   * Turns the page when a key moves past the grid's edge, to land on choice\n   * `index` of the new page, which takes focus once it is drawn. Focus stays\n   * where it is when there is no page that way.\n   */\n  onPage?: (step: 1 | -1, index: number) => void\n  /** The choices can be looked through but not picked. */\n  readOnly?: boolean\n  disabled?: boolean\n}\n\nconst calendarChoices = definePrimitive({\n  name: 'calendar-choices',\n  options: {\n    choices: 'list',\n    value: 'string',\n    onValueChange: 'callback',\n    onPage: 'callback',\n    readOnly: 'boolean',\n    disabled: 'boolean',\n  },\n  controlled: ['value'],\n  state: (options: CalendarChoicesOptions) => ({\n    value: options.value ?? null,\n    focused: null as string | null,\n  }),\n  sync: (options) => ({ value: options.value ?? null }),\n  api: (context) => {\n    const change = createChange(context)\n    const choiceOf = (value: string) =>\n      (context.options().choices ?? []).find((choice) => choice.value === value)\n    const firstOpen = () =>\n      (context.options().choices ?? []).find((choice) => !choice.disabled)?.value\n    const roving = createRovingFocus(context, {\n      slot: 'choice',\n      key: 'focused',\n      disabled: (item: { props: { disabled?: boolean } }) => !!item.props.disabled,\n      preferred: (item) => item.key === context.store.get().value,\n      claims: (state, item) =>\n        state.value !== null && choiceOf(state.value) && !choiceOf(state.value)?.disabled\n          ? item.key === state.value\n          : item.key === firstOpen(),\n      move: (event, { from, items, rtl }) => {\n        if (event.altKey || event.ctrlKey || event.metaKey) return\n        const choices = context.options().choices ?? []\n        const index = choices.findIndex((choice) => choice.value === from.key)\n        const target = cellTarget(index, event.key, { columns: COLUMNS, rtl })\n        if (target === null) return\n        // Past an edge the page turns, and the new page focuses where the key lands.\n        if (target < 0) {\n          context.options().onPage?.(-1, target + choices.length)\n          return from.key\n        }\n        if (target >= choices.length) {\n          context.options().onPage?.(1, target - choices.length)\n          return from.key\n        }\n        return items.find((item) => item.key === choices[target].value)?.key ?? from.key\n      },\n    })\n    /** Picks a choice, as a press on it does. */\n    const setValue = (value: string, event?: Event) => {\n      const { readOnly, disabled } = context.options()\n      const choice = choiceOf(value)\n      if (!choice) {\n        throw new Error(\n          `No choice \"${value}\". Choices: ${(context.options().choices ?? []).map((item) => item.value).join(', ')}.`,\n        )\n      }\n      if (readOnly || disabled || choice.disabled) return false\n      return change('value', value, { reason: 'item-press', event })\n    }\n    return {\n      roving,\n      setValue,\n      /** The choices on the page, for an agent. */\n      choices: () =>\n        (context.options().choices ?? []).map(({ value, label, disabled }) => ({\n          value,\n          label,\n          disabled,\n        })),\n      keydown(event: KeyboardEvent, el: HTMLElement, value: string) {\n        if (event.defaultPrevented) return\n        if ((event.key === 'Enter' || event.key === ' ') && !event.repeat) {\n          event.preventDefault()\n          setValue(value, event)\n          return\n        }\n        roving.keydown(event, el)\n      },\n    }\n  },\n  slots: (slot) => ({\n    root: slot({\n      role: 'grid',\n      keys: { none: 'Focus stays on a choice, whose keydown handles them.' },\n    }),\n    row: slot({ role: 'row' }),\n    choice: slot<\n      { value: string; today?: boolean; disabled?: boolean },\n      { current: boolean }\n    >({\n      role: 'gridcell',\n      focus: 'roving',\n      props: { value: 'string', today: 'boolean', disabled: 'boolean' },\n      state: (state, { props }) => ({ current: state.value === props.value }),\n      attrs: (state, part) => ({\n        tabindex: part.api.roving.tabIndex(state, part),\n        'aria-selected': String(state.value === part.props.value),\n        'aria-disabled': part.props.disabled ? 'true' : undefined,\n        'aria-current': part.props.today ? 'date' : undefined,\n        'data-current': state.value === part.props.value ? '' : undefined,\n        'data-today': part.props.today ? '' : undefined,\n      }),\n      press: ({ api, props }, event) => {\n        api.setValue(props.value, event)\n      },\n      on: {\n        keydown: (event, { api, el, props }) => {\n          if (el) api.keydown(event as KeyboardEvent, el, props.value)\n        },\n      },\n      bind: (el, part) => part.api.roving.bind(el, part),\n    }),\n  }),\n  agent: { actions: ['setValue'], closed: true, items: (api) => api.choices() },\n})\n\n/** A choice's box, shared by its cell and the pill's copy of it. */\nconst choiceLayout =\n  'relative flex h-(--control-height) items-center justify-center rounded-(--control-radius) text-sm tabular-nums select-none data-today:font-medium'\n\nconst choiceClassName = cn(\n  choiceLayout,\n  'w-full text-foreground transition-[color,box-shadow] duration-(--motion-press-duration) ease-(--motion-press-fade-easing) focus-visible:ring-3 focus-visible:ring-ring/50 focus-visible:outline-hidden aria-disabled:text-foreground/30',\n  // Until the pill's script runs, the current one draws its own pill.\n  '[[data-slot=calendar-choices]:not([data-mounted])_&]:data-current:bg-primary [[data-slot=calendar-choices]:not([data-mounted])_&]:data-current:text-primary-foreground',\n  'forced-colors:data-current:forced-color-adjust-none forced-colors:data-current:bg-[Highlight] forced-colors:data-current:text-[HighlightText] forced-colors:data-current:focus-visible:outline-[CanvasText]',\n)\n\nconst CELL = '[data-slot=calendar-choices-choice]'\n\n/** Twelve months or years as a grid, with the Calendar's backdrop and pill. */\nfunction CalendarChoices({\n  choices,\n  current,\n  today,\n  label,\n  labelledBy,\n  focusOn,\n  readOnly,\n  disabled,\n  onPick,\n  onPage,\n}: {\n  choices: readonly Choice[]\n  /** The value of the one on screen now, or null. */\n  current: string | null\n  /** The value of today's month or year, or null. */\n  today: string | null\n  label: string\n  /** Ids that name the grid in place of `label`, such as a Field's label and the page's title. */\n  labelledBy?: string\n  /** The value to focus once drawn, `stop` for the grid's tab stop, or null to leave focus where it is. */\n  focusOn: string | null\n  readOnly?: boolean\n  disabled?: boolean\n  onPick: (value: string, event: Event | undefined) => void\n  onPage: (step: 1 | -1, index: number) => void\n}) {\n  const grid = usePrimitive(calendarChoices, {\n    choices,\n    value: current,\n    onValueChange: (value, details) => onPick(value, details.event),\n    onPage,\n    readOnly,\n    disabled,\n  })\n  const pillRef = useRef<HTMLSpanElement>(null)\n  const backdropRef = useRef<HTMLSpanElement>(null)\n\n  useEffect(() => {\n    // The pill and its backdrop sit straight inside the grid.\n    const area = pillRef.current?.parentElement\n    if (!area || !pillRef.current || !backdropRef.current) return\n    const stopPick = followPick(area, pillRef.current, {\n      picked: () => area.querySelector<HTMLElement>(`${CELL}[data-current]`),\n      attributes: ['data-current'],\n    })\n    const stopHover = followPointer(area, backdropRef.current, {\n      itemOf: itemMatching(area, CELL),\n      focus: true,\n    })\n    return () => {\n      stopPick()\n      stopHover()\n    }\n  }, [])\n\n  // Once a new page or view is drawn.\n  useEffect(() => {\n    if (focusOn === null) return\n    grid.api.roving.focus(focusOn === 'stop' ? undefined : focusOn)\n  }, [focusOn, grid])\n\n  const rows = Array.from({ length: Math.ceil(choices.length / COLUMNS) }, (_, row) =>\n    choices.slice(row * COLUMNS, row * COLUMNS + COLUMNS),\n  )\n  // Rows share whatever height the box has, each choice in the middle of its\n  // row, up to twice a choice's height a row; in a taller box they sit in the middle.\n  const layout = 'grid h-full grid-cols-3 grid-rows-4 items-center gap-y-0.5'\n\n  const root = usePart(\n    grid,\n    'root',\n    {},\n    {\n      ref: markMounted,\n      'aria-label': labelledBy ? undefined : label,\n      'aria-labelledby': labelledBy,\n      'aria-readonly': readOnly ? 'true' : undefined,\n      'aria-disabled': disabled ? 'true' : undefined,\n      className: cn(\n        layout,\n        'relative isolate max-h-[calc(var(--control-height)*8)] w-full flex-1',\n      ),\n      children: (\n        <>\n          {rows.map((row) => (\n            <ChoiceRow key={row[0].value} grid={grid} row={row} today={today} />\n          ))}\n          <span\n            ref={backdropRef}\n            aria-hidden\n            className={cn(highlightClassName, pillBackdropClassName)}\n          />\n          <span\n            ref={pillRef}\n            aria-hidden\n            inert\n            className={cn(\n              pickClassName,\n              pillClassName,\n              'z-10 group-data-disabled/calendar:data-[highlight=shown]:opacity-50',\n            )}\n          >\n            <span className={layout}>\n              {choices.map((choice) => (\n                <span\n                  key={choice.value}\n                  data-today={choice.value === today ? '' : undefined}\n                  className={choiceLayout}\n                >\n                  {choice.label}\n                </span>\n              ))}\n            </span>\n          </span>\n        </>\n      ),\n    },\n  )\n\n  return (\n    <div className='flex w-[calc(var(--control-height)*7)] max-w-full flex-col'>\n      <div className='flex flex-1 flex-col justify-center'>{root}</div>\n    </div>\n  )\n}\n\nfunction ChoiceRow({\n  grid,\n  row,\n  today,\n}: {\n  grid: PrimitiveHandle<typeof calendarChoices>\n  row: readonly Choice[]\n  today: string | null\n}) {\n  return usePart(\n    grid,\n    'row',\n    {},\n    {\n      className: 'contents',\n      children: row.map((choice) => (\n        <ChoiceCell key={choice.value} grid={grid} choice={choice} today={today} />\n      )),\n    },\n  )\n}\n\nfunction ChoiceCell({\n  grid,\n  choice,\n  today,\n}: {\n  grid: PrimitiveHandle<typeof calendarChoices>\n  choice: Choice\n  today: string | null\n}) {\n  return usePart(\n    grid,\n    'choice',\n    { value: choice.value, today: choice.value === today, disabled: !!choice.disabled },\n    {\n      className: choiceClassName,\n      children: choice.label,\n    },\n    'span',\n  )\n}\n\nexport { CalendarChoices, calendarChoices, cellTarget }\nexport type { Choice }\n",
      "type": "registry:lib",
      "target": "@lib/calendar-choices.tsx"
    }
  ],
  "type": "registry:component"
}