{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "agenda-view",
  "title": "Agenda View",
  "description": "The coming days' events as a scrolling list, grouped by day.",
  "dependencies": [
    "date-fns",
    "lucide-react"
  ],
  "registryDependencies": [
    "@calendarcn/calendar-core",
    "@calendarcn/event-details"
  ],
  "files": [
    {
      "path": "src/components/agenda-view.tsx",
      "content": "\"use client\";\n\nimport {\n  useCallback,\n  useEffect,\n  useId,\n  useLayoutEffect,\n  useMemo,\n  useRef,\n  useState,\n} from \"react\";\nimport { addDays, format, isSameDay, isSameMonth, isWeekend } from \"date-fns\";\nimport { CalendarCheckIcon } from \"lucide-react\";\n\nimport { cn } from \"@/lib/utils\";\nimport { useEventKeyboard } from \"@/hooks/use-event-keyboard\";\nimport { useIsPast, useNow, useToday } from \"@/hooks/use-now\";\nimport { EventContextMenu } from \"./event-context-menu\";\nimport { EventDetailPopover } from \"./event-detail-popover\";\nimport {\n  CalendarPopoverBoundaryProvider,\n  isEventInsideCalendarPopover,\n} from \"./calendar-popover-context\";\nimport { CalendarLoadingBar } from \"./calendar-loading-bar\";\nimport {\n  EventContentSlot,\n  useCalendar,\n  useCalendarConfig,\n  useCalendarViewSync,\n} from \"./calendar-provider\";\nimport {\n  EVENT_FOCUS_RING_CLASS,\n  eventColorStyles,\n  getEventDetailsTriggerProps,\n} from \"./calendar-event-item\";\nimport {\n  AGENDA_DAYS,\n  formatAgendaDayOfSpan,\n  formatAgendaTime,\n  formatFullDate,\n  getAgendaDays,\n  getEventLabel,\n  getVisibleDays,\n  resolveEventColor,\n} from \"@/lib/event-utils\";\nimport { expandRecurringEvents } from \"@/lib/recurrence\";\nimport type {\n  AgendaDay,\n  AgendaEntry,\n  CalendarEvent,\n  DetailedCalendarEvent,\n} from \"./calendar-types\";\nimport type { AgendaViewProps } from \"./week-view-types\";\n\n/**\n * Box for custom `renderEventContent` output: fills the row after the color\n * accent, inset like the default content\n */\nconst AGENDA_SLOT_CLASS =\n  \"flex min-w-0 flex-1 items-center overflow-hidden px-2.5 py-1.5\";\n\ninterface ContextMenuState {\n  x: number;\n  y: number;\n  event: CalendarEvent;\n}\n\n/** The agenda's days of one month, under that month's label */\ninterface AgendaMonth {\n  /** Start of the first listed day of the month */\n  date: Date;\n  days: AgendaDay[];\n}\n\ninterface AgendaEventRowProps {\n  entry: AgendaEntry;\n  isSelected: boolean;\n  /** Whether this row opens the details popover of the selected event */\n  showPopover: boolean;\n  /** Whether rows open the details in a popover at all */\n  showEventPopover: boolean;\n  onSelect: (event: CalendarEvent) => void;\n  onContextMenu: (e: React.MouseEvent, event: CalendarEvent) => void;\n  onEventChange: (event: CalendarEvent) => void;\n  /** Closes the given event's popover (clears it only while it is still selected) */\n  onPopoverClose: (eventId: string) => void;\n  /** Callback for the popover's expand button (hidden when absent) */\n  onPopoverExpand?: () => void;\n}\n\ninterface AgendaDayGroupProps {\n  day: AgendaDay;\n  isToday: boolean;\n  /** Draws one of the day's entries */\n  renderRow: (day: AgendaDay, entry: AgendaEntry) => React.ReactNode;\n}\n\ninterface AgendaTodayRowsProps {\n  day: AgendaDay;\n  renderRow: (day: AgendaDay, entry: AgendaEntry) => React.ReactNode;\n}\n\ninterface AgendaEmptyStateProps {\n  /** First day of the agenda */\n  from: Date;\n  /** Last day of the agenda */\n  to: Date;\n}\n\n/** Splits the listed days into months, in order */\nfunction groupByMonth(days: AgendaDay[]): AgendaMonth[] {\n  const months: AgendaMonth[] = [];\n  for (const day of days) {\n    const current = months[months.length - 1];\n    if (current && isSameMonth(current.date, day.date)) {\n      current.days.push(day);\n      continue;\n    }\n    months.push({ date: day.date, days: [day] });\n  }\n  return months;\n}\n\n/** Stable key for an entry: an event is listed at most once per day */\nfunction getEntryKey(day: Date, entry: AgendaEntry): string {\n  return `${format(day, \"yyyy-MM-dd\")}:${entry.event.id}`;\n}\n\n/**\n * Index in today's entries where the current-time line goes: before the\n * first timed entry that starts after `now`, or after the last entry\n */\nfunction getNowLineIndex(entries: AgendaEntry[], now: Date): number {\n  const index = entries.findIndex(\n    (entry) =>\n      !entry.isAllDayOnThisDay &&\n      entry.dayIndex === 1 &&\n      entry.event.start > now,\n  );\n  return index === -1 ? entries.length : index;\n}\n\n/**\n * Scrolling list of the coming days' events, grouped by day: `AGENDA_DAYS`\n * days from the provider's date, skipping days without events (today is\n * always shown). Date, events, selection and view settings come from the\n * surrounding CalendarProvider.\n */\nexport function AgendaView({\n  showEventPopover = true,\n  onEventPopoverExpand,\n  className,\n}: AgendaViewProps) {\n  const {\n    view,\n    currentDate,\n    events,\n    viewSettings,\n    selectedEventId,\n    selectEvent,\n    clearSelection,\n    updateEvent,\n    goToDate,\n    loading,\n  } = useCalendar();\n  const { locale } = useCalendarConfig();\n  const { reportView, reportVisibleDays, closeEventPopover } =\n    useCalendarViewSync();\n  // `null` on the server and during hydration, so no day is marked as today\n  const today = useToday();\n  /**\n   * Whether the provider navigates by the agenda's range. False for the\n   * commit before it adopts this view (on mount, or right after a switch it\n   * doesn't follow).\n   */\n  const isProviderInSync = view === \"agenda\";\n  const boundaryRef = useRef<HTMLDivElement | null>(null);\n  /**\n   * Never attached: nothing sits above the list, so the details popover may\n   * use the agenda's full height\n   */\n  const headerRef = useRef<HTMLDivElement | null>(null);\n  const scrollContainerRef = useRef<HTMLDivElement | null>(null);\n\n  const [contextMenu, setContextMenu] = useState<ContextMenuState | null>(null);\n\n  const { showWeekends } = viewSettings;\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 the agenda before the first paint.\n  useLayoutEffect(() => {\n    reportView({ view: \"agenda\" });\n  }, [reportView]);\n\n  const rangeDays = useMemo(\n    () => getVisibleDays(currentDate, \"agenda\", AGENDA_DAYS),\n    [currentDate],\n  );\n  const rangeStart = rangeDays[0];\n  const rangeEnd = rangeDays[rangeDays.length - 1];\n\n  // Report the covered days to the provider (header and range consumers).\n  // Not while it is adopting this view: the date is about to change.\n  useEffect(() => {\n    if (!isProviderInSync) return;\n    reportVisibleDays(rangeDays);\n  }, [isProviderInSync, rangeDays, reportVisibleDays]);\n\n  // A new range starts at the top of the list\n  useEffect(() => {\n    scrollContainerRef.current?.scrollTo({ top: 0 });\n  }, [currentDate]);\n\n  const listedDays = useMemo(() => {\n    // A repeating event is listed under each of its dates in the range\n    const occurrences = expandRecurringEvents(events, {\n      start: rangeStart,\n      end: addDays(rangeEnd, 1),\n    });\n    const days = getAgendaDays(occurrences, currentDate, AGENDA_DAYS);\n    return days.filter((day) => {\n      if (!showWeekends && isWeekend(day.date)) return false;\n      if (day.entries.length > 0) return true;\n      return today !== null && isSameDay(day.date, today);\n    });\n  }, [events, rangeStart, rangeEnd, currentDate, showWeekends, today]);\n\n  const months = useMemo(() => groupByMonth(listedDays), [listedDays]);\n  const hasEvents = listedDays.some((day) => day.entries.length > 0);\n\n  /**\n   * Row that opens the selected event's popover: its first listed day, so\n   * a multi-day event opens it once\n   */\n  const popoverEntryKey = useMemo(() => {\n    if (!selectedEventId || !showEventPopover) return null;\n    for (const day of listedDays) {\n      const entry = day.entries.find((e) => e.event.id === selectedEventId);\n      if (entry) return getEntryKey(day.date, entry);\n    }\n    return null;\n  }, [listedDays, selectedEventId, showEventPopover]);\n\n  const handleSelect = useCallback(\n    (event: CalendarEvent) => selectEvent(event.id),\n    [selectEvent],\n  );\n\n  const handleContextMenu = useCallback(\n    (e: React.MouseEvent, event: CalendarEvent) => {\n      e.preventDefault();\n      setContextMenu({ x: e.clientX, y: e.clientY, event });\n    },\n    [],\n  );\n\n  /** Whether a day is in the agenda's range */\n  const isDayVisible = useCallback(\n    (date: Date) => date >= rangeStart && date < addDays(rangeEnd, 1),\n    [rangeStart, rangeEnd],\n  );\n\n  /** Moves the range a day toward a day just outside it (keyboard moves go a day at most) */\n  const revealDay = useCallback(\n    (date: Date) => {\n      goToDate(addDays(currentDate, date < rangeStart ? -1 : 1));\n    },\n    [currentDate, rangeStart, goToDate],\n  );\n\n  const handleEventKeyDown = useEventKeyboard({\n    containerRef: boundaryRef,\n    scrollContainerRef,\n    isDayVisible,\n    revealDay,\n  });\n\n  const handleRootClick = useCallback(\n    (e: React.MouseEvent<HTMLDivElement>) => {\n      const target = e.target as HTMLElement;\n      if (\n        isEventInsideCalendarPopover(e) ||\n        target.closest(\"button\") ||\n        target.closest(\"[role='button']\")\n      ) {\n        return;\n      }\n      clearSelection();\n    },\n    [clearSelection],\n  );\n\n  const renderRow = (day: AgendaDay, entry: AgendaEntry) => {\n    const key = getEntryKey(day.date, entry);\n    return (\n      <AgendaEventRow\n        key={key}\n        entry={entry}\n        isSelected={entry.event.id === selectedEventId}\n        showPopover={key === popoverEntryKey}\n        showEventPopover={showEventPopover}\n        onSelect={handleSelect}\n        onContextMenu={handleContextMenu}\n        onEventChange={updateEvent}\n        onPopoverClose={closeEventPopover}\n        onPopoverExpand={onEventPopoverExpand}\n      />\n    );\n  };\n\n  return (\n    <CalendarPopoverBoundaryProvider\n      boundaryRef={boundaryRef}\n      headerRef={headerRef}\n      view=\"agenda\"\n    >\n      <div\n        ref={boundaryRef}\n        className={cn(\n          \"@container/agenda relative flex h-full flex-col overflow-hidden bg-background\",\n          className,\n        )}\n        aria-busy={loading || undefined}\n        onClick={handleRootClick}\n        onKeyDown={handleEventKeyDown}\n      >\n        <div\n          ref={scrollContainerRef}\n          className=\"min-h-0 flex-1 overflow-y-auto overscroll-contain\"\n        >\n          {hasEvents ? (\n            months.map((month) => (\n              <div key={month.date.toISOString()}>\n                {/* The day groups' labels carry the month for screen readers */}\n                <div\n                  aria-hidden\n                  className=\"sticky top-0 z-10 border-b border-border bg-background/95 px-3 py-1.5 text-xs font-semibold text-muted-foreground backdrop-blur @xl/agenda:px-6\"\n                >\n                  {format(month.date, \"MMMM yyyy\", { locale })}\n                </div>\n                {month.days.map((day) => (\n                  <AgendaDayGroup\n                    key={day.date.toISOString()}\n                    day={day}\n                    isToday={today !== null && isSameDay(day.date, today)}\n                    renderRow={renderRow}\n                  />\n                ))}\n              </div>\n            ))\n          ) : (\n            <AgendaEmptyState from={rangeStart} to={rangeEnd} />\n          )}\n        </div>\n        {/* No header to sit under, so the bar runs along the top, above the\n            sticky month labels */}\n        {loading && <CalendarLoadingBar className=\"top-0 bottom-auto z-20\" />}\n\n        {contextMenu && (\n          <EventContextMenu\n            event={contextMenu.event}\n            position={{ x: contextMenu.x, y: contextMenu.y }}\n            onClose={() => setContextMenu(null)}\n            onEventChange={updateEvent}\n          />\n        )}\n      </div>\n    </CalendarPopoverBoundaryProvider>\n  );\n}\n\n/**\n * One day of the agenda: its date on the left (today in a badge), its\n * events on the right. A labelled group, like the time grid's day columns\n * and month cells.\n */\nfunction AgendaDayGroup({ day, isToday, renderRow }: AgendaDayGroupProps) {\n  const { locale } = useCalendarConfig();\n  const fullDate = formatFullDate(day.date, locale);\n\n  return (\n    <div\n      role=\"group\"\n      aria-label={isToday ? `${fullDate}, today` : fullDate}\n      data-date={format(day.date, \"yyyy-MM-dd\")}\n      className=\"flex gap-3 border-b border-border px-3 py-2.5 @xl/agenda:gap-5 @xl/agenda:px-6\"\n    >\n      {/* The group's label reads the date out */}\n      <div\n        aria-hidden\n        className=\"flex w-10 shrink-0 flex-col items-center gap-0.5 pt-1\"\n      >\n        <span\n          className={cn(\n            \"text-[11px] leading-none uppercase\",\n            isToday ? \"font-semibold text-primary\" : \"text-muted-foreground\",\n          )}\n        >\n          {format(day.date, \"EEE\", { locale })}\n        </span>\n        <span\n          className={cn(\n            \"flex size-7 items-center justify-center rounded-full text-base tabular-nums\",\n            isToday\n              ? \"bg-primary font-semibold text-primary-foreground\"\n              : \"text-foreground\",\n          )}\n        >\n          {format(day.date, \"d\", { locale })}\n        </span>\n      </div>\n      <div className=\"flex min-w-0 flex-1 flex-col gap-1\">\n        {isToday ? (\n          <AgendaTodayRows day={day} renderRow={renderRow} />\n        ) : (\n          day.entries.map((entry) => renderRow(day, entry))\n        )}\n      </div>\n    </div>\n  );\n}\n\n/**\n * Today's entries with a current-time line between the past and upcoming\n * ones, or a note when today has none. Its own component, so only today\n * re-renders as the clock ticks.\n */\nfunction AgendaTodayRows({ day, renderRow }: AgendaTodayRowsProps) {\n  // `null` on the server and during hydration: no line until then\n  const now = useNow();\n\n  if (day.entries.length === 0) {\n    return (\n      <p className=\"flex min-h-9 items-center text-sm text-muted-foreground\">\n        No events today\n      </p>\n    );\n  }\n\n  const lineIndex = now ? getNowLineIndex(day.entries, now) : -1;\n\n  return day.entries.flatMap((entry, index) => {\n    const row = renderRow(day, entry);\n    const isLastRow = index === day.entries.length - 1;\n    if (index === lineIndex) return [<AgendaNowLine key=\"now\" />, row];\n    if (isLastRow && lineIndex === day.entries.length) {\n      return [row, <AgendaNowLine key=\"now\" />];\n    }\n    return [row];\n  });\n}\n\n/** Red line marking the current time between today's events */\nfunction AgendaNowLine() {\n  return (\n    <div aria-hidden className=\"relative flex h-0 items-center\">\n      <span className=\"absolute -left-1 size-2 rounded-full bg-primary\" />\n      <span className=\"h-0.5 flex-1 rounded-full bg-primary\" />\n    </div>\n  );\n}\n\n/**\n * An event under one of its days: a tinted row in the event's color with\n * its time, title, location and, for a multi-day event, which day this is.\n * Selects the event on click, Enter or Space, and opens the details popover\n * when it is the selected event's first listed day.\n */\nfunction AgendaEventRow({\n  entry,\n  isSelected,\n  showPopover,\n  showEventPopover,\n  onSelect,\n  onContextMenu,\n  onEventChange,\n  onPopoverClose,\n  onPopoverExpand,\n}: AgendaEventRowProps) {\n  const { event } = entry;\n  const { calendars, hourCycle, locale } = useCalendarConfig();\n  const color = resolveEventColor(event, calendars);\n  const styles = eventColorStyles[color];\n  // `false` on the server and during hydration, so the markup matches\n  const eventIsPast = useIsPast(event.end);\n  // Every field is optional: plain events read as details without any\n  const { location }: DetailedCalendarEvent = event;\n  const timeLabel = formatAgendaTime(entry, hourCycle, locale);\n  const dayOfSpan = formatAgendaDayOfSpan(entry);\n  const label = getEventLabel(event, hourCycle, locale);\n  const details = [location, dayOfSpan].filter(Boolean).join(\" · \");\n  /** The row: its details popover opens below it */\n  const rowRef = useRef<HTMLDivElement>(null);\n  /** The row's details popover, for the row's `aria-controls` */\n  const detailsId = useId();\n\n  function handleClick(e: React.MouseEvent) {\n    e.stopPropagation();\n    onSelect(event);\n  }\n\n  function handleContextMenu(e: React.MouseEvent) {\n    e.preventDefault();\n    e.stopPropagation();\n    onContextMenu(e, event);\n  }\n\n  function handleKeyDown(e: React.KeyboardEvent) {\n    if (e.key !== \"Enter\" && e.key !== \" \") return;\n    e.preventDefault();\n    onSelect(event);\n  }\n\n  const secondaryTextClass = isSelected\n    ? \"text-white/85\"\n    : cn(styles.text, \"opacity-80 dark:text-white/70 dark:opacity-100\");\n\n  return (\n    // The row stays first, so opening the details keeps this element (and\n    // its focus) instead of re-creating it\n    <>\n      <div\n        ref={rowRef}\n        role=\"button\"\n        tabIndex={0}\n        aria-label={dayOfSpan ? `${label}, ${dayOfSpan.toLowerCase()}` : label}\n        aria-pressed={isSelected}\n        {...getEventDetailsTriggerProps({\n          showEventPopover,\n          showPopover,\n          detailsId,\n        })}\n        data-event-id={event.id}\n        onClick={handleClick}\n        onContextMenu={handleContextMenu}\n        onKeyDown={handleKeyDown}\n        className={cn(\n          \"relative flex min-h-9 cursor-default overflow-hidden rounded-md select-none\",\n          \"focus:outline-none\",\n          EVENT_FOCUS_RING_CLASS,\n          isSelected ? styles.border : cn(styles.bg, styles.bgHover),\n          eventIsPast && !isSelected && \"opacity-60\",\n        )}\n      >\n        {/* Color accent, merged into the background when selected (kept\n              in place so the content doesn't shift) */}\n        <span\n          aria-hidden\n          className={cn(\n            \"w-1 shrink-0\",\n            !isSelected &&\n              cn(styles.border, \"dark:bg-white dark:mix-blend-overlay\"),\n          )}\n        />\n        <EventContentSlot\n          event={event}\n          view=\"agenda\"\n          placement=\"agenda\"\n          isSelected={isSelected}\n          isPast={eventIsPast}\n          isDragging={false}\n          isResizing={false}\n          isCompact={false}\n          timeLabel={timeLabel}\n          className={AGENDA_SLOT_CLASS}\n          fallback={\n            <div\n              className={cn(\n                \"grid min-w-0 flex-1 grid-cols-[auto_minmax(0,1fr)] content-center gap-x-1 gap-y-0.5 px-2.5 py-1.5 text-xs\",\n                \"@xl/agenda:grid-cols-[8.5rem_minmax(0,1fr)_auto] @xl/agenda:items-center @xl/agenda:gap-x-4\",\n              )}\n            >\n              <span\n                className={cn(\n                  \"col-span-2 truncate text-sm font-medium\",\n                  \"@xl/agenda:col-span-1 @xl/agenda:col-start-2 @xl/agenda:row-start-1\",\n                  isSelected\n                    ? \"text-white\"\n                    : cn(styles.text, \"dark:text-white/90\"),\n                )}\n              >\n                {event.title}\n              </span>\n              <span\n                className={cn(\n                  \"whitespace-nowrap tabular-nums\",\n                  \"@xl/agenda:col-start-1 @xl/agenda:row-start-1\",\n                  secondaryTextClass,\n                )}\n              >\n                {timeLabel}\n              </span>\n              {details && (\n                <span\n                  className={cn(\n                    \"truncate before:mr-1 before:content-['·'] @xl/agenda:col-start-3 @xl/agenda:row-start-1 @xl/agenda:max-w-56 @xl/agenda:text-right @xl/agenda:before:content-none\",\n                    secondaryTextClass,\n                  )}\n                >\n                  {details}\n                </span>\n              )}\n            </div>\n          }\n        />\n      </div>\n      {showPopover && (\n        <EventDetailPopover\n          event={event}\n          id={detailsId}\n          anchor={rowRef}\n          onEventChange={onEventChange}\n          onClose={() => onPopoverClose(event.id)}\n          onExpand={onPopoverExpand}\n          side=\"bottom\"\n          align=\"end\"\n        />\n      )}\n    </>\n  );\n}\n\n/** Shown when no events fall in the agenda's range */\nfunction AgendaEmptyState({ from, to }: AgendaEmptyStateProps) {\n  const { locale } = useCalendarConfig();\n\n  return (\n    <div className=\"flex h-full min-h-48 flex-col items-center justify-center gap-2 px-6 py-10 text-center\">\n      <div className=\"flex size-10 items-center justify-center rounded-full bg-muted text-muted-foreground\">\n        <CalendarCheckIcon aria-hidden className=\"size-5\" />\n      </div>\n      <p className=\"text-sm font-medium text-foreground\">Nothing planned</p>\n      <p className=\"max-w-64 text-sm text-muted-foreground\">\n        No events from {format(from, \"MMM d\", { locale })} to{\" \"}\n        {format(to, \"MMM d\", { locale })}.\n      </p>\n    </div>\n  );\n}\n",
      "type": "registry:component"
    }
  ],
  "type": "registry:component"
}