{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "schedule",
  "title": "Schedule",
  "description": "Primitives for schedules: date helpers that take a fixed now and a time zone, an event row, urgency labels and badges, and a keyboard-navigable month calendar.",
  "registryDependencies": [
    "https://www.dashboardblocks.com/r/radix/status-label.json",
    "https://www.dashboardblocks.com/r/radix/format.json"
  ],
  "files": [
    {
      "path": "registry/components/dashboardblocks/schedule.tsx",
      "content": "'use client'\n\nimport {\n  StatusLabel,\n  type StatusTone,\n} from '@/registry/components/dashboardblocks/status-label'\nimport {\n  dayIn,\n  formatDate,\n  formatDayHeading,\n  formatRelativeDays,\n  formatRelativeTime,\n  joinDetails,\n  zonedParts,\n} from '@/registry/lib/dashboardblocks/format'\nimport {\n  type CSSProperties,\n  type KeyboardEvent,\n  type ReactNode,\n  useEffect,\n  useRef,\n  useState,\n} from 'react'\n\nimport { cn } from '@/lib/utils'\n\ninterface ScheduleEvent {\n  allDay?: boolean\n  calendar?: string\n  /** @default 'var(--color-chart-2)' */\n  color?: string\n  /** Leave out for a point in time, such as a deadline. */\n  end?: Date\n  id: string\n  location?: string\n  start: Date\n  title: string\n}\n\nconst DAY = 86_400_000\n\nfunction getDay(date: Date, timeZone = 'UTC') {\n  const { day, month, year } = zonedParts(date, timeZone)\n  return new Date(Date.UTC(year, month - 1, day))\n}\n\nfunction addDays(day: Date, days: number) {\n  return new Date(day.getTime() + days * DAY)\n}\n\nfunction getDayOffset(date: Date, now: Date, timeZone = 'UTC') {\n  return Math.round(\n    (getDay(date, timeZone).getTime() - getDay(now, timeZone).getTime()) / DAY,\n  )\n}\n\nfunction formatTime(date: Date, timeZone = 'UTC') {\n  return formatDate(date, 'time', timeZone)\n}\n\nfunction formatTimeRange(start: Date, end: Date | undefined, timeZone = 'UTC') {\n  const from = formatTime(start, timeZone)\n  if (!end) return from\n  const to = formatTime(end, timeZone)\n  if (from.slice(-2) === to.slice(-2)) return `${from.slice(0, -3)}–${to}`\n  return `${from}–${to}`\n}\n\nfunction formatDuration(start: Date, end: Date) {\n  const minutes = Math.max(0, Math.round((end.getTime() - start.getTime()) / 60_000))\n  const hours = Math.floor(minutes / 60)\n  const rest = minutes % 60\n  if (hours === 0) return `${rest} min`\n  return rest === 0 ? `${hours} hr` : `${hours} hr ${rest} min`\n}\n\nfunction formatCountdown(date: Date, now: Date, timeZone = 'UTC') {\n  const offset = getDayOffset(date, now, timeZone)\n  if (offset !== 0) return formatRelativeDays(offset)\n  if (Math.abs(date.getTime() - now.getTime()) < 60_000) return 'now'\n  return formatRelativeTime(date, now, { style: 'long', timeZone })\n}\n\ninterface ScheduleDay<T extends ScheduleEvent> {\n  day: Date\n  events: T[]\n  key: string\n  label: string\n}\n\nfunction groupByDay<T extends ScheduleEvent>(events: T[], now: Date, timeZone = 'UTC') {\n  const days = new Map<string, ScheduleDay<T>>()\n  for (const event of [...events].sort((a, b) => a.start.getTime() - b.start.getTime())) {\n    const key = dayIn(event.start, timeZone)\n    const group = days.get(key) ?? {\n      day: getDay(event.start, timeZone),\n      events: [],\n      key,\n      label: formatDayHeading(event.start, now, timeZone),\n    }\n    group.events.push(event)\n    days.set(key, group)\n  }\n  return [...days.values()]\n}\n\nfunction getMonthWeeks(month: Date, weekStartsOn: 0 | 1 = 0) {\n  const first = new Date(Date.UTC(month.getUTCFullYear(), month.getUTCMonth(), 1))\n  const start = addDays(first, -((first.getUTCDay() - weekStartsOn + 7) % 7))\n  return Array.from({ length: 6 }, (_, week) =>\n    Array.from({ length: 7 }, (_, weekday) => addDays(start, week * 7 + weekday)),\n  )\n}\n\n/** Tints an event chip with its colour over `surface`, the colour behind it, and fades it once it has ended. */\nfunction getEventStyle(\n  event: ScheduleEvent,\n  ended = false,\n  surface = 'var(--color-card)',\n): CSSProperties {\n  const color = event.color ?? 'var(--color-chart-2)'\n  return {\n    backgroundColor: `color-mix(in oklab, ${color} ${ended ? 12 : 24}%, ${surface})`,\n  }\n}\n\nfunction EventSwatch({ className, color }: { className?: string; color?: string }) {\n  return (\n    <span\n      aria-hidden\n      className={cn('size-2 shrink-0 rounded-full', className)}\n      style={{ backgroundColor: color ?? 'var(--color-chart-2)' }}\n    />\n  )\n}\n\ninterface EventRowProps {\n  action?: ReactNode\n  className?: string\n  event: ScheduleEvent\n  /** Dims events that have ended and marks the one in progress. */\n  now?: Date\n  /** Tints the row and keeps its small text at full contrast on the tint. */\n  selected?: boolean\n  /** @default 'UTC' */\n  timeZone?: string\n}\n\nfunction EventRow({\n  action,\n  className,\n  event,\n  now,\n  selected = false,\n  timeZone = 'UTC',\n}: EventRowProps) {\n  const muted = !selected && 'text-muted-foreground'\n  const ended = now !== undefined && (event.end ?? event.start) <= now\n  const live =\n    now !== undefined &&\n    !event.allDay &&\n    event.end !== undefined &&\n    event.start <= now &&\n    now < event.end\n  const meta = joinDetails(event.calendar, event.location)\n\n  return (\n    <li className={cn('flex items-stretch gap-3', selected && 'bg-muted', className)}>\n      <div className='flex w-16 shrink-0 flex-col pt-px text-xs tabular-nums'>\n        {event.allDay ? (\n          <span className={cn('font-medium', muted)}>All day</span>\n        ) : (\n          <>\n            <time\n              dateTime={event.start.toISOString()}\n              className={cn('font-medium', ended && muted)}\n            >\n              {formatTime(event.start, timeZone)}\n            </time>\n            {event.end && (\n              <span className={cn(muted)}>{formatDuration(event.start, event.end)}</span>\n            )}\n          </>\n        )}\n      </div>\n      <span\n        aria-hidden\n        className={cn('w-1 shrink-0 rounded-full', ended && 'opacity-40')}\n        style={{ backgroundColor: event.color ?? 'var(--color-chart-2)' }}\n      />\n      <div className='flex min-w-0 flex-1 flex-wrap items-start justify-between gap-x-3 gap-y-1.5'>\n        <div className='flex min-w-0 grow basis-32 flex-col gap-0.5'>\n          <p\n            className={cn(\n              'flex flex-wrap items-center gap-x-2 text-sm font-medium',\n              ended && muted,\n            )}\n          >\n            <span className='min-w-0 break-words'>{event.title}</span>\n            {live && (\n              <StatusLabel tone='good' className='text-xs'>\n                Now\n              </StatusLabel>\n            )}\n            {ended && <span className='sr-only'>(ended)</span>}\n          </p>\n          {meta && <p className={cn('truncate text-xs', muted)}>{meta}</p>}\n        </div>\n        {action && <div className='flex shrink-0 items-start'>{action}</div>}\n      </div>\n    </li>\n  )\n}\n\ntype Urgency = 'overdue' | 'today' | 'soon' | 'later'\n\nconst urgencyConfig: Record<Urgency, { label: string; text: string }> = {\n  later: {\n    label: 'Upcoming',\n    text: 'text-muted-foreground',\n  },\n  overdue: {\n    label: 'Overdue',\n    text: 'text-red-700 dark:text-red-400',\n  },\n  soon: {\n    label: 'Due soon',\n    text: 'text-orange-700 dark:text-orange-400',\n  },\n  today: {\n    label: 'Today',\n    text: 'text-orange-700 dark:text-orange-400',\n  },\n}\n\n/** How pressing a deadline is by calendar day: overdue, today, within `soonDays` (default 7) or later. */\nfunction getUrgency(date: Date, now: Date, timeZone = 'UTC', soonDays = 7): Urgency {\n  const offset = getDayOffset(date, now, timeZone)\n  if (offset < 0) return 'overdue'\n  if (offset === 0) return 'today'\n  return offset <= soonDays ? 'soon' : 'later'\n}\n\nconst urgencyTones: Record<Urgency, StatusTone> = {\n  later: 'neutral',\n  overdue: 'bad',\n  soon: 'warning',\n  today: 'warning',\n}\n\nfunction UrgencyLabel({\n  className,\n  label,\n  urgency,\n  variant = 'text',\n}: {\n  className?: string\n  label?: string\n  urgency: Urgency\n  variant?: 'badge' | 'text'\n}) {\n  return (\n    <StatusLabel tone={urgencyTones[urgency]} className={className} variant={variant}>\n      {label ?? urgencyConfig[urgency].label}\n    </StatusLabel>\n  )\n}\n\ninterface DueLabelProps {\n  className?: string\n  /** A done task reads as plain text, whatever its date. */\n  done?: boolean\n  due: Date\n  id?: string\n  now: Date\n  /** Days ahead that read as due soon. @default 7 */\n  soonDays?: number\n  /** @default 'UTC' */\n  timeZone?: string\n  /** `badge` where it's the row's status, such as in a table. @default 'text' */\n  variant?: 'badge' | 'text'\n}\n\n/** When a task is due, coloured by how close it is: `3 days overdue`, `Due today`, `Due tomorrow`, then `Due Dec 14`. */\nfunction DueLabel({\n  className,\n  done = false,\n  due,\n  id,\n  now,\n  soonDays = 7,\n  timeZone = 'UTC',\n  variant,\n}: DueLabelProps) {\n  const offset = getDayOffset(due, now, timeZone)\n  const day = getDay(due, timeZone)\n  const urgency = done ? 'later' : getUrgency(due, now, timeZone, soonDays)\n  const label =\n    urgency === 'overdue'\n      ? `${-offset} ${offset === -1 ? 'day' : 'days'} overdue`\n      : urgency === 'today'\n        ? 'Due today'\n        : offset === 1\n          ? 'Due tomorrow'\n          : `Due ${formatDate(day, 'day')}`\n  return (\n    <time id={id} dateTime={day.toISOString().slice(0, 10)} className={className}>\n      <UrgencyLabel\n        className={cn(urgency === 'later' && variant !== 'badge' && 'font-normal')}\n        label={label}\n        urgency={urgency}\n        variant={variant}\n      />\n    </time>\n  )\n}\n\ninterface MonthCalendarProps {\n  className?: string\n  /** Events to mark with dots, up to three per day. */\n  events: ScheduleEvent[]\n  label: string\n  /** The month shown, as a plain day from `getDay`. */\n  month: Date\n  onMonthChange: (month: Date) => void\n  onSelect: (day: Date) => void\n  now: Date\n  selected?: Date\n  /** @default 'UTC' */\n  timeZone?: string\n  /** 0 for Sunday, 1 for Monday. */\n  weekStartsOn?: 0 | 1\n}\n\nfunction MonthCalendar({\n  className,\n  events,\n  label,\n  month,\n  now,\n  onMonthChange,\n  onSelect,\n  selected,\n  timeZone = 'UTC',\n  weekStartsOn = 0,\n}: MonthCalendarProps) {\n  const grid = useRef<HTMLTableElement>(null)\n  const [cursor, setCursor] = useState<Date | null>(null)\n  const shouldFocus = useRef(false)\n\n  const weeks = getMonthWeeks(month, weekStartsOn)\n  const today = getDay(now, timeZone).getTime()\n  const inMonth = (day: Date) =>\n    day.getUTCFullYear() === month.getUTCFullYear() &&\n    day.getUTCMonth() === month.getUTCMonth()\n  const fallback =\n    selected && inMonth(selected)\n      ? selected\n      : inMonth(new Date(today))\n        ? new Date(today)\n        : new Date(Date.UTC(month.getUTCFullYear(), month.getUTCMonth(), 1))\n  const active = cursor && inMonth(cursor) ? cursor : fallback\n\n  const eventsByDay = new Map<string, ScheduleEvent[]>()\n  for (const event of events) {\n    const key = dayIn(event.start, timeZone)\n    eventsByDay.set(key, [...(eventsByDay.get(key) ?? []), event])\n  }\n\n  useEffect(() => {\n    if (!shouldFocus.current) return\n    shouldFocus.current = false\n    grid.current\n      ?.querySelector<HTMLElement>(`[data-day=\"${active.toISOString().slice(0, 10)}\"]`)\n      ?.focus()\n  })\n\n  const moveTo = (day: Date) => {\n    setCursor(day)\n    shouldFocus.current = true\n    if (!inMonth(day))\n      onMonthChange(new Date(Date.UTC(day.getUTCFullYear(), day.getUTCMonth(), 1)))\n  }\n\n  const moveMonths = (months: number) => {\n    const target = new Date(\n      Date.UTC(active.getUTCFullYear(), active.getUTCMonth() + months, 1),\n    )\n    const lastDay = new Date(\n      Date.UTC(target.getUTCFullYear(), target.getUTCMonth() + 1, 0),\n    ).getUTCDate()\n    target.setUTCDate(Math.min(active.getUTCDate(), lastDay))\n    moveTo(target)\n  }\n\n  const onKeyDown = (event: KeyboardEvent<HTMLTableElement>) => {\n    const weekday = (active.getUTCDay() - weekStartsOn + 7) % 7\n    switch (event.key) {\n      case 'ArrowRight':\n        moveTo(addDays(active, 1))\n        break\n      case 'ArrowLeft':\n        moveTo(addDays(active, -1))\n        break\n      case 'ArrowDown':\n        moveTo(addDays(active, 7))\n        break\n      case 'ArrowUp':\n        moveTo(addDays(active, -7))\n        break\n      case 'Home':\n        moveTo(addDays(active, -weekday))\n        break\n      case 'End':\n        moveTo(addDays(active, 6 - weekday))\n        break\n      case 'PageDown':\n        moveMonths(event.shiftKey ? 12 : 1)\n        break\n      case 'PageUp':\n        moveMonths(event.shiftKey ? -12 : -1)\n        break\n      default:\n        return\n    }\n    event.preventDefault()\n  }\n\n  const weekdays = weeks[0].map((day) => ({\n    long: formatDate(day, 'weekday-long'),\n    short: formatDate(day, 'weekday').slice(0, 2),\n  }))\n\n  return (\n    // Not a data table: a calendar month, drawn as the ARIA date grid pattern.\n    <table\n      ref={grid}\n      // oxlint-disable-next-line jsx-a11y/no-noninteractive-element-to-interactive-role -- the ARIA date grid pattern is a table with the grid role\n      role='grid'\n      aria-label={label}\n      onKeyDown={onKeyDown}\n      className={cn('w-full table-fixed border-collapse', className)}\n    >\n      <thead>\n        <tr>\n          {weekdays.map((weekday) => (\n            <th\n              key={weekday.long}\n              scope='col'\n              abbr={weekday.long}\n              className='text-muted-foreground pb-1 text-xs font-normal'\n            >\n              {weekday.short}\n            </th>\n          ))}\n        </tr>\n      </thead>\n      <tbody>\n        {weeks.map((week) => (\n          <tr key={week[0].getTime()}>\n            {week.map((day) => {\n              const key = day.toISOString().slice(0, 10)\n              const dayEvents = eventsByDay.get(key) ?? []\n              const isToday = day.getTime() === today\n              const isSelected = selected?.getTime() === day.getTime()\n              const isActive = active.getTime() === day.getTime()\n              const outside = !inMonth(day)\n              const name = [\n                formatDate(day, 'weekday-long-day'),\n                isToday ? 'today' : '',\n                dayEvents.length === 0\n                  ? 'no events'\n                  : `${dayEvents.length} ${dayEvents.length === 1 ? 'event' : 'events'}`,\n              ]\n                .filter(Boolean)\n                .join(', ')\n              return (\n                <td key={key} aria-selected={isSelected} className='p-0.5 text-center'>\n                  <button\n                    type='button'\n                    data-day={key}\n                    tabIndex={isActive ? 0 : -1}\n                    aria-label={name}\n                    aria-current={isToday ? 'date' : undefined}\n                    onClick={() => {\n                      setCursor(day)\n                      if (outside) {\n                        onMonthChange(\n                          new Date(Date.UTC(day.getUTCFullYear(), day.getUTCMonth(), 1)),\n                        )\n                      }\n                      onSelect(day)\n                    }}\n                    className={cn(\n                      'focus-visible:ring-ring/50 relative mx-auto flex h-10 w-full max-w-10 flex-col items-center justify-center gap-0.5 rounded-md text-sm tabular-nums outline-none focus-visible:ring-[3px]',\n                      outside ? 'text-muted-foreground' : 'hover:bg-muted',\n                      isToday &&\n                        !isSelected &&\n                        'text-foreground font-semibold ring-1 ring-border',\n                      isSelected &&\n                        'bg-primary text-primary-foreground hover:bg-primary font-semibold',\n                    )}\n                  >\n                    <span aria-hidden className='leading-none'>\n                      {day.getUTCDate()}\n                    </span>\n                    <span aria-hidden className='flex h-1.5 items-center gap-0.5'>\n                      {dayEvents.slice(0, 3).map((event) => (\n                        <span\n                          key={event.id}\n                          className={cn(\n                            'size-1 rounded-full',\n                            isSelected && 'ring-primary-foreground/80 ring-1',\n                          )}\n                          style={{\n                            backgroundColor: event.color ?? 'var(--color-chart-2)',\n                          }}\n                        />\n                      ))}\n                    </span>\n                  </button>\n                </td>\n              )\n            })}\n          </tr>\n        ))}\n      </tbody>\n    </table>\n  )\n}\n\nexport {\n  DueLabel,\n  EventRow,\n  EventSwatch,\n  MonthCalendar,\n  UrgencyLabel,\n  addDays,\n  formatCountdown,\n  formatDuration,\n  formatTime,\n  formatTimeRange,\n  getDay,\n  getDayOffset,\n  getEventStyle,\n  getMonthWeeks,\n  getUrgency,\n  groupByDay,\n  urgencyConfig,\n  urgencyTones,\n}\n\nexport type {\n  DueLabelProps,\n  EventRowProps,\n  MonthCalendarProps,\n  ScheduleDay,\n  ScheduleEvent,\n  Urgency,\n}\n",
      "type": "registry:component",
      "target": "@components/dashboardblocks/schedule.tsx"
    }
  ],
  "type": "registry:component"
}
