{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "calendar-view",
  "title": "Calendar View",
  "description": "Day, week, and month layouts with event overflow.",
  "dependencies": [
    "class-variance-authority",
    "lucide-react"
  ],
  "registryDependencies": [
    "button",
    "toggle",
    "https://uaiblocks.dev/r/uai-theme.json",
    "https://uaiblocks.dev/r/uai-utils.json"
  ],
  "files": [
    {
      "path": "src/registry/uai/components/calendar-view.tsx",
      "content": "\"use client\";\n\nimport { cva } from \"class-variance-authority\";\nimport { ChevronLeft, ChevronRight } from \"lucide-react\";\nimport {\n  type ComponentProps,\n  createContext,\n  type KeyboardEvent,\n  useContext,\n  useId,\n  useState,\n} from \"react\";\nimport { Button } from \"@/components/ui/button\";\nimport { toggleVariants } from \"@/components/ui/toggle\";\nimport { cn } from \"@/lib/uai-utils\";\n\nexport const CALENDAR_VIEW_VARIANTS = [\"card\", \"plain\", \"compact\"] as const;\nexport type CalendarViewVariant = (typeof CALENDAR_VIEW_VARIANTS)[number];\nexport const CALENDAR_VIEW_MODES = [\"month\", \"week\", \"day\"] as const;\nexport type CalendarViewMode = (typeof CALENDAR_VIEW_MODES)[number];\nexport type CalendarViewEvent = {\n  id: string;\n  title: string;\n  /** Local start time. */\n  start: Date;\n  /** Local end time. */\n  end?: Date;\n  allDay?: boolean;\n};\nexport type CalendarViewProps = ComponentProps<\"section\"> & {\n  variant?: CalendarViewVariant;\n  view?: CalendarViewMode;\n  defaultView?: CalendarViewMode;\n  onViewChange?: (view: CalendarViewMode) => void;\n  date?: Date;\n  defaultDate?: Date;\n  onDateChange?: (date: Date) => void;\n  /** The local day shown as today. Pass a fixed date to avoid hydration mismatches. */\n  today?: Date;\n  weekStartsOn?: 0 | 1;\n  locale?: string;\n};\n\ntype CalendarContext = {\n  id: string;\n  variant: CalendarViewVariant;\n  view: CalendarViewMode;\n  setView: (view: CalendarViewMode) => void;\n  date: Date;\n  setDate: (date: Date) => void;\n  today: Date;\n  weekStartsOn: 0 | 1;\n  locale: string;\n};\nconst Context = createContext<CalendarContext | null>(null);\nfunction useCalendar(part: string) {\n  const context = useContext(Context);\n  if (!context) throw new Error(`${part} must be used within CalendarView`);\n  return context;\n}\n\nconst calendarViewVariants = cva(\"grid min-w-0 rounded-[14px] text-[13px]/[18px] text-foreground\", {\n  variants: {\n    variant: {\n      card: \"gap-3 border bg-card p-3.5 text-card-foreground\",\n      plain: \"gap-3 border-0 bg-transparent p-0\",\n      compact: \"gap-2 border-0 bg-transparent p-0\",\n    },\n  },\n});\n\nfunction startOfDay(date: Date) {\n  return new Date(date.getFullYear(), date.getMonth(), date.getDate());\n}\nfunction addDays(date: Date, days: number) {\n  return new Date(date.getFullYear(), date.getMonth(), date.getDate() + days);\n}\nfunction sameDay(a: Date, b: Date) {\n  return (\n    a.getFullYear() === b.getFullYear() &&\n    a.getMonth() === b.getMonth() &&\n    a.getDate() === b.getDate()\n  );\n}\nfunction startOfWeek(date: Date, weekStartsOn: 0 | 1) {\n  return addDays(date, -((date.getDay() - weekStartsOn + 7) % 7));\n}\nfunction dateKey(date: Date) {\n  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, \"0\")}-${String(date.getDate()).padStart(2, \"0\")}`;\n}\nfunction eventsOn(events: readonly CalendarViewEvent[], day: Date) {\n  const start = startOfDay(day).getTime();\n  const end = addDays(day, 1).getTime();\n  return events\n    .filter((event) => {\n      const from = event.start.getTime();\n      const to = (event.end ?? event.start).getTime();\n      return from < end && (to > start || (to === from && from >= start));\n    })\n    .sort(\n      (a, b) =>\n        Number(Boolean(b.allDay)) - Number(Boolean(a.allDay)) ||\n        a.start.getTime() - b.start.getTime(),\n    );\n}\n\nexport function CalendarView({\n  variant = \"card\",\n  view,\n  defaultView = \"month\",\n  onViewChange,\n  date,\n  defaultDate,\n  onDateChange,\n  today,\n  weekStartsOn = 0,\n  locale = \"en-US\",\n  className,\n  children,\n  ...props\n}: CalendarViewProps) {\n  const id = useId();\n  const [now] = useState(() => startOfDay(today ?? new Date()));\n  const [internalView, setInternalView] = useState(defaultView);\n  const [internalDate, setInternalDate] = useState(() =>\n    startOfDay(defaultDate ?? today ?? new Date()),\n  );\n  const context: CalendarContext = {\n    id,\n    variant,\n    view: view ?? internalView,\n    setView: (next) => {\n      if (view === undefined) setInternalView(next);\n      onViewChange?.(next);\n    },\n    date: startOfDay(date ?? internalDate),\n    setDate: (next) => {\n      if (date === undefined) setInternalDate(startOfDay(next));\n      onDateChange?.(startOfDay(next));\n    },\n    today: today ? startOfDay(today) : now,\n    weekStartsOn,\n    locale,\n  };\n  return (\n    <Context.Provider value={context}>\n      <section\n        aria-labelledby={`${id}-title`}\n        data-slot=\"calendar-view\"\n        className={cn(calendarViewVariants({ variant }), className)}\n        {...props}\n        data-variant={variant}\n        data-view={context.view}\n      >\n        {children}\n      </section>\n    </Context.Provider>\n  );\n}\n\nexport function CalendarViewHeader({ className, ...props }: ComponentProps<\"div\">) {\n  return (\n    <div\n      data-slot=\"calendar-view-header\"\n      className={cn(\"flex flex-wrap items-center justify-between gap-2\", className)}\n      {...props}\n    />\n  );\n}\n\nexport function CalendarViewTitle({ className, children, ...props }: ComponentProps<\"h3\">) {\n  const context = useCalendar(\"CalendarViewTitle\");\n  const { date, view, locale, weekStartsOn } = context;\n  let label: string;\n  if (view === \"month\") {\n    label = new Intl.DateTimeFormat(locale, { month: \"long\", year: \"numeric\" }).format(date);\n  } else if (view === \"day\") {\n    label = new Intl.DateTimeFormat(locale, { dateStyle: \"full\" }).format(date);\n  } else {\n    const start = startOfWeek(date, weekStartsOn);\n    label = new Intl.DateTimeFormat(locale, {\n      month: \"short\",\n      day: \"numeric\",\n      year: \"numeric\",\n    }).formatRange(start, addDays(start, 6));\n  }\n  return (\n    <h3\n      data-slot=\"calendar-view-title\"\n      className={cn(\n        \"m-0 font-semibold tracking-[-0.01em] tabular-nums\",\n        context.variant === \"compact\" ? \"text-[13px]/5\" : \"text-sm/5\",\n        className,\n      )}\n      {...props}\n      id={`${context.id}-title`}\n      aria-live=\"polite\"\n    >\n      {children ?? label}\n    </h3>\n  );\n}\n\nfunction controlClass(variant: CalendarViewVariant) {\n  return cn(\n    \"inline-flex cursor-pointer items-center justify-center rounded-full border-0 font-medium\",\n    variant === \"compact\" ? \"h-6 min-w-6 px-2.5 text-[12px]\" : \"h-7 min-w-7 px-3 text-[12.5px]\",\n  );\n}\nconst press =\n  \"transition-[background-color,color,scale] duration-[120ms,120ms,140ms] ease-[ease-out,ease-out,cubic-bezier(0.23,1,0.32,1)] focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring active:scale-[0.97] motion-reduce:transition-none motion-reduce:active:scale-100\";\n// Primitive controls swap their ring for the Uai outline; `outline-solid` undoes their `outline-none`.\nconst primitiveFocus = \"focus-visible:ring-0 focus-visible:outline-solid\";\n// Ghost icon button and secondary pill, per the shared button rules.\nconst ghostClass = `bg-transparent text-muted-foreground hover:bg-accent hover:text-foreground dark:hover:bg-accent ${press}`;\nconst secondaryClass = `bg-secondary text-secondary-foreground hover:bg-[color-mix(in_oklab,var(--secondary)_85%,var(--foreground))] ${press}`;\nconst modeThumbOffset: Record<CalendarViewMode, string> = {\n  month: \"translate-x-0\",\n  week: \"translate-x-full\",\n  day: \"translate-x-[200%]\",\n};\n\nexport function CalendarViewNavigation({ className, ...props }: ComponentProps<\"div\">) {\n  const context = useCalendar(\"CalendarViewNavigation\");\n  const step = (direction: 1 | -1) => {\n    const { date, view } = context;\n    if (view === \"month\")\n      context.setDate(new Date(date.getFullYear(), date.getMonth() + direction, 1));\n    else context.setDate(addDays(date, direction * (view === \"week\" ? 7 : 1)));\n  };\n  const iconButton = cn(\n    controlClass(context.variant),\n    \"rounded-lg p-0 has-[>svg]:p-0\",\n    context.variant === \"compact\" ? \"size-6\" : \"size-7\",\n    ghostClass,\n    primitiveFocus,\n  );\n  return (\n    // biome-ignore lint/a11y/useSemanticElements: a fieldset would add form semantics to calendar navigation buttons.\n    <div\n      role=\"group\"\n      aria-label=\"Calendar navigation\"\n      data-slot=\"calendar-view-navigation\"\n      className={cn(\"flex items-center gap-0.5\", className)}\n      {...props}\n    >\n      <Button\n        type=\"button\"\n        variant=\"ghost\"\n        size=\"icon-sm\"\n        aria-label={`Previous ${context.view}`}\n        onClick={() => step(-1)}\n        className={iconButton}\n      >\n        <ChevronLeft size={16} strokeWidth={1.75} aria-hidden=\"true\" />\n      </Button>\n      <Button\n        type=\"button\"\n        variant=\"secondary\"\n        size=\"sm\"\n        onClick={() => context.setDate(context.today)}\n        className={cn(controlClass(context.variant), \"mx-0.5\", secondaryClass, primitiveFocus)}\n      >\n        Today\n      </Button>\n      <Button\n        type=\"button\"\n        variant=\"ghost\"\n        size=\"icon-sm\"\n        aria-label={`Next ${context.view}`}\n        onClick={() => step(1)}\n        className={iconButton}\n      >\n        <ChevronRight size={16} strokeWidth={1.75} aria-hidden=\"true\" />\n      </Button>\n    </div>\n  );\n}\n\n/** Arrows move focus and selection together, as in an APG radio group. */\nfunction moveRadio(event: KeyboardEvent<HTMLElement>) {\n  const radios = Array.from(\n    event.currentTarget.querySelectorAll<HTMLButtonElement>('[role=\"radio\"]:not(:disabled)'),\n  );\n  const index = radios.indexOf(document.activeElement as HTMLButtonElement);\n  if (index === -1) return;\n  const next = {\n    ArrowRight: index + 1,\n    ArrowDown: index + 1,\n    ArrowLeft: index - 1,\n    ArrowUp: index - 1,\n    Home: 0,\n    End: radios.length - 1,\n  }[event.key];\n  if (next === undefined) return;\n  event.preventDefault();\n  const target = radios[(next + radios.length) % radios.length];\n  target?.focus();\n  target?.click();\n}\n\n/**\n * Single-choice segments are plain radio buttons styled like ToggleGroupItem: ToggleGroup's value\n * is a string on Radix but an array on Base UI, so the selected layout stays in uai state.\n */\nconst segmentClass = \"w-auto min-w-0 shrink-0 px-3 focus:z-10 focus-visible:z-10\";\n\nexport function CalendarViewModes({\n  onKeyDown,\n  className,\n  ...props\n}: Omit<ComponentProps<\"div\">, \"defaultValue\" | \"dir\">) {\n  const context = useCalendar(\"CalendarViewModes\");\n  return (\n    <div\n      role=\"radiogroup\"\n      aria-label=\"Calendar layout\"\n      data-slot=\"calendar-view-modes\"\n      className={cn(\n        \"relative isolate inline-grid w-auto grid-cols-3 gap-0 rounded-full bg-muted p-0.5\",\n        className,\n      )}\n      {...props}\n      onKeyDown={(event) => {\n        onKeyDown?.(event);\n        if (!event.defaultPrevented) moveRadio(event);\n      }}\n    >\n      {/* One thumb slides under the active layout instead of each button repainting. */}\n      <span\n        aria-hidden=\"true\"\n        className={cn(\n          \"absolute inset-y-0.5 left-0.5 -z-1 w-[calc((100%-4px)/3)] rounded-full bg-card shadow-[0_0_0_1px_var(--border),0_1px_2px_oklch(0_0_0/0.08)] transition-[translate] duration-240 ease-out-quint motion-reduce:transition-none\",\n          modeThumbOffset[context.view],\n        )}\n      />\n      {CALENDAR_VIEW_MODES.map((mode) => {\n        const active = context.view === mode;\n        return (\n          // biome-ignore lint/a11y/useSemanticElements: a segment button in a radio group; ToggleGroupItem renders the same role=\"radio\" button.\n          <button\n            key={mode}\n            type=\"button\"\n            role=\"radio\"\n            aria-checked={active}\n            data-state={active ? \"on\" : \"off\"}\n            tabIndex={active ? 0 : -1}\n            onClick={() => context.setView(mode)}\n            className={cn(\n              toggleVariants(),\n              segmentClass,\n              controlClass(context.variant),\n              context.variant === \"compact\" ? \"h-5.5\" : \"h-6.5\",\n              // The thumb paints the active layout; the items stay transparent and fully rounded.\n              \"rounded-full bg-transparent hover:bg-transparent data-[state=on]:bg-transparent\",\n              active\n                ? \"text-foreground hover:text-foreground data-[state=on]:text-foreground\"\n                : \"text-subtle-foreground hover:text-muted-foreground\",\n              press,\n              primitiveFocus,\n            )}\n          >\n            {mode.charAt(0).toUpperCase() + mode.slice(1)}\n          </button>\n        );\n      })}\n    </div>\n  );\n}\n\nexport type CalendarViewGridProps = ComponentProps<\"div\"> & {\n  events?: readonly CalendarViewEvent[];\n  /** Events shown per month cell before \"+N more\". Week view shows twice as many. */\n  maxEvents?: number;\n  onEventSelect?: (event: CalendarViewEvent) => void;\n};\n\nexport function CalendarViewGrid({\n  events = [],\n  maxEvents = 2,\n  onEventSelect,\n  className,\n  ...props\n}: CalendarViewGridProps) {\n  const context = useCalendar(\"CalendarViewGrid\");\n  const { date, view, locale, weekStartsOn, variant } = context;\n  const time = new Intl.DateTimeFormat(locale, { hour: \"numeric\", minute: \"2-digit\" });\n  const long = new Intl.DateTimeFormat(locale, { dateStyle: \"full\" });\n  const weekday = new Intl.DateTimeFormat(locale, { weekday: \"short\" });\n  const compact = variant === \"compact\";\n\n  const eventItem = (event: CalendarViewEvent, showTime: boolean) => {\n    const when = event.allDay ? \"All day\" : time.format(event.start);\n    const content = (\n      <>\n        {showTime ? (\n          <span className=\"shrink-0 font-normal text-subtle-foreground tabular-nums\">{when}</span>\n        ) : (\n          <span className=\"sr-only\">{when}, </span>\n        )}\n        <span className=\"truncate\">{event.title}</span>\n      </>\n    );\n    // All-day events read as tinted accent chips; timed events as quiet tonal chips.\n    const itemClass = cn(\n      \"flex w-full min-w-0 items-center gap-1.5 rounded-md border-0 px-1.5 text-left font-medium text-foreground\",\n      compact ? \"py-px text-[11px]/4\" : \"py-0.5 text-[11.5px]/4\",\n      event.allDay ? \"bg-primary/16\" : \"bg-muted\",\n    );\n    return (\n      <li key={event.id} className=\"min-w-0\">\n        {onEventSelect ? (\n          <button\n            type=\"button\"\n            onClick={() => onEventSelect(event)}\n            className={cn(\n              itemClass,\n              \"cursor-pointer [transition:filter_120ms_ease-out,scale_140ms_var(--ease-out-quint)] hover:brightness-110 focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring active:scale-[0.98] motion-reduce:transition-none motion-reduce:active:scale-100\",\n            )}\n          >\n            {content}\n          </button>\n        ) : (\n          <span className={itemClass}>{content}</span>\n        )}\n      </li>\n    );\n  };\n\n  const dayCell = (day: Date, limit: number, muted: boolean) => {\n    const dayEvents = eventsOn(events, day);\n    const visible = dayEvents.slice(0, limit);\n    const hidden = dayEvents.length - visible.length;\n    const isToday = sameDay(day, context.today);\n    return (\n      <td\n        key={dateKey(day)}\n        aria-current={isToday ? \"date\" : undefined}\n        className={cn(\n          \"border align-top\",\n          view === \"month\" ? (compact ? \"h-[68px]\" : \"h-[92px]\") : \"h-40\",\n          compact ? \"p-0.75\" : \"p-1\",\n          muted\n            ? \"bg-[color-mix(in_oklab,var(--background)_70%,var(--card))] text-subtle-foreground\"\n            : \"bg-card\",\n        )}\n      >\n        <time\n          dateTime={dateKey(day)}\n          className={cn(\n            \"mb-0.5 inline-grid place-items-center rounded-full px-1.25 font-medium tabular-nums\",\n            compact ? \"h-5 min-w-5 text-[11.5px]\" : \"h-5.5 min-w-5.5 text-[12px]\",\n            isToday ? \"bg-primary text-primary-foreground\" : !muted && \"text-muted-foreground\",\n          )}\n        >\n          <span aria-hidden=\"true\">{day.getDate()}</span>\n          <span className=\"sr-only\">{long.format(day)}</span>\n        </time>\n        {visible.length > 0 ? (\n          <ul className=\"m-0 grid list-none gap-0.5 p-0\">\n            {visible.map((event) => eventItem(event, view === \"week\"))}\n          </ul>\n        ) : null}\n        {hidden > 0 ? (\n          <button\n            type=\"button\"\n            aria-label={`Show ${hidden} more ${hidden === 1 ? \"event\" : \"events\"} on ${long.format(day)}`}\n            onClick={() => {\n              context.setDate(day);\n              context.setView(\"day\");\n            }}\n            className={cn(\n              // The hit area grows vertically so the short row is easy to tap.\n              \"relative mt-0.5 cursor-pointer rounded-md border-0 bg-transparent px-1.5 text-[11px]/4 after:absolute after:inset-x-0 after:-inset-y-1 after:content-[''] font-medium text-subtle-foreground hover:bg-accent hover:text-foreground\",\n              press,\n            )}\n          >\n            +{hidden} more\n          </button>\n        ) : null}\n      </td>\n    );\n  };\n\n  const shell = cn(\"min-w-0 overflow-x-auto\", compact ? \"rounded-[10px]\" : \"rounded-xl\");\n\n  if (view === \"day\") {\n    const dayEvents = eventsOn(events, date);\n    return (\n      <div data-slot=\"calendar-view-grid\" className={cn(shell, className)} {...props}>\n        {dayEvents.length === 0 ? (\n          <p\n            className={cn(\n              \"m-0 border border-dashed px-3 py-8 text-center text-[12.5px] text-subtle-foreground\",\n              compact ? \"rounded-[10px]\" : \"rounded-xl\",\n            )}\n          >\n            No events on {long.format(date)}.\n          </p>\n        ) : (\n          <ol\n            aria-label={`Events on ${long.format(date)}`}\n            className=\"m-0 grid list-none gap-1 p-0\"\n          >\n            {dayEvents.map((event) => {\n              const when = event.allDay\n                ? \"All day\"\n                : event.end\n                  ? time.formatRange(event.start, event.end)\n                  : time.format(event.start);\n              const body = (\n                <>\n                  <span\n                    className={cn(\n                      \"shrink-0 text-subtle-foreground tabular-nums\",\n                      compact ? \"w-28 text-[12px]\" : \"w-33 text-[12.5px]\",\n                    )}\n                  >\n                    {when}\n                  </span>\n                  <span className=\"font-medium wrap-anywhere\">{event.title}</span>\n                </>\n              );\n              const rowClass = cn(\n                \"flex w-full flex-wrap items-baseline gap-2 border-0 text-left text-inherit\",\n                compact ? \"rounded-lg px-2.5 py-1.5\" : \"rounded-[10px] px-3 py-2.25\",\n                event.allDay\n                  ? \"bg-primary/12\"\n                  : \"bg-muted shadow-[inset_2px_0_0_var(--border-strong)]\",\n              );\n              return (\n                <li key={event.id}>\n                  {onEventSelect ? (\n                    <button\n                      type=\"button\"\n                      onClick={() => onEventSelect(event)}\n                      className={cn(\n                        rowClass,\n                        \"cursor-pointer [transition:filter_120ms_ease-out,scale_140ms_var(--ease-out-quint)] hover:brightness-110 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring active:scale-[0.99] motion-reduce:transition-none motion-reduce:active:scale-100\",\n                      )}\n                    >\n                      {body}\n                    </button>\n                  ) : (\n                    <span className={rowClass}>{body}</span>\n                  )}\n                </li>\n              );\n            })}\n          </ol>\n        )}\n      </div>\n    );\n  }\n\n  const weekStart = startOfWeek(date, weekStartsOn);\n  const headers = Array.from({ length: 7 }, (_, index) => addDays(weekStart, index));\n  const weeks: Date[][] = [];\n  if (view === \"week\") {\n    weeks.push(headers);\n  } else {\n    let cursor = startOfWeek(new Date(date.getFullYear(), date.getMonth(), 1), weekStartsOn);\n    do {\n      weeks.push(Array.from({ length: 7 }, (_, index) => addDays(cursor, index)));\n      cursor = addDays(cursor, 7);\n    } while (cursor.getMonth() === date.getMonth());\n  }\n\n  return (\n    <div data-slot=\"calendar-view-grid\" className={cn(\"border\", shell, className)} {...props}>\n      {/* border-hidden hides the outer cell edges; the rounded shell draws the frame. */}\n      <table\n        aria-labelledby={`${context.id}-title`}\n        className=\"w-full min-w-[560px] table-fixed border-collapse border-hidden\"\n      >\n        <thead>\n          <tr>\n            {headers.map((day) => (\n              <th\n                key={dateKey(day)}\n                scope=\"col\"\n                className={cn(\n                  \"border-b text-left font-medium text-subtle-foreground tabular-nums\",\n                  compact ? \"p-1.5 text-[11px]/4\" : \"p-2 text-[11.5px]/4\",\n                )}\n              >\n                {weekday.format(day)}\n                {view === \"week\" ? ` ${day.getDate()}` : null}\n              </th>\n            ))}\n          </tr>\n        </thead>\n        {/* Keyed by the first visible date so each period change fades the grid in. */}\n        <tbody\n          key={`${view}-${weeks[0]?.[0] ? dateKey(weeks[0][0]) : \"\"}`}\n          className=\"animate-in fade-in-0 duration-150 ease-out motion-reduce:animate-none\"\n        >\n          {weeks.map((week) => (\n            <tr key={week.map(dateKey).join()}>\n              {week.map((day) =>\n                dayCell(\n                  day,\n                  view === \"week\" ? maxEvents * 2 : maxEvents,\n                  view === \"month\" && day.getMonth() !== date.getMonth(),\n                ),\n              )}\n            </tr>\n          ))}\n        </tbody>\n      </table>\n    </div>\n  );\n}\n",
      "type": "registry:ui",
      "target": "@ui/uai/calendar-view.tsx"
    }
  ],
  "categories": [
    "data-display"
  ],
  "type": "registry:ui"
}