{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "year-view",
  "title": "Year View",
  "author": "vmnog <https://vmnog.com>",
  "description": "The year as twelve month grids, with today and the days that have events marked.",
  "dependencies": [
    "date-fns",
    "react-day-picker@^9"
  ],
  "registryDependencies": [
    "@calendarcn/calendar-core"
  ],
  "files": [
    {
      "path": "src/components/year-view.tsx",
      "content": "\"use client\";\n\nimport {\n  Fragment,\n  useCallback,\n  useEffect,\n  useLayoutEffect,\n  useMemo,\n  useRef,\n} from \"react\";\nimport type { ComponentProps, KeyboardEvent } from \"react\";\nimport { addDays, addYears, format, isWeekend, startOfYear } from \"date-fns\";\nimport {\n  Day as DayPickerDay,\n  DayPicker,\n  Week as DayPickerWeek,\n  Weekday as DayPickerWeekday,\n  type DayButton,\n  type Modifiers,\n} from \"react-day-picker\";\n\nimport { cn } from \"@/lib/utils\";\nimport { useToday } from \"@/hooks/use-now\";\nimport { CalendarLoadingBar } from \"./calendar-loading-bar\";\nimport {\n  useCalendar,\n  useCalendarConfig,\n  useCalendarViewSync,\n} from \"./calendar-provider\";\nimport {\n  countEventsByDay,\n  filterDeclinedEvents,\n  formatCellDate,\n  formatFullDate,\n} from \"@/lib/event-utils\";\nimport { expandRecurringEvents } from \"@/lib/recurrence\";\nimport type { YearViewProps } from \"./week-view-types\";\n\n/**\n * Stand-in for \"today\" on the server and during hydration, where the\n * viewer's date is unknown. No year the view shows contains it, so no day\n * is marked as today and server and client markup match.\n */\nconst UNKNOWN_TODAY = new Date(0);\n\n/** Month grids the view draws: the whole year, from January */\nconst MONTHS_PER_YEAR = 12;\n\n/** DayPicker modifier set on the days that have events */\nconst HAS_EVENTS_MODIFIER = \"hasEvents\";\n\n/**\n * Classes for DayPicker's parts. Months flow two to a row, three from a\n * 42rem wide view and four from 64rem: container queries on the view, so an\n * open sidebar counts. A month shows only its own days.\n */\nconst YEAR_VIEW_CLASS_NAMES = {\n  root: \"w-full\",\n  months:\n    \"grid grid-cols-2 gap-x-4 gap-y-6 p-4 @2xl/year:grid-cols-3 @2xl/year:gap-x-8 @5xl/year:grid-cols-4 @5xl/year:p-6\",\n  month: \"flex min-w-0 flex-col gap-1\",\n  month_caption: \"px-1 pb-1\",\n  caption_label: \"text-sm font-semibold text-foreground\",\n  month_grid: \"w-full table-fixed border-collapse\",\n  weekday: \"h-6 p-0 text-center text-xxs font-normal text-muted-foreground\",\n  week_number_header: \"w-5 p-0\",\n  week_number: \"w-5 p-0 text-center text-xxs text-muted-foreground\",\n  day: \"h-7 p-0 text-center\",\n  hidden: \"invisible\",\n};\n\n/** A day: a 28px box, narrower when its month is, with room for a dot under the number */\nconst DAY_BUTTON_CLASS =\n  \"relative mx-auto flex h-7 w-full max-w-7 cursor-pointer items-center justify-center rounded-sm text-xs tabular-nums text-foreground outline-none select-none hover:bg-calendar-day-hover focus-visible:ring-2 focus-visible:ring-ring\";\n\n/** Today, in red like the mini calendar and month view */\nconst TODAY_BUTTON_CLASS =\n  \"bg-primary font-semibold text-primary-foreground hover:bg-primary/80\";\n\n/** The dot under the number of a day with events */\nconst EVENT_DOT_CLASS =\n  \"pointer-events-none absolute bottom-0.5 left-1/2 size-1 -translate-x-1/2 rounded-full bg-muted-foreground\";\n\n/** Saturday and Sunday, which DayPicker skips while weekends are hidden */\nconst WEEKEND_MATCHER = { dayOfWeek: [0, 6] };\n\n/** A Saturday and a Sunday, to name the weekend's weekday headers */\nconst WEEKEND_DAYS = [new Date(2026, 0, 3), new Date(2026, 0, 4)];\n\n/** Format of a weekday header's accessible name, the full day name */\nconst WEEKDAY_LABEL_FORMAT = \"cccc\";\n\n/** Props DayPicker gives a day's button */\ntype YearViewDayButtonProps = ComponentProps<typeof DayButton>;\n\n/** Props DayPicker gives a day's cell */\ntype YearViewDayProps = ComponentProps<typeof DayPickerDay>;\n\n/** Props DayPicker gives a weekday header */\ntype YearViewWeekdayProps = ComponentProps<typeof DayPickerWeekday>;\n\n/** Props DayPicker gives a week's row */\ntype YearViewWeekProps = ComponentProps<typeof DayPickerWeek>;\n\n/**\n * A day of the year grid: its number, a dot when it has events, today in\n * red. DayPicker moves focus between days by marking one `focused`, so the\n * button focuses itself then, as DayPicker's own day button does.\n */\nfunction YearViewDayButton({\n  day,\n  modifiers,\n  className,\n  children,\n  ...buttonProps\n}: YearViewDayButtonProps) {\n  const ref = useRef<HTMLButtonElement>(null);\n\n  useEffect(() => {\n    if (modifiers.focused) ref.current?.focus();\n  }, [modifiers.focused]);\n\n  const isToday = modifiers.today === true;\n\n  return (\n    <button\n      {...buttonProps}\n      ref={ref}\n      type=\"button\"\n      aria-current={isToday ? \"date\" : undefined}\n      data-date={formatCellDate(day.date)}\n      className={cn(DAY_BUTTON_CLASS, isToday && TODAY_BUTTON_CLASS, className)}\n    >\n      {children}\n      {modifiers[HAS_EVENTS_MODIFIER] && (\n        <span\n          aria-hidden\n          className={cn(EVENT_DOT_CLASS, isToday && \"bg-primary-foreground\")}\n        />\n      )}\n    </button>\n  );\n}\n\n/**\n * The provider's year as twelve month grids, like Google Calendar's year\n * view (Notion Calendar has none): today in red, a dot under every day with\n * events, and a click, Enter or Space on a day opens it (`showDay()`, unless\n * `onDayClick` is set). Arrow keys move between days, Page Up and Page Down\n * by a month, Home and End to the week's ends, and none of them leave the\n * year. Date, events, week start, locale and week numbers come from the\n * surrounding CalendarProvider, which navigates by year while it is mounted.\n */\nexport function YearView({ onDayClick, className }: YearViewProps) {\n  const { currentDate, events, viewSettings, weekStartsOn, showDay, loading } =\n    useCalendar();\n  const { showWeekends, showWeekNumbers, showDeclinedEvents } = viewSettings;\n  const { locale, timeZone } = useCalendarConfig();\n  const { reportView } = useCalendarViewSync();\n  // `null` on the server and during hydration, so no day is marked as today\n  const today = useToday(timeZone);\n  /** The scrolling months, searched for a day's button by its date */\n  const monthsRef = useRef<HTMLDivElement | null>(null);\n\n  // Tell the provider which view is on screen. `reportView` changes with the\n  // provider's state, so this also re-checks after every switch. A layout\n  // effect: the provider adopts year view before the first paint.\n  useLayoutEffect(() => {\n    reportView({ view: \"year\" });\n  }, [reportView]);\n\n  const yearStartTime = startOfYear(currentDate).getTime();\n\n  // Each day's event count, worked out once per change of the events or the\n  // year rather than on every render: DayPicker asks about all 365 days\n  const eventCounts = useMemo(() => {\n    const start = new Date(yearStartTime);\n    const range = { start, end: addYears(start, 1) };\n    // Repeating events count on each of their dates (ADR-007), generated\n    // for the year and never stored, as month view draws them. Declined\n    // events count only while they're shown.\n    const counted = filterDeclinedEvents(\n      expandRecurringEvents(events, range, timeZone),\n      showDeclinedEvents,\n    );\n    return countEventsByDay(counted, range);\n  }, [events, yearStartTime, timeZone, showDeclinedEvents]);\n\n  const modifiers = useMemo(\n    () => ({\n      [HAS_EVENTS_MODIFIER]: (date: Date) =>\n        eventCounts.has(formatCellDate(date)),\n    }),\n    [eventCounts],\n  );\n\n  // A day's name: its date, \"today\", then how many events it has\n  // (\"Thursday, June 4, today, 3 events\")\n  const labels = useMemo(\n    () => ({\n      // Named here, so the weekend's headers can be told apart below\n      labelWeekday: (date: Date) =>\n        format(date, WEEKDAY_LABEL_FORMAT, { locale }),\n      labelDayButton: (date: Date, dayModifiers: Modifiers) => {\n        const parts = [formatFullDate(date, locale)];\n        if (dayModifiers.today) parts.push(\"today\");\n        const count = eventCounts.get(formatCellDate(date)) ?? 0;\n        if (count === 1) parts.push(\"1 event\");\n        if (count > 1) parts.push(`${count} events`);\n        return parts.join(\", \");\n      },\n    }),\n    [eventCounts, locale],\n  );\n\n  const formatters = useMemo(\n    () => ({\n      // The header names the year, so each month is named alone\n      formatCaption: (month: Date) => format(month, \"LLLL\", { locale }),\n      formatWeekNumber: (weekNumber: number) => String(weekNumber),\n    }),\n    [locale],\n  );\n\n  // With weekends hidden, their columns go: no header, no cells, and no row\n  // for a week whose only days in the month are a Saturday or Sunday (May\n  // 31, August 1). DayPicker still lays out seven days a week, so they are\n  // left out here.\n  const components = useMemo(() => {\n    const weekendNames = new Set(\n      WEEKEND_DAYS.map((date) =>\n        format(date, WEEKDAY_LABEL_FORMAT, { locale }),\n      ),\n    );\n    return {\n      DayButton: YearViewDayButton,\n      Day: (cellProps: YearViewDayProps) => {\n        // DayPicker's components return an element: an empty one draws nothing\n        if (!showWeekends && isWeekend(cellProps.day.date)) return <Fragment />;\n        return <DayPickerDay {...cellProps} />;\n      },\n      Week: (rowProps: YearViewWeekProps) => {\n        const hasShownDay = rowProps.week.days.some(\n          (day) => !day.outside && (showWeekends || !isWeekend(day.date)),\n        );\n        if (!hasShownDay) return <Fragment />;\n        return <DayPickerWeek {...rowProps} />;\n      },\n      Weekday: (headerProps: YearViewWeekdayProps) => {\n        const name = headerProps[\"aria-label\"];\n        if (!showWeekends && name && weekendNames.has(name)) {\n          return <Fragment />;\n        }\n        return <DayPickerWeekday {...headerProps} />;\n      },\n    };\n  }, [showWeekends, locale]);\n\n  /**\n   * Home and End go to the first and last weekday of the row while weekends\n   * are hidden: DayPicker would aim at the hidden Sunday or Saturday and\n   * stay put\n   */\n  const handleWeekEndsKeyDown = useCallback(\n    (e: KeyboardEvent<HTMLDivElement>) => {\n      if (showWeekends || (e.key !== \"Home\" && e.key !== \"End\")) return;\n      if (!(e.target instanceof HTMLElement)) return;\n      const days = e.target\n        .closest(\"tr\")\n        ?.querySelectorAll<HTMLButtonElement>(\"button[data-date]\");\n      if (!days || days.length === 0) return;\n      e.preventDefault();\n      e.stopPropagation();\n      (e.key === \"Home\" ? days[0] : days[days.length - 1]).focus();\n    },\n    [showWeekends],\n  );\n\n  const handleDayClick = useCallback(\n    (date: Date) => {\n      if (onDayClick) {\n        onDayClick(date);\n        return;\n      }\n      showDay(date);\n    },\n    [onDayClick, showDay],\n  );\n\n  /**\n   * After a key press on a day, puts focus back on the same day of the year\n   * now on screen when the press changed the year (T, J or K): the focused\n   * button went with the old year, and focus would fall to the page.\n   * February 29 lands on the 28th.\n   */\n  const keepDayFocus = useCallback((date: Date) => {\n    requestAnimationFrame(() => {\n      const months = monthsRef.current;\n      const active = document.activeElement;\n      if (!months || (active && active !== document.body)) return;\n      const sameDay = months.querySelector<HTMLElement>(\n        `[data-date$=\"-${format(date, \"MM-dd\")}\"]`,\n      );\n      const dayBefore = months.querySelector<HTMLElement>(\n        `[data-date$=\"-${format(addDays(date, -1), \"MM-dd\")}\"]`,\n      );\n      (sameDay ?? dayBefore)?.focus();\n    });\n  }, []);\n\n  return (\n    <div\n      className={cn(\n        \"@container/year relative flex h-full flex-col overflow-hidden bg-background\",\n        className,\n      )}\n      aria-busy={loading || undefined}\n    >\n      <div\n        ref={monthsRef}\n        className=\"min-h-0 flex-1 overflow-y-auto overscroll-contain\"\n        onKeyDownCapture={handleWeekEndsKeyDown}\n      >\n        <DayPicker\n          month={new Date(yearStartTime)}\n          numberOfMonths={MONTHS_PER_YEAR}\n          disableNavigation\n          hideNavigation\n          today={today ?? UNKNOWN_TODAY}\n          weekStartsOn={weekStartsOn}\n          locale={locale}\n          showWeekNumber={showWeekNumbers}\n          hidden={showWeekends ? undefined : WEEKEND_MATCHER}\n          modifiers={modifiers}\n          labels={labels}\n          formatters={formatters}\n          classNames={YEAR_VIEW_CLASS_NAMES}\n          components={components}\n          onDayClick={handleDayClick}\n          onDayKeyDown={keepDayFocus}\n        />\n      </div>\n      {/* No header to sit under, so the bar runs along the top, as in the agenda */}\n      {loading && <CalendarLoadingBar className=\"top-0 bottom-auto z-20\" />}\n    </div>\n  );\n}\n",
      "type": "registry:component"
    }
  ],
  "categories": [
    "calendar",
    "views"
  ],
  "type": "registry:component"
}