Documentation menu
Getting Started
Components
Primitives
- Agent Thinking
- Alert
- Alert Dialog
- Avatar
- Badge
- Breadcrumb
- Button
- Button Group
- Calendar
- Card
- Checkbox
- Command
- Command Palette
- Context Menu
- Data Table
- Dialog
- Dropdown Menu
- Empty
- Field
- Glow Cloud
- Input
- Label
- Medication Schedule
- Period Tabs
- Popover
- Rainbow Button
- Scroll Area
- Select
- Selectable Card
- Separator
- Sheet
- Sidebar
- Skeleton
- Slider
- Sonner
- Spinner
- Switch
- Table
- Tabs
- Tag
- Textarea
- Timeline
- Tooltip
- Use Count Up
Charts and metrics
Patterns
- Confirm Button
- Date Picker
- Embedded
- Empty State
- Entity Drawer
- Error Boundary
- Field Row
- File Dropzone
- Form Dialog
- Kv
- List Editor
- List Page
- Live Time
- Mini Table
- Money
- Note Field
- Note Text
- Page Card
- Page Header
- Page Tabs
- Page Toolbar
- Person Cell
- Picture Field
- Print Card
- Range Switcher
- Row Actions
- Search Input
- Search Select
- Selected Box
- Signature Pad
- Status Badge
- Sub Nav Layout
- Suggest Input
- Tab Icons
- Table Footer
- Theme Accent Picker
- Time Picker
- View All Link
Dashboard cards
Advanced
Device frames
Website widgets
Website screens
Website panels
Advanced
Event Calendar
A full calendar: month, week, day, agenda and resource views, with drag and drop and recurring events.
import { addDays, setHours, startOfWeek } from "date-fns"
import { ChevronLeft, ChevronRight } from "lucide-react"
import { Button } from "@/registry/vcare/ui/button"
import { EventCalendar, useEventCalendarNavigation, useEventCalendarView } from "@/registry/vcare/ui/event-calendar/event-calendar"
import { EventCalendarContent } from "@/registry/vcare/ui/event-calendar/event-calendar-content"
import type { CalendarEvent } from "@/registry/vcare/ui/event-calendar/event-calendar-types"
const monday = startOfWeek(new Date(), { weekStartsOn: 1 })
const at = (day: number, hour: number) => setHours(addDays(monday, day), hour)
const events: CalendarEvent[] = [
{ id: "1", title: "Meera Raghavan", start: at(0, 9), end: at(0, 10), color: "var(--chart-1)" },
{ id: "2", title: "Arjun Nair", start: at(1, 11), end: at(1, 12), color: "var(--chart-2)" },
{ id: "3", title: "Physio: Anjali Das", start: at(2, 15), end: at(2, 16), color: "var(--chart-3)" },
{ id: "4", title: "Team meeting", start: at(3, 8), end: at(3, 9), color: "var(--warning)" },
{ id: "5", title: "Joseph Mathew", start: at(4, 10), end: at(4, 11), color: "var(--chart-1)" },
]
/** A small toolbar built from the calendar's navigation and view hooks. */
function CalendarNav() {
const { title, prev, next, today } = useEventCalendarNavigation()
const { view, availableViews, setView } = useEventCalendarView()
return (
<div className="mb-3 flex flex-wrap items-center gap-2">
<Button variant="outline" size="sm" onClick={today}>Today</Button>
<Button variant="ghost" size="icon-sm" aria-label="Previous" onClick={prev}><ChevronLeft /></Button>
<Button variant="ghost" size="icon-sm" aria-label="Next" onClick={next}><ChevronRight /></Button>
<span className="font-semibold">{title}</span>
<div className="ms-auto flex gap-1">
{availableViews.map((v) => (
<Button key={v} size="sm" variant={v === view ? "secondary" : "ghost"} onClick={() => setView(v)} className="capitalize">
{v}
</Button>
))}
</div>
</div>
)
}
export default function EventCalendarDemo() {
return (
<div className="h-[560px] w-full">
<EventCalendar defaultEvents={events} defaultView="week" views={["month", "week", "day", "agenda"]} weekStartsOn={1} dayStartHour={7} dayEndHour={19} nowIndicator className="h-full">
<div className="flex h-full flex-col">
<CalendarNav />
<EventCalendarContent className="min-h-0 flex-1" />
</div>
</EventCalendar>
</div>
)
}Installation
npx shadcn@latest add @vcare/event-calendarOr install directly from the URL: https://ui.vcarehms.com/r/event-calendar.json
- Install the dependencies:
npm i @base-ui/react @date-fns/tz date-fns lucide-react - Add the registry items it uses: icon-stack, popover, scroll-area, tooltip, utils.
- Copy these 12 files into your project and change the
@/registry/vcare/…imports to your own paths.
import { useMemo } from 'react';
import {
EventCalendarViewContext,
useEventCalendar,
useEventCalendarSelector,
useEventCalendarSettings,
useEventCalendarViewConfig,
} from '@/registry/vcare/ui/event-calendar/event-calendar';
import { EventCalendarEvent } from '@/registry/vcare/ui/event-calendar/event-calendar-event';
import { getDayKey, getRangeKey, toZoned, zonedStartOfDay } from '@/registry/vcare/ui/event-calendar/event-calendar-lib';
import type { EventCalendarDateRange, EventCalendarSegment } from '@/registry/vcare/ui/event-calendar/event-calendar-types';
import { IconStack } from '@/registry/vcare/ui/icon-stack';
import { mergeProps } from '@base-ui/react/merge-props';
import { useRender } from '@base-ui/react/use-render';
import { addDays, format } from 'date-fns';
import { cn } from '@/registry/vcare/lib/utils';
import { ScrollArea } from '@/registry/vcare/ui/scroll-area';
import { CalendarIcon } from 'lucide-react';
// The agenda window length is the agendaDayCount SETTING (the store derives
// visibleRange from it); a per-view prop here would silently disagree.
type EventCalendarAgendaViewProps = useRender.ComponentProps<'div'>;
function EventCalendarAgendaView({ className, render, ...props }: EventCalendarAgendaViewProps) {
const instance = useEventCalendar();
const settings = useEventCalendarSettings();
const viewConfig = useEventCalendarViewConfig();
const visibleRange = useEventCalendarSelector<unknown, EventCalendarDateRange>((state) => state.visibleRange, {
isEqual: (a, b) => getRangeKey(a) === getRangeKey(b),
});
// Subscribe to event changes via the day-bucket content of the whole range
useEventCalendarSelector((state) => state.events);
const days = useMemo(() => {
const result: Date[] = [];
let cursor = zonedStartOfDay(visibleRange.start, settings.timeZone);
while (cursor < visibleRange.end) {
result.push(cursor);
cursor = zonedStartOfDay(addDays(toZoned(cursor, settings.timeZone), 1), settings.timeZone);
}
return result;
}, [visibleRange, settings.timeZone]);
const index = instance.internals.getIndex();
const groups = days
.map((day) => ({
day,
bucket: index.byDay.get(getDayKey(day, settings.timeZone)),
}))
.filter((group) => {
const total = (group.bucket?.allDay.length ?? 0) + (group.bucket?.timed.length ?? 0);
return total > 0;
});
const isToday = (day: Date) => getDayKey(day, settings.timeZone) === getDayKey(new Date(), settings.timeZone);
const native = viewConfig.scrollbars === 'native';
const body = (
<>
{groups.length === 0 ? (
<div
data-slot="event-calendar-no-events"
className={cn('flex min-h-72 flex-col items-center justify-center gap-4 py-16', viewConfig.classNames?.noEvents)}
>
{viewConfig.renderNoEvents?.() ?? (
<>
<IconStack>
<CalendarIcon className="size-5" aria-hidden="true" />
</IconStack>
<span className="text-muted-foreground text-sm">{settings.i18n.labels.noEvents}</span>
</>
)}
</div>
) : (
// Drop the very last row's bottom border so it does not double up with
// the calendar container's own bottom border. Targets the last day
// group's last child (its last agenda item); per-item `border-b` is
// kept everywhere else, including each day's internal rows.
<div className="flex flex-col [&>*:last-child>*:last-child]:border-b-0">
{groups.map(({ day, bucket }) => {
const items = [...(bucket?.allDay ?? []), ...(bucket?.timed ?? [])];
const zoned = toZoned(day, settings.timeZone);
const weekday = format(zoned, 'EEEE', { locale: settings.locale });
const dayDate = format(zoned, 'MMMM d, yyyy', {
locale: settings.locale,
});
return (
<div
key={day.getTime()}
data-slot="event-calendar-agenda-day"
data-today={isToday(day) || undefined}
// A named group per day so a screen reader can step day by day
// (and hear how full one is) instead of arrowing every row.
role="group"
aria-label={`${weekday}, ${dayDate}, ${settings.i18n.labels.events(items.length)}`}
>
{/* Group header: weekday (leading) + full date (trailing) */}
<div
data-slot="event-calendar-agenda-day-header"
// The day bar is the agenda's only structure, so give it a
// heading level: the H key and the rotor can jump between
// days, which is the whole point of a long agenda.
role="heading"
aria-level={3}
className={cn(
'bg-muted/60 sticky top-0 z-10 flex items-baseline justify-between gap-4 border-b px-4 py-2',
// The custom ScrollArea's overlay scrollbar (w-2.5 = 10px)
// is painted UNDER this sticky, z-10, opaque header, so the
// thumb vanishes behind the day bar at the top of the view.
// Inset the header by the scrollbar lane so its background
// stops before the scrollbar instead of covering it. Native
// scrollbars already sit outside the content box, so this
// only applies to the custom-scrollbar path.
!native && 'me-2.5',
viewConfig.classNames?.agendaDayHeader,
)}
>
<span className={cn('text-foreground font-semibold', isToday(day) && 'text-primary')}>{weekday}</span>
<span className="text-muted-foreground font-medium tabular-nums">{dayDate}</span>
</div>
{items.map((segment) => (
<EventCalendarAgendaItem key={segment.occurrence.key} segment={segment} />
))}
</div>
);
})}
</div>
)}
</>
);
const defaultProps = {
'data-slot': 'event-calendar-agenda-view',
'data-view': 'agenda',
// Unlike the grid views the agenda has no row/column semantics to carry a
// name, so label the region with the day range it covers - through
// formatDayRange, so a consumer override reaches it.
role: 'group',
'aria-label': settings.i18n.functions.formatDayRange(visibleRange, {
locale: settings.locale,
}),
className: cn('flex min-h-0 flex-1 flex-col overflow-hidden border-t', viewConfig.classNames?.agendaView, className),
children: native ? (
<div data-slot="scroll-area-viewport" data-ec-native-scroll="" className="h-full overflow-y-auto">
{body}
</div>
) : (
<ScrollArea className="h-full">{body}</ScrollArea>
),
};
return (
<EventCalendarViewContext.Provider value={{ view: 'agenda' }}>
{useRender({
defaultTagName: 'div',
render,
props: mergeProps<'div'>(defaultProps, props),
})}
</EventCalendarViewContext.Provider>
);
}
/**
* One agenda row: a full-width, selectable table row - time column, color dot,
* and title (all replaceable via renderAgendaEvent). Clicking selects the
* event (drag/resize stay off in the agenda).
*/
function EventCalendarAgendaItem({ segment }: { segment: EventCalendarSegment }) {
const viewConfig = useEventCalendarViewConfig();
return (
<EventCalendarEvent
segment={segment}
className={cn(
// read-only list: hover only, no selected/focused styling on click
'hover:bg-accent/40 gap-3 rounded-none border-b px-4 py-2.5 transition-colors',
viewConfig.classNames?.agendaItem,
)}
/>
);
}
export { EventCalendarAgendaView };
export type { EventCalendarAgendaViewProps };'use client';
import { type ComponentType, type ReactNode } from 'react';
import { useEventCalendarSelector, useEventCalendarViewConfig } from '@/registry/vcare/ui/event-calendar/event-calendar';
import { EventCalendarAgendaView } from '@/registry/vcare/ui/event-calendar/event-calendar-agenda-view';
import { EventCalendarMonthView } from '@/registry/vcare/ui/event-calendar/event-calendar-month-view';
import { EventCalendarResourceView } from '@/registry/vcare/ui/event-calendar/event-calendar-resource-view';
import { EventCalendarDaysView, EventCalendarDayView, EventCalendarWeekView } from '@/registry/vcare/ui/event-calendar/event-calendar-time-grid';
import type { CalendarView } from '@/registry/vcare/ui/event-calendar/event-calendar-types';
import { mergeProps } from '@base-ui/react/merge-props';
import { useRender } from '@base-ui/react/use-render';
import { cn } from '@/registry/vcare/lib/utils';
const DEFAULT_VIEW_COMPONENTS: Record<CalendarView, ComponentType> = {
month: EventCalendarMonthView,
week: EventCalendarWeekView,
day: EventCalendarDayView,
days: EventCalendarDaysView,
agenda: EventCalendarAgendaView,
resource: EventCalendarResourceView,
};
interface EventCalendarContentProps extends Omit<useRender.ComponentProps<'div'>, 'children'> {
/** Swap individual view implementations. */
components?: Partial<Record<CalendarView, ComponentType>>;
/** Replaces the switchboard entirely; read useEventCalendarView() inside. */
children?: ReactNode;
}
function EventCalendarContent({ className, render, components, children, ...props }: EventCalendarContentProps) {
const viewConfig = useEventCalendarViewConfig();
const view = useEventCalendarSelector((state) => state.view);
const loading = useEventCalendarSelector((state) => state.loading);
const resolved = {
...DEFAULT_VIEW_COMPONENTS,
...viewConfig.components,
...components,
};
// A spread copies keys that hold `undefined`, so `components={{ month: isPro
// ? ProMonth : undefined }}` would erase the default and render <undefined />.
const ActiveView = resolved[view] ?? DEFAULT_VIEW_COMPONENTS[view];
const defaultProps = {
'data-slot': 'event-calendar-content',
'data-view': view,
'data-loading': loading || undefined,
className: cn(
'relative flex min-h-0 min-w-0 flex-1 flex-col',
'data-loading:pointer-events-none data-loading:opacity-60',
viewConfig.classNames?.content,
className,
),
children: children ?? <ActiveView />,
};
return useRender({
defaultTagName: 'div',
render,
props: mergeProps<'div'>(defaultProps, props),
});
}
export { DEFAULT_VIEW_COMPONENTS, EventCalendarContent };
export type { EventCalendarContentProps };import { useCallback, useEffect, useMemo } from 'react';
import { useEventCalendar, useEventCalendarViewConfig, type EventCalendarInstance } from '@/registry/vcare/ui/event-calendar/event-calendar';
import { snapMinutes, toZoned, zonedStartOfDay } from '@/registry/vcare/ui/event-calendar/event-calendar-lib';
import type { EventCalendarProposedUpdate, EventCalendarSegment } from '@/registry/vcare/ui/event-calendar/event-calendar-types';
import { addDays, addMinutes, differenceInCalendarDays } from 'date-fns';
/**
* Activation policy (dnd-kit parity where proven):
* mouse move 5px before a drag starts (below = click), create 4px;
* touch long-press 250ms with 5px tolerance (movement past tolerance
* before the delay cancels the drag so taps stay taps).
*/
const EVENT_CALENDAR_ACTIVATION = {
moveDistancePx: 5,
createDistancePx: 4,
touchDelayMs: 250,
touchTolerancePx: 5,
autoScrollEdgePx: 48,
autoScrollMaxStepPx: 15,
} as const;
type GestureKind = 'move' | 'resize-start' | 'resize-end' | 'create';
interface TimeColumnRect {
day: Date;
rect: DOMRect;
boundsStartMin: number;
boundsEndMin: number;
resourceId?: string;
}
interface DayCellRect {
day: Date;
rect: DOMRect;
}
interface Surface {
/** Minute-precise day columns (week/day/days) or resource columns. */
columns: TimeColumnRect[];
/** Day-precise cells (month grid, all-day row). */
cells: DayCellRect[];
viewport: HTMLElement | null;
/**
* Viewport rect captured ONCE at gesture start. The scroll container does
* not move on screen while a pointer drag is captured (auto-scroll changes
* its scrollTop, not its box), so reusing this avoids a per-pointermove
* getBoundingClientRect - that read forces a synchronous full-document
* reflow, which is cheap on a bare demo page but ~200ms on a long docs page
* (big prop tables re-lay-out on every flush), turning drag into a slideshow.
*/
viewportRect: DOMRect | null;
viewportStartScrollTop: number;
/**
* Live scrollTop, seeded from the start value and advanced by auto-scroll
* itself. Tracking it here lets pointerMinutes read a number instead of the
* DOM `scrollTop` property every move (another forced reflow).
*/
scrollTop: number;
}
/** Module flag so chip onClick can ignore the click that ends a drag. */
let lastGestureEndedAt = 0;
function wasRecentDrag(): boolean {
return performance.now() - lastGestureEndedAt < 250;
}
/**
* A press that started on an event chip. Slot-create clicks consult this so a
* refused drag (e.g. a locked chip that never registers a gesture) whose
* trailing native click retargets to the empty grid does NOT open a create
* dialog. Refreshed on release so it covers long presses; the chip's own
* click-to-edit is unaffected (only grid slot-clicks check it).
*/
let lastChipPressAt = 0;
function markChipPress(): void {
lastChipPressAt = performance.now();
window.addEventListener(
'pointerup',
() => {
lastChipPressAt = performance.now();
},
{ once: true, capture: true },
);
}
function wasRecentChipPress(): boolean {
return performance.now() - lastChipPressAt < 300;
}
/**
* Registry of in-flight gesture cancels. A gesture measures its surface (day
* columns and cells) once at activation and then lives on window listeners, so
* the CALENDAR - not the chip, chips legitimately unmount mid-gesture (lane
* repacking, a "+N more" popover closing) - is what must be able to abort it.
* Cancel fully reverts: listeners, overlays and the body drag state all clear,
* and no update is committed.
*/
const activeGestureCancels = new Set<() => void>();
/** Cancel (and fully revert) every in-flight event calendar pointer gesture. */
function cancelActiveEventCalendarGestures(): void {
for (const cancel of [...activeGestureCancels]) cancel();
}
/**
* Mounted-consumer count for the gestures hook. Every chip holds one, so only
* the LAST consumer leaving means the calendar itself is gone; aborting when
* any single chip unmounts would kill a drag the user is still holding.
*/
let gestureConsumers = 0;
/**
* Snap a translate offset to the device pixel grid. The cursor-following
* overlays (carry clone, drop hint) are their own `will-change: transform`
* compositing layers: the GPU rasterizes their text once and repositions that
* texture each frame, so a subpixel translate (getBoundingClientRect and raw
* clientX/Y are routinely fractional) resamples the texture and blurs the
* text. Rounding each offset to a whole device pixel lands the layer on the
* grid so glyphs stay crisp, without giving up the per-frame GPU transform.
*/
function snapToPixel(value: number): number {
const dpr = typeof window !== 'undefined' ? window.devicePixelRatio || 1 : 1;
return Math.round(value * dpr) / dpr;
}
function collectSurface(origin: HTMLElement, fallbackRoot?: HTMLElement | null): Surface {
// A gesture from a portaled surface (the "+N more" popover) has no calendar
// ancestor, so fall back to the root the host registered on the instance.
const root =
origin.closest<HTMLElement>('[data-slot=event-calendar-time-grid]') ??
origin.closest<HTMLElement>('[data-slot=event-calendar-resource-view]') ??
origin.closest<HTMLElement>('[data-slot=event-calendar-month-view]') ??
origin.closest<HTMLElement>('[data-slot=event-calendar]') ??
fallbackRoot ??
null;
const columns: TimeColumnRect[] = [];
const cells: DayCellRect[] = [];
if (root) {
for (const el of root.querySelectorAll<HTMLElement>('[data-ec-day]')) {
const day = new Date(Number(el.dataset.ecDay));
if (el.dataset.ecBoundsStart !== undefined) {
columns.push({
day,
rect: el.getBoundingClientRect(),
boundsStartMin: Number(el.dataset.ecBoundsStart),
boundsEndMin: Number(el.dataset.ecBoundsEnd),
resourceId: el.dataset.ecResource,
});
} else {
cells.push({ day, rect: el.getBoundingClientRect() });
}
}
}
const viewport = root?.querySelector<HTMLElement>('[data-slot=scroll-area-viewport]') ?? null;
const viewportStartScrollTop = viewport?.scrollTop ?? 0;
return {
columns,
cells,
viewport,
viewportRect: viewport?.getBoundingClientRect() ?? null,
viewportStartScrollTop,
scrollTop: viewportStartScrollTop,
};
}
function findColumn(surface: Surface, clientX: number): TimeColumnRect | undefined {
const scrollAdjusted = surface.columns;
let best: TimeColumnRect | undefined;
for (const col of scrollAdjusted) {
if (clientX >= col.rect.left && clientX < col.rect.right) return col;
if (!best) best = col;
// clamp to nearest horizontal column
const bestDist = Math.min(Math.abs(clientX - best.rect.left), Math.abs(clientX - best.rect.right));
const dist = Math.min(Math.abs(clientX - col.rect.left), Math.abs(clientX - col.rect.right));
if (dist < bestDist) best = col;
}
return best;
}
function findCell(surface: Surface, x: number, y: number): DayCellRect | undefined {
return surface.cells.find((cell) => x >= cell.rect.left && x < cell.rect.right && y >= cell.rect.top && y < cell.rect.bottom);
}
function pointerMinutes(surface: Surface, col: TimeColumnRect, clientY: number): number {
const scrollDelta = surface.scrollTop - surface.viewportStartScrollTop;
const boundsMinutes = col.boundsEndMin - col.boundsStartMin;
const pxPerMinute = col.rect.height / Math.max(1, boundsMinutes);
const y = clientY - col.rect.top + scrollDelta;
return col.boundsStartMin + y / pxPerMinute;
}
interface BeginGestureConfig<TData> {
instance: EventCalendarInstance<TData>;
kind: GestureKind;
origin: HTMLElement;
startEvent: PointerEvent;
segment?: EventCalendarSegment<TData>;
/** create only */
createDay?: Date;
createAllDay?: boolean;
/**
* Consumer classNames for the engine's vanilla-DOM overlays (carry clone,
* validation hint pill), forwarded by the gestures hook - the engine itself
* must never import from the React chip module.
*/
ui?: {
dragCarry?: string;
dragCarryInvalid?: string;
dropHint?: string;
};
}
/**
* A move/resize was refused (locked, per-event disabled, or interaction off).
* Rather than silently swallow the press, track the pointer: once it crosses
* the activation threshold - i.e. the user genuinely tried to drag - show a
* not-allowed cursor and broadcast once via onDragBlocked so the consumer can
* explain it. The calendar picks no message. Fires at most once per gesture.
*/
function beginBlockedGesture<TData>(
instance: EventCalendarInstance<TData>,
startEvent: PointerEvent,
segment: EventCalendarSegment<TData>,
gesture: 'move' | 'resize',
) {
const startX = startEvent.clientX;
const startY = startEvent.clientY;
const activation = {
...EVENT_CALENDAR_ACTIVATION,
...instance.settings.activation,
};
const event = segment.occurrence.event;
const reason: 'readOnly' | 'disabled' | 'interactions-off' = event.readOnly
? 'readOnly'
: (gesture === 'move' ? event.draggable : event.resizable) === false
? 'disabled'
: 'interactions-off';
const pointerId = startEvent.pointerId;
let activated = false;
let finished = false;
const onMove = (e: PointerEvent) => {
if (e.pointerId !== pointerId || activated) return;
if (Math.hypot(e.clientX - startX, e.clientY - startY) < activation.moveDistancePx) {
return;
}
activated = true;
document.body.style.cursor = 'not-allowed';
// body class alongside the inline cursor so consumer CSS can restyle or
// detect the blocked-drag state (mirrors "ec-dragging")
document.body.classList.add('ec-drag-blocked');
// only now is there anything to get stuck: focus loss means the release
// may never be delivered, leaving the cursor not-allowed document-wide
window.addEventListener('blur', cleanup);
instance.settings.onDragBlocked?.(segment.occurrence, { gesture, reason });
};
const cleanup = () => {
if (finished) return;
finished = true;
window.removeEventListener('pointermove', onMove);
window.removeEventListener('pointerup', onRelease);
window.removeEventListener('pointercancel', onRelease);
window.removeEventListener('blur', cleanup);
if (activated) {
document.body.style.cursor = '';
document.body.classList.remove('ec-drag-blocked');
// the pointer travelled: suppress the trailing click so the event's own
// dialog does not open on top of the rejection message
lastGestureEndedAt = performance.now();
}
};
// only the pointer that started the press may end it: a second finger
// lifting must not clear the not-allowed cursor out from under it
const onRelease = (e: PointerEvent) => {
if (e.pointerId !== pointerId) return;
cleanup();
};
window.addEventListener('pointermove', onMove);
window.addEventListener('pointerup', onRelease);
window.addEventListener('pointercancel', onRelease);
}
function beginGesture<TData>(config: BeginGestureConfig<TData>) {
const { instance, kind, origin, startEvent, segment, ui } = config;
const { settings, internals, api } = instance;
const timeZone = settings.timeZone;
const snap = settings.snapDuration;
// per-calendar tuning shallow-merged over the module defaults
const activation = { ...EVENT_CALENDAR_ACTIVATION, ...settings.activation };
const startX = startEvent.clientX;
const startY = startEvent.clientY;
const pointerId = startEvent.pointerId;
// Resolved once: the chip can be re-rendered away mid-gesture. A gesture
// from a portaled surface (the "+N more" popover) has no calendar ancestor,
// so fall back to the registered root - same reason as collectSurface.
const announcer =
origin.closest<HTMLElement>('[data-slot=event-calendar]')?.querySelector<HTMLElement>('[data-slot=event-calendar-announcer]') ??
internals.getRootEl()?.querySelector<HTMLElement>('[data-slot=event-calendar-announcer]') ??
null;
const isTouch = startEvent.pointerType === 'touch';
// resize activates immediately on precise pointers; on touch it waits for
// the same long-press as a move, so a finger landing on the (invisible on
// touch) handle strip can never start a resize the user never asked for
let active = kind.startsWith('resize') && !isTouch;
let surface: Surface | null = active ? collectSurface(origin, internals.getRootEl()) : null;
let rafScroll: number | null = null;
let lastProposalKey = '';
let touchTimer: ReturnType<typeof setTimeout> | null = null;
let hintEl: HTMLDivElement | null = null;
let lastValid = true;
// Drag-create anchor minute, frozen at the first proposal: re-deriving it
// from the stale startY client coordinate + the CURRENT scroll delta would
// make the anchor drift with auto-scroll instead of staying pinned.
let createAnchorMin: number | null = null;
let lastPointer: PointerEvent = startEvent;
const occurrence = segment?.occurrence;
const isBar = occurrence ? occurrence.allDay || occurrence.end.getTime() - occurrence.start.getTime() > 24 * 60 * 60 * 1000 : false;
// Preserve the grab offset so the event does not jump to the pointer
let grabOffsetMin = 0;
/**
* The grabbed CHIP, not the whole occurrence. A cross-midnight event renders
* one chip per day, so the offset above is measured in the grabbed chip's own
* day frame (mixing the two frames jumps a tail chip a full day on grab) and
* these two carry that chip back to the occurrence. For a chip that fits in
* one day the lead is 0 and the duration is the occurrence's, i.e. unchanged.
*/
let grabLeadMs = 0;
let grabSegDurationMs = occurrence ? occurrence.end.getTime() - occurrence.start.getTime() : 0;
/**
* Which day of a multi-day bar was grabbed. Without it the day-granular move
* slides the bar's START under the pointer, so a Mon-Fri bar grabbed on
* Wednesday teleports two days forward on the first nudge.
*/
let grabDayOffset = 0;
const activationDistance = kind === 'create' ? activation.createDistancePx : activation.moveDistancePx;
// Each gesture keeps its own cursor: a resize must stay ns/ew-resize for
// the whole drag (flipping to grabbing reads as a move) - vertical for
// timed blocks, horizontal for day-granular bars. Moves grab.
const gestureCursor = kind.startsWith('resize') ? (isBar ? 'ew-resize' : 'ns-resize') : 'grabbing';
const setBodyDragging = (on: boolean, invalid = false) => {
document.body.classList.toggle('ec-dragging', on);
document.body.style.cursor = on ? (invalid ? 'not-allowed' : gestureCursor) : '';
document.body.style.userSelect = on ? 'none' : '';
if (!on) document.body.style.removeProperty('-webkit-user-select');
};
const activate = () => {
if (active) return;
active = true;
// armed with the gesture, not with the press: a press that never activates
// holds no drag state, no overlay and no body class to strand
window.addEventListener('blur', onWindowBlur);
surface = collectSurface(origin, internals.getRootEl());
if (kind === 'move' && occurrence) {
const grabCell = findCell(surface, startX, startY);
if (grabCell) {
const originDay = zonedStartOfDay(occurrence.start, timeZone);
// end is exclusive, so step back an instant for the last covered day
const lastDay = zonedStartOfDay(new Date(Math.max(occurrence.end.getTime() - 1, occurrence.start.getTime())), timeZone);
const offset = differenceInCalendarDays(zonedStartOfDay(grabCell.day, timeZone), originDay);
// A gesture from the "+N more" popover grabs over whatever cell that
// floating surface happens to cover, so only a day the event actually
// spans can be the grabbed day.
if (offset >= 0 && offset <= differenceInCalendarDays(lastDay, originDay)) {
grabDayOffset = offset;
}
}
if (surface.columns.length > 0 && !isBar) {
const col = findColumn(surface, startX);
if (col) {
const colDayStart = zonedStartOfDay(col.day, timeZone);
const segStartMs = Math.max(occurrence.start.getTime(), colDayStart.getTime());
grabLeadMs = segStartMs - occurrence.start.getTime();
grabSegDurationMs = Math.min(occurrence.end.getTime(), addDays(colDayStart, 1).getTime()) - segStartMs;
grabOffsetMin = pointerMinutes(surface, col, startY) - (segStartMs - colDayStart.getTime()) / 60000;
}
}
}
setBodyDragging(true);
createCarry();
};
const computeProposal = (
e: PointerEvent,
): {
start: Date;
end: Date;
allDay: boolean;
dayGranular?: boolean;
resourceId?: string;
} | null => {
if (!surface) return null;
// ---- create: select a slot range
if (kind === 'create') {
if (config.createAllDay || surface.columns.length === 0) {
const anchor = zonedStartOfDay(config.createDay!, timeZone);
const cell = findCell(surface, e.clientX, e.clientY);
const target = cell ? zonedStartOfDay(cell.day, timeZone) : anchor;
const start = anchor <= target ? anchor : target;
const end = addDays(anchor <= target ? target : anchor, 1);
return { start, end, allDay: true, dayGranular: true };
}
const col = findColumn(surface, startX);
if (!col) return null;
if (createAnchorMin === null) {
createAnchorMin = snapMinutes(pointerMinutes(surface, col, startY), snap);
}
const anchorMin = createAnchorMin;
const curMin = snapMinutes(pointerMinutes(surface, col, e.clientY), snap);
const lo = Math.max(col.boundsStartMin, Math.min(anchorMin, curMin));
const hi = Math.min(col.boundsEndMin, Math.max(anchorMin, curMin, lo + snap));
const dayStart = zonedStartOfDay(col.day, timeZone);
return {
start: addMinutes(dayStart, lo),
end: addMinutes(dayStart, hi),
allDay: false,
resourceId: col.resourceId,
};
}
if (!occurrence) return null;
const durationMs = occurrence.end.getTime() - occurrence.start.getTime();
// ---- day-granularity: month cells and bars in the all-day row
const overCell = findCell(surface, e.clientX, e.clientY);
// A timed event dropped on the all-day lane (a day cell inside a surface
// that also has time columns) converts to a full-day event on that day.
if (kind === 'move' && !isBar && surface.columns.length > 0 && overCell !== undefined) {
const targetDay = zonedStartOfDay(overCell.day, timeZone);
return {
start: targetDay,
end: addDays(targetDay, 1),
allDay: true,
dayGranular: true,
};
}
const useCells = surface.columns.length === 0 || (isBar && overCell !== undefined);
if (useCells) {
const cell = overCell ?? findCell(surface, startX, startY);
if (!cell) return null;
const targetDay = zonedStartOfDay(cell.day, timeZone);
if (kind === 'move') {
const originDay = zonedStartOfDay(occurrence.start, timeZone);
// minus the grabbed day: the bar follows the pointer by the distance
// travelled, it does not re-anchor its start under the pointer
const delta = differenceInCalendarDays(targetDay, originDay) - grabDayOffset;
const start = addDays(toZoned(occurrence.start, timeZone), delta);
return {
start,
end: new Date(start.getTime() + durationMs),
allDay: occurrence.allDay,
dayGranular: true,
};
}
// bar edge resize: day granularity
if (kind === 'resize-start') {
const time = occurrence.start.getTime() - zonedStartOfDay(occurrence.start, timeZone).getTime();
const start = new Date(targetDay.getTime() + time);
if (start >= occurrence.end) return null;
return {
start,
end: occurrence.end,
allDay: occurrence.allDay,
dayGranular: true,
};
}
const time = occurrence.allDay ? 0 : occurrence.end.getTime() - zonedStartOfDay(occurrence.end, timeZone).getTime();
const end = occurrence.allDay ? addDays(targetDay, 1) : new Date(addDays(targetDay, time > 0 ? 0 : 1).getTime() + time);
if (end <= occurrence.start) return null;
return {
start: occurrence.start,
end,
allDay: occurrence.allDay,
dayGranular: true,
};
}
// ---- minute-granularity: time-grid columns
const col = findColumn(surface, e.clientX);
if (!col) return null;
const dayStart = zonedStartOfDay(col.day, timeZone);
const rawMin = pointerMinutes(surface, col, e.clientY);
if (kind === 'move') {
const newStartMin = snapMinutes(rawMin - grabOffsetMin, snap);
// the clamp keeps the grabbed CHIP inside the column it is over; the
// lead then carries the rest of a cross-midnight occurrence with it
const chipDurationMin = Math.round(grabSegDurationMs / 60000);
const clamped = Math.min(Math.max(newStartMin, col.boundsStartMin), col.boundsEndMin - chipDurationMin);
const start = new Date(addMinutes(dayStart, clamped).getTime() - grabLeadMs);
return {
start,
end: new Date(start.getTime() + durationMs),
allDay: false,
resourceId: col.resourceId,
};
}
const min = snapMinutes(rawMin, snap);
// Both endpoints expressed in the POINTED column's day coordinates.
// Anchoring each endpoint to its OWN day breaks cross-midnight events:
// a 23:30 pointer in the start day's column would apply 1410 minutes to
// the end's next-day anchor and jump the end a full day late (and a
// midnight-ending event computes occEndMin 0 against its own day).
const occStartMinInCol = Math.round((occurrence.start.getTime() - dayStart.getTime()) / 60000);
const occEndMinInCol = Math.round((occurrence.end.getTime() - dayStart.getTime()) / 60000);
if (kind === 'resize-start') {
const clamped = Math.min(Math.max(min, col.boundsStartMin), Math.min(occEndMinInCol - snap, col.boundsEndMin));
const start = addMinutes(dayStart, clamped);
if (start >= occurrence.end) return null;
return { start, end: occurrence.end, allDay: false };
}
const clamped = Math.max(Math.min(min, col.boundsEndMin), Math.max(occStartMinInCol + snap, col.boundsStartMin));
const end = addMinutes(dayStart, clamped);
if (end <= occurrence.start) return null;
return { start: occurrence.start, end, allDay: false };
};
const applyProposal = (e: PointerEvent) => {
const proposal = computeProposal(e);
if (!proposal) return;
const key = `${proposal.start.getTime()}-${proposal.end.getTime()}-${proposal.allDay}-${proposal.resourceId ?? ''}`;
if (key === lastProposalKey) return;
lastProposalKey = key;
if (kind === 'create') {
const draft = { ...proposal, view: instance.getState().view };
if (settings.canSelectSlot && !settings.canSelectSlot(draft)) return;
internals.setSlotDraft(draft);
return;
}
const update: EventCalendarProposedUpdate<TData> = {
event: occurrence!.event,
occurrence: occurrence!,
...proposal,
source: kind as 'drag' | 'resize-start' | 'resize-end',
};
if (kind === 'move') update.source = 'drag';
const valid = settings.canDropEvent ? settings.canDropEvent(update) : true;
lastValid = valid;
setBodyDragging(true, !valid);
internals.setDrag({
kind: kind === 'move' ? 'move' : (kind as 'resize-start' | 'resize-end'),
occurrence: occurrence!,
proposedStart: proposal.start,
proposedEnd: proposal.end,
proposedAllDay: proposal.allDay,
proposedDayGranular: proposal.dayGranular ?? false,
proposedResourceId: proposal.resourceId,
valid,
});
};
// Cursor-attached carry clone for MOVE gestures: the event travels freely
// with the pointer, like an absolutely positioned overlay, while the
// in-grid ghost renders only a faint dashed placeholder at the snapped
// drop slot (EVENT_CALENDAR_GHOST.move). Vanilla DOM: cloned once at
// activation, transformed per pointermove, zero React work per frame.
let carryEl: HTMLDivElement | null = null;
let carryDX = 0;
let carryDY = 0;
const CARRY_CLASS =
'bg-background pointer-events-none fixed top-0 left-0 z-100 overflow-hidden rounded-sm opacity-90 shadow-md will-change-transform' +
(ui?.dragCarry ? ' ' + ui.dragCarry : '');
const CARRY_INVALID_CLASS = `${CARRY_CLASS} ring-destructive/60 ring-1` + (ui?.dragCarryInvalid ? ' ' + ui.dragCarryInvalid : '');
const createCarry = () => {
if (kind !== 'move') return;
const chip = origin.closest<HTMLElement>('[data-slot=event-calendar-event]') ?? origin;
const rect = chip.getBoundingClientRect();
// The clone is re-parented to <body>, escaping the calendar's inherited
// font-size, so copy the source chip's resolved type - this keeps the carry
// matching the grid at any consumer text scale (e.g. root text-sm).
const chipFont = getComputedStyle(chip);
carryDX = startX - rect.left;
carryDY = startY - rect.top;
carryEl = document.createElement('div');
carryEl.setAttribute('data-slot', 'event-calendar-drag-carry');
carryEl.setAttribute('aria-hidden', 'true');
carryEl.className = CARRY_CLASS;
carryEl.style.width = `${rect.width}px`;
carryEl.style.height = `${rect.height}px`;
carryEl.style.fontSize = chipFont.fontSize;
carryEl.style.lineHeight = chipFont.lineHeight;
carryEl.style.transform = `translate3d(${snapToPixel(rect.left)}px, ${snapToPixel(rect.top)}px, 0)`;
const clone = chip.cloneNode(true) as HTMLElement;
clone.removeAttribute('data-dragging');
clone.style.width = '100%';
clone.style.height = '100%';
carryEl.appendChild(clone);
document.body.appendChild(carryEl);
};
const positionCarry = (e: PointerEvent) => {
if (!carryEl) return;
carryEl.style.transform = `translate3d(${snapToPixel(e.clientX - carryDX)}px, ${snapToPixel(e.clientY - carryDY)}px, 0)`;
const cls = lastValid ? CARRY_CLASS : CARRY_INVALID_CLASS;
if (carryEl.className !== cls) carryEl.className = cls;
};
// Cursor-following validation hint, visible ONLY while the proposal is
// rejected (canDropEvent / bounds). Vanilla DOM: zero React work per frame;
// pairs with the not-allowed cursor and the ghost's destructive marking.
const updateHint = (e: PointerEvent) => {
if (lastValid || !active) {
hintEl?.remove();
hintEl = null;
return;
}
if (!hintEl) {
hintEl = document.createElement('div');
hintEl.setAttribute('data-slot', 'event-calendar-drop-hint');
// physical left-0 anchor: translate3d positions in physical clientX
// coordinates, so a logical start-0 anchor would fling it off-screen
// in RTL documents
hintEl.className =
'bg-background text-destructive border-destructive/40 pointer-events-none fixed top-0 left-0 z-100 rounded-md border px-2 py-0.5 text-xs font-medium shadow-sm' +
(ui?.dropHint ? ' ' + ui.dropHint : '');
hintEl.textContent = settings.i18n.labels.dropNotAllowed;
document.body.appendChild(hintEl);
}
hintEl.style.transform = `translate3d(${snapToPixel(e.clientX + 12)}px, ${snapToPixel(e.clientY + 16)}px, 0)`;
};
const autoScroll = (e: PointerEvent) => {
// Cached rect (see Surface.viewportRect) - never getBoundingClientRect per
// move; the box is stable while the pointer is captured.
const rect = surface?.viewportRect;
if (!surface?.viewport || !rect) return;
const edge = activation.autoScrollEdgePx;
const step = activation.autoScrollMaxStepPx;
let delta = 0;
/**
* The scroller wraps the time track ONLY - the day headers and the all-day
* row sit above it, outside the box - so its top edge is a hard floor. A
* pointer above that floor is over one of those rows, and both are drop
* targets in their own right (a bar moving across dates, a timed chip
* lifted onto the all-day lane to convert it); they are already fully
* visible, so reaching them is never a request to scroll. Without the
* floor, "past the top edge" is true on every single move of a horizontal
* all-day drag and the track pans out from under a gesture that only wants
* to change the date - fast, because the proximity ratio grows past 1 the
* further above the box the pointer sits.
*
* Below the track there is no such row, so overshooting the bottom keeps
* scrolling - that is how a grid is normally asked to keep going - but the
* eased speed is capped at one step per frame for the same reason.
*/
if (e.clientY >= rect.top) {
if (e.clientY < rect.top + edge) {
delta = -step * ((rect.top + edge - e.clientY) / edge);
} else if (e.clientY > rect.bottom - edge) {
delta = step * Math.min(1, (e.clientY - (rect.bottom - edge)) / edge);
}
}
if (rafScroll) cancelAnimationFrame(rafScroll);
if (delta !== 0) {
const tick = () => {
// Write-then-readback: the browser clamps scrollTop at the scroll
// extent, so mirror only the APPLIED delta - otherwise parking the
// pointer in the edge zone at the limit keeps inflating the tracked
// value past reality and poisons every later minute mapping. When
// parked (nothing applied), stop the loop; the next pointermove
// restarts it.
const before = surface!.viewport!.scrollTop;
surface!.viewport!.scrollTop = before + delta;
const applied = surface!.viewport!.scrollTop - before;
if (applied === 0) return;
// keep the tracked scrollTop in step so pointerMinutes stays a pure
// number read (no DOM scrollTop, no forced reflow)
surface!.scrollTop += applied;
applyProposal(e);
rafScroll = requestAnimationFrame(tick);
};
rafScroll = requestAnimationFrame(tick);
}
};
// idempotent: pointerup, pointercancel, Escape, blur and the calendar-level
// teardown can race; whichever lands first wins and the rest no-op
let finished = false;
const cleanup = () => {
if (finished) return;
finished = true;
activeGestureCancels.delete(cancel);
window.removeEventListener('pointermove', onPointerMove);
window.removeEventListener('pointerup', onPointerUp);
window.removeEventListener('pointercancel', onCancel);
window.removeEventListener('blur', onWindowBlur);
window.removeEventListener('keydown', onKeyDown, true);
if (rafScroll) cancelAnimationFrame(rafScroll);
if (touchTimer) clearTimeout(touchTimer);
hintEl?.remove();
hintEl = null;
carryEl?.remove();
carryEl = null;
setBodyDragging(false);
};
const cancel = () => {
cleanup();
if (active) {
lastGestureEndedAt = performance.now();
internals.setDrag(null);
internals.setSlotDraft(null);
}
};
const onKeyDown = (e: KeyboardEvent) => {
if (e.key === 'Escape') {
e.stopPropagation();
cancel();
}
};
// focus loss mid-gesture (alt-tab, OS dialogs) means the release may never
// be delivered; treat it as a cancel so the gesture cannot get stuck and
// commit its stale proposal on the next click
const onWindowBlur = () => cancel();
const onPointerMove = (e: PointerEvent) => {
// a second finger must not drive - or cancel the pending long press of -
// the gesture this pointer started
if (e.pointerId !== pointerId) return;
lastPointer = e;
if (!active) {
const distance = Math.hypot(e.clientX - startX, e.clientY - startY);
if (isTouch) {
// Long-press pending: moving past tolerance means scroll, not drag
if (distance > activation.touchTolerancePx) cancel();
return;
}
if (distance < activationDistance) return;
activate();
}
applyProposal(e);
autoScroll(e);
updateHint(e);
positionCarry(e);
};
const onPointerUp = (e: PointerEvent) => {
if (e.pointerId !== pointerId) return;
cleanup();
if (!active) return;
lastGestureEndedAt = performance.now();
const state = instance.getState();
if (kind === 'create') {
const draft = state.slotDraft;
internals.setSlotDraft(null);
if (draft) {
api.select({
slot: { start: draft.start, end: draft.end, allDay: draft.allDay },
});
settings.onSelectSlot?.(draft);
}
return;
}
const drag = state.drag;
internals.setDrag(null);
if (!drag || !occurrence) return;
const unchanged =
drag.proposedStart.getTime() === occurrence.start.getTime() &&
drag.proposedEnd.getTime() === occurrence.end.getTime() &&
(drag.proposedResourceId === undefined || drag.proposedResourceId === occurrence.event.resourceId);
if (unchanged) return;
// Commit through the one validation funnel; consumer reject = automatic
// revert because the calendar never mutated during the gesture.
const accepted = internals.applyProposedUpdate({
event: occurrence.event,
occurrence,
start: drag.proposedStart,
end: drag.proposedEnd,
allDay: drag.proposedAllDay,
resourceId: drag.proposedResourceId,
source: kind === 'move' ? 'drag' : (kind as 'resize-start' | 'resize-end'),
});
// the polite live region is the only feedback a screen-reader user gets
// that the drop landed, and on what; a vetoed commit stays silent
if (accepted && announcer) {
announcer.textContent = `${occurrence.event.title}, ${settings.i18n.functions.formatEventTime(
toZoned(drag.proposedStart, timeZone),
toZoned(drag.proposedEnd, timeZone),
drag.proposedAllDay,
{ locale: settings.locale },
)}`;
}
};
const onCancel = (e: PointerEvent) => {
if (e.pointerId !== pointerId) return;
cancel();
};
window.addEventListener('pointermove', onPointerMove);
window.addEventListener('pointerup', onPointerUp);
window.addEventListener('pointercancel', onCancel);
// a resize on a precise pointer is live from the first frame, so it never
// reaches activate() to arm its own blur cancel
if (active) window.addEventListener('blur', onWindowBlur);
window.addEventListener('keydown', onKeyDown, true);
activeGestureCancels.add(cancel);
// Touch: long-press activation (movement past tolerance cancels above)
if (isTouch && !active) {
touchTimer = setTimeout(() => {
activate();
applyProposal(lastPointer);
}, activation.touchDelayMs);
}
}
/** Per-chip / per-surface pointer gesture wiring. */
function useEventCalendarGestures<TData = unknown>() {
const instance = useEventCalendar<TData>();
// Overlay classNames bridged from React config into the vanilla-DOM engine
// (which must never import from the chip module - circular).
const { classNames } = useEventCalendarViewConfig<TData>();
const ui = useMemo(
() => ({
dragCarry: classNames?.dragCarry,
dragCarryInvalid: classNames?.dragCarryInvalid,
dropHint: classNames?.dropHint,
}),
[classNames],
);
// An in-flight gesture lives on window listeners and body-appended overlays,
// so it must never outlive the calendar. Chips hold this hook too and they
// legitimately unmount mid-gesture, so only the LAST consumer leaving - the
// calendar itself going away - aborts.
useEffect(() => {
gestureConsumers += 1;
return () => {
gestureConsumers -= 1;
if (gestureConsumers === 0) cancelActiveEventCalendarGestures();
};
}, []);
const canDrag = useCallback(
(segment: EventCalendarSegment<TData>) => {
const { interactions } = instance.getState();
const event = segment.occurrence.event;
return interactions.drag && !event.readOnly && event.draggable !== false;
},
[instance],
);
const canResize = useCallback(
(segment: EventCalendarSegment<TData>) => {
const { interactions } = instance.getState();
const event = segment.occurrence.event;
return interactions.resize && !event.readOnly && event.resizable !== false;
},
[instance],
);
const beginMove = useCallback(
(e: React.PointerEvent, segment: EventCalendarSegment<TData>) => {
if (e.button !== 0) return;
if (!canDrag(segment)) {
// refused, but still give feedback + broadcast on a real drag attempt
beginBlockedGesture(instance, e.nativeEvent, segment, 'move');
return;
}
beginGesture({
instance,
kind: 'move',
origin: e.currentTarget as HTMLElement,
startEvent: e.nativeEvent,
segment,
ui,
});
},
[instance, canDrag, ui],
);
const beginResize = useCallback(
(e: React.PointerEvent, segment: EventCalendarSegment<TData>, edge: 'start' | 'end') => {
if (e.button !== 0) return;
if (!canResize(segment)) {
e.stopPropagation();
beginBlockedGesture(instance, e.nativeEvent, segment, 'resize');
return;
}
e.stopPropagation();
e.preventDefault();
beginGesture({
instance,
kind: edge === 'start' ? 'resize-start' : 'resize-end',
origin: e.currentTarget as HTMLElement,
startEvent: e.nativeEvent,
segment,
ui,
});
},
[instance, canResize, ui],
);
const beginCreate = useCallback(
(e: React.PointerEvent, day: Date, allDay: boolean) => {
if (e.button !== 0) return;
if (!instance.getState().interactions.selectSlot) return;
beginGesture({
instance,
kind: 'create',
origin: e.currentTarget as HTMLElement,
startEvent: e.nativeEvent,
createDay: day,
createAllDay: allDay,
ui,
});
},
[instance, ui],
);
return { beginMove, beginResize, beginCreate, canDrag, canResize };
}
export { EVENT_CALENDAR_ACTIVATION, cancelActiveEventCalendarGestures, markChipPress, useEventCalendarGestures, wasRecentChipPress, wasRecentDrag };'use client';
import { createContext, useContext, useMemo, type CSSProperties, type ReactNode } from 'react';
import {
useEventCalendar,
useEventCalendarSelector,
useEventCalendarViewConfig,
useEventCalendarViewContext,
} from '@/registry/vcare/ui/event-calendar/event-calendar';
import { markChipPress, useEventCalendarGestures, wasRecentDrag } from '@/registry/vcare/ui/event-calendar/event-calendar-dnd';
import { spansMultipleDays, toZoned, zonedStartOfDay } from '@/registry/vcare/ui/event-calendar/event-calendar-lib';
import type { EventCalendarOccurrence, EventCalendarSegment } from '@/registry/vcare/ui/event-calendar/event-calendar-types';
import { mergeProps } from '@base-ui/react/merge-props';
import { useRender } from '@base-ui/react/use-render';
import { addDays, format } from 'date-fns';
import { cn } from '@/registry/vcare/lib/utils';
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/registry/vcare/ui/tooltip';
import { RepeatIcon } from 'lucide-react';
/** Event color presets; each stays legible on light and dark surfaces. */
const EVENT_CALENDAR_COLORS: Array<{ name: string; value: string }> = [
{ name: 'Blue', value: 'var(--color-blue-500)' },
{ name: 'Emerald', value: 'var(--color-emerald-500)' },
{ name: 'Violet', value: 'var(--color-violet-500)' },
{ name: 'Rose', value: 'var(--color-rose-500)' },
{ name: 'Amber', value: 'var(--color-amber-500)' },
{ name: 'Cyan', value: 'var(--color-cyan-500)' },
{ name: 'Orange', value: 'var(--color-orange-500)' },
{ name: 'Pink', value: 'var(--color-pink-500)' },
{ name: 'Teal', value: 'var(--color-teal-500)' },
{ name: 'Indigo', value: 'var(--color-indigo-500)' },
];
/**
* Drag-ghost surfaces, shared verbatim by every view. A move CARRIES the
* event: the dnd engine attaches a full clone to the cursor
* (data-slot=event-calendar-drag-carry), so this in-grid ghost is only the
* dashed placeholder for the snapped drop slot. A resize STRETCHES instead:
* the chip itself at the proposed extent, dashed rather than solid.
*/
const EVENT_CALENDAR_GHOST = {
move: 'rounded-sm border border-dashed border-(--ec-event-color)/50 bg-(--ec-event-color)/8',
resize: 'rounded-sm border border-dashed border-(--ec-event-color)/70 overflow-hidden',
invalid: 'border-destructive/70 bg-destructive/10',
invalidResize: 'border-destructive/70',
/** Applied to the clone inside an invalid resize ghost. */
invalidContent: 'opacity-60',
} as const;
/**
* Fade-out truncation for stacked timed blocks, where squeezed cascade
* columns clip titles into a mash of glyphs; a right-edge mask fade reads
* cleaner than an ellipsis at those widths. Masked ONLY below a 10rem
* container: mask-image forces text off subpixel antialiasing, so masking
* wide chips makes the whole grid read bolder and shimmer while resizing.
* Wide chips keep the plain ellipsis. Exported for consumer renderEvent.
*/
const EVENT_CALENDAR_FADE_TRUNCATE =
'w-full truncate @max-[10rem]:text-clip @max-[10rem]:[mask-image:linear-gradient(to_right,#000_calc(100%-0.75rem),transparent)] @max-[10rem]:rtl:[mask-image:linear-gradient(to_left,#000_calc(100%-0.75rem),transparent)]';
/**
* The drag-to-create selection, shared by every view: a dashed primary
* outline over a faint wash with the range printed inside. `box` is the timed
* grid's single minute-positioned rectangle; `segment` is one day-cell slice
* of a multi-cell draft, with side borders and rounding only on the run's two
* ends so it reads as one dashed box rather than a row of them.
*/
const EVENT_CALENDAR_SLOT_DRAFT = {
box: 'rounded-sm border border-dashed border-primary/40 bg-primary/5',
segment: 'border-y border-dashed border-primary/40',
segmentStart: 'rounded-s-sm border-s',
segmentEnd: 'rounded-e-sm border-e',
/**
* The wash for segmented views, on the CELL not the dashed overlay: the
* overlay stacks above the chips, so tinting it would wash them instead.
*/
surface: 'bg-primary/5',
/**
* The range readout. `leading-none` is load-bearing: the shortest timed
* draft is one snap interval tall (16px at the default 15-minute snap and
* 4rem hour height), and looser leading renders ~18px, clipped by the
* draft's own overflow-hidden.
*/
label: 'text-primary truncate px-1 py-0.5 text-[0.6875rem] leading-none font-medium',
} as const;
interface EventCalendarChipContextValue<TData = unknown> {
occurrence: EventCalendarOccurrence<TData>;
segment: EventCalendarSegment<TData>;
isDragging: boolean;
isSelected: boolean;
}
const EventCalendarChipContext =
// eslint-disable-next-line @typescript-eslint/no-explicit-any
createContext<EventCalendarChipContextValue<any> | null>(null);
/** The chip's subject; usable inside renderEvent content and chip children. */
function useEventCalendarEventChip<TData = unknown>(): EventCalendarChipContextValue<TData> {
const ctx = useContext(EventCalendarChipContext);
if (!ctx) {
throw new Error('useEventCalendarEventChip must be used within <EventCalendarEvent>');
}
return ctx as EventCalendarChipContextValue<TData>;
}
interface EventCalendarEventProps<TData = unknown> extends Omit<useRender.ComponentProps<'button'>, 'children'> {
segment: EventCalendarSegment<TData>;
/** Replaces the default chip CONTENT; the wrapper stays calendar-owned. */
children?: ReactNode;
/**
* Static drag clone: the chip as-is but inert - no gestures, resize
* handles, selection/drag state, focus or pointer events.
*/
preview?: boolean;
}
/**
* The one interactive event element in every view. The wrapper owns a11y,
* data attributes, selection and drag/resize wiring; content comes from
* children, else renderEvent, else the built-in default.
*/
function EventCalendarEvent<TData = unknown>({ segment, className, render, children, preview = false, ...props }: EventCalendarEventProps<TData>) {
const instance = useEventCalendar<TData>();
const viewConfig = useEventCalendarViewConfig<TData>();
const { view } = useEventCalendarViewContext();
const gestures = useEventCalendarGestures<TData>();
const { settings } = instance;
const occurrence = segment.occurrence;
const event = occurrence.event;
const isSelectedRaw = useEventCalendarSelector<TData, boolean>((state) => state.selection.eventKeys.includes(occurrence.key), {
calendar: instance,
});
const isDraggingRaw = useEventCalendarSelector<TData, boolean>((state) => state.drag?.occurrence.key === occurrence.key, { calendar: instance });
// reactive, unlike gestures.canResize: api.setInteractions({ resize })
// must add/remove the handles without waiting for an unrelated re-render
const resizeOn = useEventCalendarSelector<TData, boolean>((state) => state.interactions.resize, {
calendar: instance,
});
// A preview clone must never inherit the source's selected/dragging state
// (the drag key matches, which would dim the clone itself).
const isSelected = preview ? false : isSelectedRaw;
const isDragging = preview ? false : isDraggingRaw;
const isBar = occurrence.allDay || spansMultipleDays(occurrence, settings.timeZone);
const inTimeGrid = view === 'week' || view === 'day' || view === 'days' || view === 'resource';
const interactive = view !== 'agenda' && !preview;
const timedBlock = inTimeGrid && !isBar;
const horizontalBar = isBar && !inTimeGrid;
// >= compactEventMinutes renders the stacked (title over time) layout, where
// squeezed cascade columns fade-truncate instead of clipping into neighbors
const stackedBlock = timedBlock && (segment.endMin ?? 0) - (segment.startMin ?? 0) >= viewConfig.compactEventMinutes;
const defaultContent = (
<>
{/* leading dot for single-row chips (month cells, all-day bars); a
time-grid block takes its color from the tinted surface instead, and
in its stacked layout a dot would sit alone on the first line */}
{!timedBlock && (
<span
aria-hidden
data-slot="event-calendar-event-dot"
// -me-0.5 tightens only the dot-to-title gap; the chip keeps gap-1.5
className="-me-0.5 size-1.5 shrink-0 rounded-full bg-(--ec-event-color)"
/>
)}
{occurrence.isRecurring && <RepeatIcon className="size-2.5 shrink-0 opacity-70" aria-hidden="true" />}
<span className={cn('font-medium', stackedBlock ? EVENT_CALENDAR_FADE_TRUNCATE : 'truncate')}>{event.title}</span>
{/* month cells are narrow: a compact never-shrinking start time keeps
the title readable; grids show the full range */}
{!occurrence.allDay &&
segment.isStart &&
(view === 'month' ? (
<span className="text-muted-foreground shrink-0">
{format(toZoned(occurrence.start, settings.timeZone), settings.i18n.formats.eventTime, {
locale: settings.locale,
})}
</span>
) : (
<span className={cn('text-muted-foreground hidden @[8rem]:inline', stackedBlock ? EVENT_CALENDAR_FADE_TRUNCATE : 'truncate')}>
{settings.i18n.functions.formatEventTime(
toZoned(occurrence.start, settings.timeZone),
toZoned(occurrence.end, settings.timeZone),
occurrence.allDay,
{ locale: settings.locale },
)}
</span>
))}
</>
);
// Per-day time text for a multi-day event: "From 9:00 AM", "All day",
// "Until 5:00 PM". Boundaries come from the occurrence vs segment.day, never
// the packing flags - lane merging rewrites those on shared segments.
const agendaTimeText = (() => {
if (view !== 'agenda') return '';
if (occurrence.allDay) return settings.i18n.labels.allDay;
const dayStart = zonedStartOfDay(segment.day, settings.timeZone);
const dayEnd = addDays(toZoned(dayStart, settings.timeZone), 1);
const startsBefore = occurrence.start < dayStart;
const endsAfter = occurrence.end > dayEnd;
if (startsBefore && endsAfter) return settings.i18n.labels.allDay;
if (endsAfter) {
return settings.i18n.labels.timeFrom(
format(toZoned(occurrence.start, settings.timeZone), settings.i18n.formats.eventTime, {
locale: settings.locale,
}),
);
}
if (startsBefore) {
return settings.i18n.labels.timeUntil(
format(toZoned(occurrence.end, settings.timeZone), settings.i18n.formats.eventTime, {
locale: settings.locale,
}),
);
}
return settings.i18n.functions.formatEventTime(toZoned(occurrence.start, settings.timeZone), toZoned(occurrence.end, settings.timeZone), false, {
locale: settings.locale,
});
})();
// Agenda default row: time column, color-dot badge, plain title
const agendaDefaultContent = (
<>
<span className="text-muted-foreground w-40 shrink-0 truncate tabular-nums">{agendaTimeText}</span>
<span aria-hidden data-slot="event-calendar-agenda-dot" className="size-2 shrink-0 rounded-full bg-(--ec-event-color)" />
<span className="truncate text-sm">{event.title}</span>
{occurrence.isRecurring && <RepeatIcon className="text-muted-foreground size-2.5 shrink-0" aria-hidden="true" />}
</>
);
// Memoized so a drag - which re-renders the lane on every pointer move -
// never re-invokes the consumer's renderEvent per frame: a referentially
// stable element lets React skip the custom subtree instead of flickering it.
// The render fns are deps, so an inline arrow from the consumer defeats it.
const customContent = useMemo(() => {
const renderProps = { occurrence, segment, view, isDragging, isSelected };
return view === 'agenda' ? viewConfig.renderAgendaEvent?.(renderProps) : viewConfig.renderEvent?.(renderProps);
}, [occurrence, segment, view, isDragging, isSelected, viewConfig.renderAgendaEvent, viewConfig.renderEvent]);
const content = children ?? customContent ?? (view === 'agenda' ? agendaDefaultContent : defaultContent);
const timeLabel = settings.i18n.functions.formatEventTime(
toZoned(occurrence.start, settings.timeZone),
toZoned(occurrence.end, settings.timeZone),
occurrence.allDay,
{ locale: settings.locale },
);
// native hover tooltip text; a formatter returning undefined drops the title
const label = settings.i18n.functions.formatEventLabel
? settings.i18n.functions.formatEventLabel(event.title, timeLabel)
: `${event.title}, ${timeLabel}`;
// Optional styled tooltip (viewConfig.eventTooltip, default off). It replaces
// the native title so the two never stack, and a preview never gets one. A
// falsy renderEventTooltip result (including the false/"" of `cond && <node>`)
// falls back to the label; an empty label leaves no content and skips it.
const tooltipOpts = typeof viewConfig.eventTooltip === 'object' ? viewConfig.eventTooltip : null;
const tooltipContent =
!preview && viewConfig.eventTooltip
? viewConfig.renderEventTooltip?.({
occurrence,
segment,
view,
label,
}) || label
: null;
const tooltipOn = Boolean(tooltipContent);
const showResize = interactive && resizeOn && !event.readOnly && event.resizable !== false;
// Hover grip pill (mirrors the gantt bars) marking the resize direction.
// Shown on compact sub-compactEventMinutes blocks too: the 1.5rem chip
// min-height leaves edge room without colliding with the centered title.
const grip = (
<span
aria-hidden
data-slot="event-calendar-resize-grip"
className={cn('bg-foreground/40 rounded-full', timedBlock ? 'h-0.5 w-2.5' : 'h-2.5 w-0.5', viewConfig.classNames?.resizeGrip)}
/>
);
const resizeHandles = showResize && (
<>
{timedBlock && segment.isStart && (
<span
data-slot="event-calendar-resize-handle"
data-edge="start"
className={cn(
'absolute inset-x-1 top-0 flex h-1.5 cursor-ns-resize items-center justify-center opacity-0 transition-opacity duration-150 group-hover/ec-event:opacity-100',
viewConfig.classNames?.resizeHandle,
)}
onPointerDown={(e) => gestures.beginResize(e, segment, 'start')}
>
{grip}
</span>
)}
{timedBlock && segment.isEnd && (
<span
data-slot="event-calendar-resize-handle"
data-edge="end"
className={cn(
'absolute inset-x-1 bottom-0 flex h-1.5 cursor-ns-resize items-center justify-center opacity-0 transition-opacity duration-150 group-hover/ec-event:opacity-100',
viewConfig.classNames?.resizeHandle,
)}
onPointerDown={(e) => gestures.beginResize(e, segment, 'end')}
>
{grip}
</span>
)}
{(horizontalBar || (isBar && inTimeGrid)) && segment.isStart && (
<span
data-slot="event-calendar-resize-handle"
data-edge="start"
className={cn(
'absolute inset-y-0 start-0 flex w-2 cursor-ew-resize items-center justify-center opacity-0 transition-opacity duration-150 group-hover/ec-event:opacity-100',
viewConfig.classNames?.resizeHandle,
)}
onPointerDown={(e) => gestures.beginResize(e, segment, 'start')}
>
{grip}
</span>
)}
{(horizontalBar || (isBar && inTimeGrid)) && segment.isEnd && (
<span
data-slot="event-calendar-resize-handle"
data-edge="end"
className={cn(
'absolute inset-y-0 end-0 flex w-2 cursor-ew-resize items-center justify-center opacity-0 transition-opacity duration-150 group-hover/ec-event:opacity-100',
viewConfig.classNames?.resizeHandle,
)}
onPointerDown={(e) => gestures.beginResize(e, segment, 'end')}
>
{grip}
</span>
)}
</>
);
const defaultProps = {
type: 'button' as const,
'data-slot': 'event-calendar-event',
'data-view': view,
'data-all-day': occurrence.allDay || undefined,
'data-recurring': occurrence.isRecurring || undefined,
'data-selected': isSelected || undefined,
'data-dragging': isDragging || undefined,
'data-preview': preview || undefined,
'data-past': occurrence.end.getTime() < Date.now() || undefined,
title: preview || tooltipOn ? undefined : label,
'aria-label':
settings.i18n.functions.formatEventAriaLabel?.(event.title, timeLabel, segment.continuesBefore || segment.continuesAfter) ??
`${event.title}, ${timeLabel}${segment.continuesBefore || segment.continuesAfter ? `, ${settings.i18n.labels.continues}` : ''}`,
// A background tint alone conveys selection, so the chip is a real toggle
// wherever it is interactive (agenda rows never select, previews are inert).
'aria-pressed': interactive ? isSelected : undefined,
'aria-hidden': preview || undefined,
tabIndex: preview ? -1 : undefined,
style: {
'--ec-event-color': event.color ?? 'var(--color-primary)',
} as CSSProperties,
onPointerDown: (e: React.PointerEvent) => {
e.stopPropagation();
// suppress the trailing slot-create click when this press yields no drag
markChipPress();
if (interactive) gestures.beginMove(e, segment);
},
onClick: (e: React.MouseEvent) => {
e.stopPropagation();
if (wasRecentDrag()) return;
// consumer first: e.preventDefault() opts out of built-in selection
settings.onEventClick?.(occurrence, e);
// the agenda is a read-only list: a click never selects/focuses a row
if (e.defaultPrevented || view === 'agenda') return;
instance.api.selectEvent(occurrence.key);
},
onDoubleClick: (e: React.MouseEvent) => {
e.stopPropagation();
settings.onEventDoubleClick?.(occurrence, e);
},
className: cn(
'group/ec-event text-foreground relative flex w-full min-w-0 cursor-pointer touch-none items-center overflow-hidden text-start select-none',
'focus-visible:ring-ring/50 outline-none focus-visible:ring-2',
preview && 'pointer-events-none',
view === 'agenda'
? // plain list row: color lives in the dot badge, not a tinted pill;
// hover AND selection surfaces are owned by the agenda row wrapper
'gap-3 rounded-md text-sm'
: cn(
// @container removes intrinsic sizing; only grid chips are containers
// py-1: room above/below inline badges (attendee pill etc.)
'@container gap-1.5 rounded-sm px-1.5 py-1 leading-normal',
// soft tint + inset ring, not an accent border: legible on both themes
'bg-(--ec-event-color)/15 hover:bg-(--ec-event-color)/25',
// a flat tint reads darker on a dark surface, so lift it there
'dark:bg-(--ec-event-color)/20 dark:hover:bg-(--ec-event-color)/30',
'inset-ring inset-ring-(--ec-event-color)/15',
'transition-[background-color,box-shadow] duration-150',
'data-dragging:opacity-40',
'data-selected:bg-(--ec-event-color)/30 data-selected:inset-ring-(--ec-event-color)/40',
segment.continuesBefore && 'rounded-s-none',
segment.continuesAfter && 'rounded-e-none',
),
viewConfig.classNames?.event,
className,
),
children: (
<>
{content}
{resizeHandles}
</>
),
};
const chip = useRender({
defaultTagName: 'button',
render,
props: mergeProps<'button'>(defaultProps, props),
});
return (
<EventCalendarChipContext.Provider value={{ occurrence, segment, isDragging, isSelected }}>
{tooltipOn ? (
<TooltipProvider delayDuration={tooltipOpts?.delay ?? 600}>
<Tooltip>
<TooltipTrigger asChild>{chip}</TooltipTrigger>
<TooltipContent side={tooltipOpts?.side ?? 'top'} className={viewConfig.classNames?.eventTooltip}>
{tooltipContent}
</TooltipContent>
</Tooltip>
</TooltipProvider>
) : (
chip
)}
</EventCalendarChipContext.Provider>
);
}
export {
EVENT_CALENDAR_COLORS,
EVENT_CALENDAR_FADE_TRUNCATE,
EVENT_CALENDAR_GHOST,
EVENT_CALENDAR_SLOT_DRAFT,
EventCalendarEvent,
useEventCalendarEventChip,
};
export type { EventCalendarChipContextValue, EventCalendarEventProps };import type { CalendarView, EventCalendarDateRange } from '@/registry/vcare/ui/event-calendar/event-calendar-types';
import { format, isSameMonth, isSameYear, subMilliseconds, type Locale } from 'date-fns';
interface EventCalendarI18nConfig {
labels: {
today: string;
previous: string;
next: string;
addEvent: string;
allDay: string;
more: (count: number) => string;
noEvents: string;
loading: string;
event: string;
events: (count: number) => string;
selectView: string;
week: (weekNumber: number) => string;
resources: string;
goToDate: string;
/** Cursor hint while a drag/resize hovers a rejected position. */
dropNotAllowed: string;
/** Aria-label suffix on chip segments that continue past the cell. */
continues: string;
/** Agenda label for the first day of a multi-day event. */
timeFrom: (time: string) => string;
/** Agenda label for the last day of a multi-day event. */
timeUntil: (time: string) => string;
/** View-switcher shortcut hint characters, per view. */
viewShortcuts: Record<CalendarView, string>;
/** Aria-label of the agenda day collapse/expand toggle. */
toggleDayEvents: (count: number, expanded: boolean) => string;
/** Aria-label of the agenda event details toggle. */
eventDetails: (title: string) => string;
/** Compact "+N" overflow (agenda summary dot stack). */
moreCompact: (count: number) => string;
/** Joins a bounded from-to time span. */
timeRange: (from: string, to: string) => string;
};
viewNames: {
month: string;
week: string;
day: string;
days: (count: number) => string;
agenda: string;
resource: string;
};
/** date-fns format strings, applied with the calendar `locale`. */
formats: {
monthTitle: string;
/** Undefined = smart cross-month range via functions.formatTitle. */
weekTitle?: string;
dayTitle: string;
/** Undefined = smart range label via functions.formatTitle. */
agendaTitle?: string;
monthDayHeader: string;
/** Narrow variant used by the month view below the compact breakpoint. */
monthDayHeaderNarrow: string;
timeGridDayHeader: string;
agendaDayHeader: string;
/** Agenda date-gutter day number. */
agendaDayNumber: string;
/** Agenda date-gutter weekday label. */
agendaWeekday: string;
/** "+N more" popover day header. */
moreDayHeader: string;
/** Month cell aria-label date. */
monthCellAriaLabel: string;
/** Time-grid day column aria-label date. */
dayAria: string;
/** Undefined = the resource view title falls back to dayTitle. */
resourceTitle?: string;
timeGutter: string;
/** Sub-hour gutter labels (interval below 60 minutes). */
timeGutterMinute: string;
eventTime: string;
monthCellDay: string;
};
functions: {
formatTitle: (
view: CalendarView,
ctx: {
date: Date;
activeRange: EventCalendarDateRange;
visibleRange: EventCalendarDateRange;
locale?: Locale;
},
) => string;
formatEventTime: (
start: Date,
end: Date,
allDay: boolean,
/** date-fns options (the calendar `locale`); trailing so a 3-arg override still fits. */
opts?: { locale?: Locale },
) => string;
formatDayRange: (range: EventCalendarDateRange, opts?: { locale?: Locale }) => string;
/** Chip native tooltip text; return undefined to drop the attribute. */
formatEventLabel?: (title: string, timeLabel: string) => string | undefined;
/** Chip aria-label composition. */
formatEventAriaLabel?: (title: string, timeLabel: string, continues: boolean) => string;
};
}
const DEFAULT_LABELS: EventCalendarI18nConfig['labels'] = {
today: 'Today',
previous: 'Previous',
next: 'Next',
addEvent: 'Add event',
allDay: 'All day',
more: (count) => `+${count} more`,
noEvents: 'No events',
loading: 'Loading events',
event: 'event',
events: (count) => (count === 1 ? '1 event' : `${count} events`),
selectView: 'Select view',
week: (weekNumber) => `W${weekNumber}`,
resources: 'Resources',
goToDate: 'Go to date',
dropNotAllowed: "Can't place here",
continues: 'continues',
timeFrom: (time) => `From ${time}`,
timeUntil: (time) => `Until ${time}`,
viewShortcuts: {
month: 'M',
week: 'W',
day: 'D',
days: '5',
agenda: 'A',
resource: 'G',
},
toggleDayEvents: (count) => (count === 1 ? '1 event' : `${count} events`),
eventDetails: (title) => title,
moreCompact: (count) => `+${count}`,
timeRange: (from, to) => `${from} - ${to}`,
};
const DEFAULT_VIEW_NAMES: EventCalendarI18nConfig['viewNames'] = {
month: 'Month',
week: 'Week',
day: 'Day',
days: (count) => (count === 1 ? '1 day' : `${count} days`),
agenda: 'Agenda',
resource: 'Time Grid',
};
const DEFAULT_FORMATS: EventCalendarI18nConfig['formats'] = {
monthTitle: 'MMMM yyyy',
weekTitle: undefined,
dayTitle: 'EEEE, MMMM d, yyyy',
agendaTitle: undefined,
monthDayHeader: 'EEE',
monthDayHeaderNarrow: 'EEEEE',
timeGridDayHeader: 'EEE d',
agendaDayHeader: 'EEEE, MMMM d',
agendaDayNumber: 'd',
agendaWeekday: 'EEE',
moreDayHeader: 'EEEE, MMMM d',
monthCellAriaLabel: 'PPPP',
dayAria: 'PPPP',
resourceTitle: undefined,
timeGutter: 'h a',
timeGutterMinute: 'h:mm a',
eventTime: 'h:mm a',
monthCellDay: 'd',
};
/**
* Default formatting functions BOUND to a config's labels/formats, so that
* `formats` overrides flow into the default renderers (a consumer overriding
* formats.monthTitle without replacing formatTitle still sees it applied).
*/
function makeDefaultFunctions(cfg: Pick<EventCalendarI18nConfig, 'labels' | 'formats'>): EventCalendarI18nConfig['functions'] {
return {
formatTitle: (view, { date, activeRange, locale }) => {
const opts = { locale };
if (view === 'month') {
return format(date, cfg.formats.monthTitle, opts);
}
if (view === 'resource') {
return format(date, cfg.formats.resourceTitle ?? cfg.formats.dayTitle, opts);
}
if (view === 'day') {
return format(date, cfg.formats.dayTitle, opts);
}
if (view === 'week' && cfg.formats.weekTitle) {
return format(date, cfg.formats.weekTitle, opts);
}
if (view === 'agenda' && cfg.formats.agendaTitle) {
return format(date, cfg.formats.agendaTitle, opts);
}
// week / days / agenda: smart range label, last day is activeRange.end - 1ms.
// subMilliseconds keeps the zoned date type (a plain new Date(ms)
// would flip the label to the machine zone near midnight)
const rangeEnd = subMilliseconds(activeRange.end, 1);
const start = activeRange.start;
if (isSameMonth(start, rangeEnd)) {
return `${format(start, 'MMMM d', opts)} - ${format(rangeEnd, 'd, yyyy', opts)}`;
}
if (isSameYear(start, rangeEnd)) {
return `${format(start, 'MMM d', opts)} - ${format(rangeEnd, 'MMM d, yyyy', opts)}`;
}
return `${format(start, 'MMM d, yyyy', opts)} - ${format(rangeEnd, 'MMM d, yyyy', opts)}`;
},
formatEventTime: (start, end, allDay, opts) => {
if (allDay) return cfg.labels.allDay;
const fmt = cfg.formats.eventTime;
// Multi-day timed events carry the date on both sides. Compare calendar
// days off the last rendered instant (end is exclusive, so a 14:00 to
// midnight event still ends on the start day). Elapsed ms would miss an
// exactly-24h event and a DST day that only runs 23 hours.
const lastInstant = end.getTime() - 1 >= start.getTime() ? subMilliseconds(end, 1) : start;
if (format(start, 'yyyy-MM-dd') !== format(lastInstant, 'yyyy-MM-dd')) {
return `${format(start, `MMM d, ${fmt}`, opts)} - ${format(end, `MMM d, ${fmt}`, opts)}`;
}
return `${format(start, fmt, opts)} - ${format(end, fmt, opts)}`;
},
formatDayRange: (range, opts) => {
// subMilliseconds keeps the zoned date type, same reason as formatTitle
const rangeEnd = subMilliseconds(range.end, 1);
return `${format(range.start, 'MMM d', opts)} - ${format(rangeEnd, 'MMM d', opts)}`;
},
};
}
const DEFAULT_EVENT_CALENDAR_I18N: EventCalendarI18nConfig = {
labels: DEFAULT_LABELS,
viewNames: DEFAULT_VIEW_NAMES,
formats: DEFAULT_FORMATS,
functions: makeDefaultFunctions({
labels: DEFAULT_LABELS,
formats: DEFAULT_FORMATS,
}),
};
/**
* One level deeper than `Partial`, because the merge below is per nested
* section: overriding a single label must not force a consumer to restate the
* other 22. Unknown keys are still rejected by the excess property check.
*/
type EventCalendarI18nOverrides = {
[K in keyof EventCalendarI18nConfig]?: Partial<EventCalendarI18nConfig[K]>;
};
/**
* Shallow merge per nested object, matching the filters.tsx i18n contract:
* a partial override replaces individual keys, never whole sections. Default
* functions are re-bound to the MERGED labels/formats; explicit `functions`
* overrides still win.
*/
function mergeEventCalendarI18n(overrides?: EventCalendarI18nOverrides): EventCalendarI18nConfig {
if (!overrides) return DEFAULT_EVENT_CALENDAR_I18N;
const labels = { ...DEFAULT_LABELS, ...overrides.labels };
const viewNames = { ...DEFAULT_VIEW_NAMES, ...overrides.viewNames };
const formats = { ...DEFAULT_FORMATS, ...overrides.formats };
return {
labels,
viewNames,
formats,
functions: {
...makeDefaultFunctions({ labels, formats }),
...overrides.functions,
},
};
}
export { DEFAULT_EVENT_CALENDAR_I18N, mergeEventCalendarI18n };
export type { EventCalendarI18nConfig, EventCalendarI18nOverrides };import { expandRecurrence } from '@/registry/vcare/ui/event-calendar/event-calendar-recurrence';
import type {
CalendarEvent,
CalendarView,
EventCalendarDateRange,
EventCalendarOccurrence,
EventCalendarOffDaysConfig,
EventCalendarResource,
EventCalendarSegment,
} from '@/registry/vcare/ui/event-calendar/event-calendar-types';
import { TZDate } from '@date-fns/tz';
import { addDays, addMonths, addWeeks, differenceInCalendarDays, differenceInMinutes, format, startOfDay, startOfMonth, startOfWeek } from 'date-fns';
type WeekStartsOn = 0 | 1 | 2 | 3 | 4 | 5 | 6;
/** Packing-effective minimum in minutes so tiny events do not stack invisibly. */
const MIN_PACK_SLOT = 30;
/** The instant re-expressed in the display time zone (TZDate extends Date). */
function toZoned(date: Date, timeZone: string): TZDate {
return new TZDate(date.getTime(), timeZone);
}
/** Zoned midnight of the day containing the instant. */
function zonedStartOfDay(date: Date, timeZone: string): TZDate {
return startOfDay(toZoned(date, timeZone));
}
/** Stable per-day key in the display time zone. */
function getDayKey(date: Date, timeZone: string): string {
return format(toZoned(date, timeZone), 'yyyy-MM-dd');
}
/** Day length in minutes; 1380/1500 on DST transition days - never assume 1440. */
function getDayTotalMinutes(dayStart: Date, timeZone: string): number {
const next = zonedStartOfDay(addDays(toZoned(dayStart, timeZone), 1), timeZone);
return differenceInMinutes(next, dayStart);
}
function snapMinutes(minutes: number, snap: number): number {
return Math.round(minutes / snap) * snap;
}
interface ViewRangeOptions {
timeZone: string;
weekStartsOn: WeekStartsOn;
dayCount: number;
agendaDayCount: number;
fixedWeeks: boolean;
}
interface ViewDateRanges {
visibleRange: EventCalendarDateRange;
activeRange: EventCalendarDateRange;
}
function getViewDateRange(view: CalendarView, date: Date, opts: ViewRangeOptions): ViewDateRanges {
const { timeZone, weekStartsOn, dayCount, agendaDayCount, fixedWeeks } = opts;
const zoned = toZoned(date, timeZone);
if (view === 'month') {
const activeStart = startOfMonth(zoned);
const activeEnd = startOfMonth(addMonths(zoned, 1));
const visibleStart = startOfWeek(activeStart, { weekStartsOn });
let visibleEnd: Date;
if (fixedWeeks) {
visibleEnd = addDays(visibleStart, 42);
} else {
visibleEnd = startOfWeek(addDays(activeEnd, -1), { weekStartsOn });
visibleEnd = addWeeks(visibleEnd, 1);
}
return {
activeRange: { start: activeStart, end: activeEnd },
visibleRange: { start: visibleStart, end: visibleEnd },
};
}
if (view === 'week') {
const start = startOfWeek(zoned, { weekStartsOn });
const range = { start, end: addWeeks(start, 1) };
return { activeRange: range, visibleRange: range };
}
if (view === 'day' || view === 'resource') {
const start = startOfDay(zoned);
const range = { start, end: addDays(start, 1) };
return { activeRange: range, visibleRange: range };
}
if (view === 'days') {
const start = startOfDay(zoned);
const range = { start, end: addDays(start, Math.max(1, dayCount)) };
return { activeRange: range, visibleRange: range };
}
// agenda
const start = startOfDay(zoned);
const range = { start, end: addDays(start, Math.max(1, agendaDayCount)) };
return { activeRange: range, visibleRange: range };
}
/** Day of month of the last day of the month containing the zoned date. */
function lastDayOfZonedMonth(date: Date): number {
return addDays(startOfMonth(addMonths(date, 1)), -1).getDate();
}
/** The anchor date stepped one period forward or backward for the view. */
function stepDate(view: CalendarView, date: Date, direction: 1 | -1, opts: Pick<ViewRangeOptions, 'timeZone' | 'dayCount' | 'agendaDayCount'>): Date {
const zoned = toZoned(date, opts.timeZone);
if (view === 'month') {
const stepped = addMonths(zoned, direction);
// addMonths clamps the day down into a shorter month and never restores
// it, so next-then-prev from the 31st would leave the anchor on the 28th.
// Sticking a month end to the target month's end keeps stepping
// invertible, which matters because the anchor is what day and week view
// open on after a month navigation.
if (zoned.getDate() !== lastDayOfZonedMonth(zoned)) return stepped;
return addDays(stepped, lastDayOfZonedMonth(stepped) - stepped.getDate());
}
if (view === 'week') return addWeeks(zoned, direction);
if (view === 'day' || view === 'resource') return addDays(zoned, direction);
if (view === 'days') return addDays(zoned, direction * Math.max(1, opts.dayCount));
return addDays(zoned, direction * Math.max(1, opts.agendaDayCount));
}
function rangesIntersect(a: EventCalendarDateRange, b: EventCalendarDateRange): boolean {
return a.start < b.end && a.end > b.start;
}
function eventsOverlap(a: { start: Date; end: Date }, b: { start: Date; end: Date }): boolean {
return a.start < b.end && a.end > b.start;
}
/**
* The one canonical multi-day segmentation. Splits an occurrence into per-day
* segments clamped to the range. Rules (unit-tested in M1): exclusive end - an
* event ending exactly at zoned midnight emits NO segment for that day;
* zero-duration events emit one min-height segment; allDay occurrences walk
* the same absolute instants as timed ones and only drop startMin/endMin, so
* their bounds have to already BE display-zone midnights (see
* CalendarEvent.allDay) or the bar paints on the wrong days.
*/
function segmentOccurrence<TData>(
occurrence: EventCalendarOccurrence<TData>,
range: EventCalendarDateRange,
timeZone: string,
): EventCalendarSegment<TData>[] {
const occStart = occurrence.start;
const occEnd = occurrence.end;
const isZeroLength = occEnd.getTime() === occStart.getTime();
const clampStart = occStart > range.start ? occStart : range.start;
const clampEnd = occEnd < range.end ? occEnd : range.end;
if (clampEnd < clampStart) return [];
if (clampEnd.getTime() === clampStart.getTime() && !isZeroLength) return [];
const segments: EventCalendarSegment<TData>[] = [];
let cursor = zonedStartOfDay(clampStart, timeZone);
while (cursor < clampEnd || (isZeroLength && segments.length === 0)) {
const next = zonedStartOfDay(addDays(toZoned(cursor, timeZone), 1), timeZone);
const segStart = clampStart > cursor ? clampStart : cursor;
const segEnd = clampEnd < next ? clampEnd : next;
const emptySeg = segEnd.getTime() <= segStart.getTime();
if (!emptySeg || isZeroLength) {
const isStart = segStart.getTime() === occStart.getTime();
const isEnd = segEnd.getTime() === occEnd.getTime();
segments.push({
occurrence,
day: cursor,
isStart,
isEnd,
continuesBefore: !isStart,
continuesAfter: !isEnd,
startMin: occurrence.allDay ? undefined : differenceInMinutes(segStart, cursor),
endMin: occurrence.allDay ? undefined : Math.max(differenceInMinutes(segEnd, cursor), differenceInMinutes(segStart, cursor)),
});
}
if (isZeroLength) break;
cursor = next;
}
return segments;
}
/** True when the occurrence should render as a bar (all-day row / month lanes). */
function isBarOccurrence(occurrence: EventCalendarOccurrence, timeZone?: string): boolean {
return occurrence.allDay || spansMultipleDays(occurrence, timeZone);
}
function spansMultipleDays(occ: { start: Date; end: Date }, timeZone?: string): boolean {
// An event ending exactly at the next midnight is still single-day
// (exclusive end), so compare against a strictly-later instant. The
// yardstick is the length of the day the event starts on, never a flat 24h:
// a fall-back day is 25h long, and a 00:00-to-00:00 shift on it is still one
// calendar day that belongs in the hour track, not in the all-day row.
// Without a display zone the dates answer in their own frame (TZDate) or in
// the host zone.
const dayStart = startOfDay(timeZone ? toZoned(occ.start, timeZone) : occ.start);
const nextDayStart = startOfDay(addDays(dayStart, 1));
return occ.end.getTime() - occ.start.getTime() > nextDayStart.getTime() - dayStart.getTime();
}
interface PackedPosition {
column: number;
columnCount: number;
columnSpan: number;
}
/**
* Google-style overlap packing for one day's timed segments.
* Mutates column/columnCount/columnSpan on the segments, in place.
* z resolution happens at render: event.zIndex verbatim, else 10 + column.
*/
function packTimedSegments<TData>(segments: EventCalendarSegment<TData>[]): void {
if (segments.length === 0) return;
type Working = {
seg: EventCalendarSegment<TData>;
startMin: number;
effEnd: number;
};
const items: Working[] = segments
.map((seg) => {
const startMin = seg.startMin ?? 0;
const endMin = seg.endMin ?? startMin;
return {
seg,
startMin,
effEnd: Math.max(endMin, startMin + MIN_PACK_SLOT),
};
})
.sort(
(a, b) =>
a.startMin - b.startMin || b.effEnd - b.startMin - (a.effEnd - a.startMin) || a.seg.occurrence.key.localeCompare(b.seg.occurrence.key),
);
// Sweep into connected clusters
const clusters: Working[][] = [];
let current: Working[] = [];
let clusterEnd = -Infinity;
for (const item of items) {
if (item.startMin >= clusterEnd) {
current = [];
clusters.push(current);
clusterEnd = -Infinity;
}
current.push(item);
clusterEnd = Math.max(clusterEnd, item.effEnd);
}
for (const cluster of clusters) {
// Greedy column assignment
const colEnds: number[] = [];
const byColumn = new Map<number, Working[]>();
for (const item of cluster) {
let col = colEnds.findIndex((end) => end <= item.startMin);
if (col === -1) {
col = colEnds.length;
colEnds.push(0);
}
colEnds[col] = item.effEnd;
item.seg.column = col;
const bucket = byColumn.get(col) ?? [];
bucket.push(item);
byColumn.set(col, bucket);
}
const columnCount = colEnds.length;
// Partial-overlap expansion: widen rightward into free columns
for (const item of cluster) {
let span = 1;
const col = item.seg.column ?? 0;
while (col + span < columnCount) {
const occupants = byColumn.get(col + span) ?? [];
const blocked = occupants.some((o) => o.startMin < item.effEnd && o.effEnd > item.startMin);
if (blocked) break;
span++;
}
item.seg.columnCount = columnCount;
item.seg.columnSpan = span;
}
}
}
/**
* Greedy lane packing for bar segments within one week row (7 columns).
* Mutates lane/rowIndex/colStart/colSpan on the segments, in place.
*/
/**
* Build the laned month-row bars for one week: consecutive-day segments of
* the same occurrence merge into ONE bar (colStart -> colSpan) stacked into
* lanes. Returns NEW segment objects - the shared per-day segments (also
* rendered by the all-day rows and day cells) must stay pristine: mutating
* their isEnd/continues flags gave the first-day chip a whole-bar shape and
* a bogus end resize handle in the week all-day row, where dragging it
* collapsed the event to a single day.
*/
function packWeekRowLanes<TData>(
segments: EventCalendarSegment<TData>[],
rowIndex: number,
rowStart: Date,
timeZone: string,
): EventCalendarSegment<TData>[] {
type Bar = {
seg: EventCalendarSegment<TData>;
colStart: number;
colSpan: number;
isStart: boolean;
isEnd: boolean;
lane: number;
};
const bars: Bar[] = segments.map((seg) => {
const dayIndex = Math.round(
(zonedStartOfDay(seg.day, timeZone).getTime() - zonedStartOfDay(rowStart, timeZone).getTime()) / (24 * 60 * 60 * 1000),
);
return {
seg,
colStart: Math.max(0, Math.min(6, dayIndex)),
colSpan: 1,
isStart: seg.isStart,
isEnd: seg.isEnd,
lane: 0,
};
});
// Merge consecutive-day segments of the same occurrence into one bar per row
const merged = new Map<string, Bar>();
for (const bar of bars) {
const key = bar.seg.occurrence.key;
const existing = merged.get(key);
if (existing) {
const start = Math.min(existing.colStart, bar.colStart);
const end = Math.max(existing.colStart + existing.colSpan, bar.colStart + bar.colSpan);
existing.colStart = start;
existing.colSpan = end - start;
existing.isStart = existing.isStart || bar.isStart;
existing.isEnd = existing.isEnd || bar.isEnd;
} else {
merged.set(key, bar);
}
}
const rowBars = Array.from(merged.values()).sort(
(a, b) => a.colStart - b.colStart || b.colSpan - a.colSpan || a.seg.occurrence.key.localeCompare(b.seg.occurrence.key),
);
const lanes: boolean[][] = [];
for (const bar of rowBars) {
let lane = 0;
for (;;) {
lanes[lane] ??= new Array(7).fill(false);
const row = lanes[lane];
let free = true;
for (let c = bar.colStart; c < bar.colStart + bar.colSpan; c++) {
if (row[c]) {
free = false;
break;
}
}
if (free) break;
lane++;
}
for (let c = bar.colStart; c < bar.colStart + bar.colSpan; c++) {
lanes[lane][c] = true;
}
bar.lane = lane;
}
return rowBars.map((bar) => ({
...bar.seg,
isStart: bar.isStart,
isEnd: bar.isEnd,
continuesBefore: !bar.isStart,
continuesAfter: !bar.isEnd,
lane: bar.lane,
rowIndex,
colStart: bar.colStart,
colSpan: bar.colSpan,
}));
}
interface EventCalendarDayBucket<TData = unknown> {
allDay: EventCalendarSegment<TData>[];
timed: EventCalendarSegment<TData>[];
}
interface EventCalendarWeekRow<TData = unknown> {
rowIndex: number;
rowStart: Date;
/** Laned bar segments (one per occurrence per row). */
bars: EventCalendarSegment<TData>[];
}
interface EventCalendarIndex<TData = unknown> {
occurrences: EventCalendarOccurrence<TData>[];
byDay: Map<string, EventCalendarDayBucket<TData>>;
weekRows: EventCalendarWeekRow<TData>[];
}
interface BuildIndexOptions<TData> {
timeZone: string;
weekStartsOn: WeekStartsOn;
eventOrder?: (a: EventCalendarOccurrence<TData>, b: EventCalendarOccurrence<TData>) => number;
getOccurrences?: (
event: CalendarEvent<TData>,
range: EventCalendarDateRange,
ctx: { timeZone: string },
) => Array<{ start: Date; end: Date }> | null;
}
function defaultEventOrder(a: EventCalendarOccurrence, b: EventCalendarOccurrence): number {
return (
a.start.getTime() - b.start.getTime() || b.end.getTime() - b.start.getTime() - (a.end.getTime() - a.start.getTime()) || a.key.localeCompare(b.key)
);
}
function buildEventIndex<TData>(
events: CalendarEvent<TData>[],
visibleRange: EventCalendarDateRange,
opts: BuildIndexOptions<TData>,
): EventCalendarIndex<TData> {
const { timeZone, weekStartsOn } = opts;
const order = opts.eventOrder ?? defaultEventOrder;
// RECURRENCE-ID override replacement: an event carrying recurringEventId +
// originalStart is an edited single occurrence of that series. The parent's
// expansion drops the replaced instant; the override renders as its own
// occurrence through the normal path below.
const overrideTimes = new Map<string, Set<number>>();
for (const event of events) {
if (!event.recurringEventId || !event.originalStart) continue;
let times = overrideTimes.get(event.recurringEventId);
if (!times) overrideTimes.set(event.recurringEventId, (times = new Set()));
times.add(event.originalStart.getTime());
}
const occurrences: EventCalendarOccurrence<TData>[] = [];
for (const event of events) {
const replaced = overrideTimes.get(event.id);
const custom = opts.getOccurrences?.(event, visibleRange, { timeZone });
if (custom) {
custom.forEach((occ, i) => {
if (replaced?.has(occ.start.getTime())) return;
if (!rangesIntersect({ start: occ.start, end: occ.end }, visibleRange)) return;
occurrences.push({
key: `${event.id}::${occ.start.toISOString()}`,
eventId: event.id,
event,
start: occ.start,
end: occ.end,
allDay: event.allDay ?? false,
isRecurring: true,
recurrenceIndex: i,
});
});
continue;
}
const expanded = expandRecurrence(event, visibleRange, { timeZone });
occurrences.push(...(replaced ? expanded.filter((occ) => !replaced.has(occ.start.getTime())) : expanded));
}
occurrences.sort(order);
const byDay = new Map<string, EventCalendarDayBucket<TData>>();
const barSegmentsByRow = new Map<number, EventCalendarSegment<TData>[]>();
const firstRowStart = startOfWeek(toZoned(visibleRange.start, timeZone), {
weekStartsOn,
});
for (const occurrence of occurrences) {
const segments = segmentOccurrence(occurrence, visibleRange, timeZone);
const bar = isBarOccurrence(occurrence, timeZone);
for (const seg of segments) {
const key = getDayKey(seg.day, timeZone);
let bucket = byDay.get(key);
if (!bucket) {
bucket = { allDay: [], timed: [] };
byDay.set(key, bucket);
}
if (bar) {
bucket.allDay.push(seg);
// calendar-day math, not a fixed 168h divisor: DST transition weeks
// are 167/169h long and the fixed divisor mis-buckets every later
// Sunday one row early (which then clamps into the wrong column)
const rowIndex = Math.floor(differenceInCalendarDays(toZoned(seg.day, timeZone), firstRowStart) / 7);
const rowBucket = barSegmentsByRow.get(rowIndex) ?? [];
rowBucket.push(seg);
barSegmentsByRow.set(rowIndex, rowBucket);
} else {
bucket.timed.push(seg);
}
}
}
for (const bucket of byDay.values()) {
packTimedSegments(bucket.timed);
}
const weekRows: EventCalendarWeekRow<TData>[] = [];
for (const [rowIndex, segs] of barSegmentsByRow) {
const rowStart = addWeeks(firstRowStart, rowIndex);
weekRows.push({
rowIndex,
rowStart,
bars: packWeekRowLanes(segs, rowIndex, rowStart, timeZone),
});
}
weekRows.sort((a, b) => a.rowIndex - b.rowIndex);
return { occurrences, byDay, weekRows };
}
/** Cache key for index memoization; cheap string compare. */
function getRangeKey(range: EventCalendarDateRange): string {
return `${range.start.getTime()}-${range.end.getTime()}`;
}
/** Depth-first flatten of the resource tree (parents included). */
function flattenResources(resources: EventCalendarResource[], depth = 0): Array<{ resource: EventCalendarResource; depth: number }> {
const rows: Array<{ resource: EventCalendarResource; depth: number }> = [];
for (const resource of resources) {
rows.push({ resource, depth });
if (resource.children?.length) {
rows.push(...flattenResources(resource.children, depth + 1));
}
}
return rows;
}
const DEFAULT_WEEKEND_DAYS = [0, 6];
/**
* Resolves whether a day is an off day (non-working) in the display zone.
* Callers pass the calendar's own weekendDays so the shading cannot contradict
* the weekend the rest of the calendar renders; an explicit offDays.weekendDays
* still wins over it.
*/
function resolveOffDay(
day: Date,
timeZone: string,
config: boolean | EventCalendarOffDaysConfig | undefined,
defaultWeekendDays?: number[],
): boolean {
if (!config) return false;
const resolved: EventCalendarOffDaysConfig = config === true ? {} : config;
const weekendDays = resolved.weekendDays ?? defaultWeekendDays ?? DEFAULT_WEEKEND_DAYS;
const zoned = toZoned(day, timeZone);
if (weekendDays.includes(zoned.getDay())) return true;
if (resolved.dates?.length) {
const key = getDayKey(day, timeZone);
if (resolved.dates.some((date) => getDayKey(date, timeZone) === key)) {
return true;
}
}
return resolved.isOffDay?.(day) ?? false;
}
export {
buildEventIndex,
defaultEventOrder,
eventsOverlap,
flattenResources,
getDayKey,
getDayTotalMinutes,
getRangeKey,
getViewDateRange,
isBarOccurrence,
MIN_PACK_SLOT,
packTimedSegments,
packWeekRowLanes,
rangesIntersect,
resolveOffDay,
segmentOccurrence,
snapMinutes,
spansMultipleDays,
stepDate,
toZoned,
zonedStartOfDay,
};
export type { BuildIndexOptions, EventCalendarDayBucket, EventCalendarIndex, EventCalendarWeekRow, ViewDateRanges, ViewRangeOptions, WeekStartsOn };import { useCallback, useEffect, useId, useLayoutEffect, useMemo, useRef, useState, type CSSProperties, type Ref } from 'react';
import {
EventCalendarViewContext,
useEventCalendar,
useEventCalendarDay,
useEventCalendarSelector,
useEventCalendarSettings,
useEventCalendarViewConfig,
useEventCalendarViewSettings,
useEventCalendarWeek,
} from '@/registry/vcare/ui/event-calendar/event-calendar';
import { useEventCalendarGestures, wasRecentChipPress, wasRecentDrag } from '@/registry/vcare/ui/event-calendar/event-calendar-dnd';
import { EVENT_CALENDAR_GHOST, EVENT_CALENDAR_SLOT_DRAFT, EventCalendarEvent } from '@/registry/vcare/ui/event-calendar/event-calendar-event';
import { getDayKey, getRangeKey, resolveOffDay, toZoned, zonedStartOfDay } from '@/registry/vcare/ui/event-calendar/event-calendar-lib';
import type {
EventCalendarDateRange,
EventCalendarDragState,
EventCalendarEventId,
EventCalendarSegment,
} from '@/registry/vcare/ui/event-calendar/event-calendar-types';
import { mergeProps } from '@base-ui/react/merge-props';
import { useRender } from '@base-ui/react/use-render';
import { addDays, format, getWeek } from 'date-fns';
import { cn } from '@/registry/vcare/lib/utils';
import { Popover, PopoverContent, PopoverTrigger } from '@/registry/vcare/ui/popover';
import { ScrollArea } from '@/registry/vcare/ui/scroll-area';
import { PlusIcon } from 'lucide-react';
// Layout-effect on the client (measure before paint, no flash), plain effect on
// the server (never runs there) to avoid the SSR useLayoutEffect warning.
const useIsoLayoutEffect = typeof window !== 'undefined' ? useLayoutEffect : useEffect;
// An occurrence key encodes the start instant and is also the chip's React key,
// so committing a move re-keys the chip: React remounts it and the browser
// drops focus to <body>. The chip that owns focus is recorded here so the cell
// rendering its replacement can hand focus back. Module scope because the drop
// can land in a different cell than the one the chip left, and only one element
// holds focus at a time anyway.
let focusedChip: {
node: HTMLElement;
eventId: EventCalendarEventId;
recurrenceIndex?: number;
} | null = null;
/** Give focus back to the recorded chip's replacement, if `root` renders it. */
function restoreChipFocus(root: HTMLElement | null, segments: EventCalendarSegment[]) {
const pending = focusedChip;
// Only a chip removed WHILE focused needs help: a node still in the tree, or
// a focus that has already moved on by itself, is left alone.
if (!root || !pending || pending.node.isConnected) return;
const active = document.activeElement;
if (active && active !== document.body) return;
const index = segments.findIndex(
(segment) => segment.occurrence.eventId === pending.eventId && segment.occurrence.recurrenceIndex === pending.recurrenceIndex,
);
if (index < 0) return;
const chip = root.querySelectorAll<HTMLElement>('[data-slot=event-calendar-event]')[index];
if (!chip) return;
// cleared first: focus() re-records through the new chip's own onFocus
focusedChip = null;
chip.focus();
}
interface EventCalendarMonthViewProps extends useRender.ComponentProps<'div'> {
maxEventsPerCell?: number | 'auto';
}
function EventCalendarMonthView({ className, render, maxEventsPerCell, ...props }: EventCalendarMonthViewProps) {
const instance = useEventCalendar();
const settings = useEventCalendarSettings();
const viewConfig = useEventCalendarViewConfig();
const visibleRange = useEventCalendarSelector<unknown, EventCalendarDateRange>((state) => state.visibleRange, {
isEqual: (a, b) => getRangeKey(a) === getRangeKey(b),
});
const anchorDate = useEventCalendarSelector((state) => state.date);
const { effective } = useEventCalendarViewSettings();
const weeks = useMemo(() => {
const days: Date[] = [];
let cursor = zonedStartOfDay(visibleRange.start, settings.timeZone);
while (cursor < visibleRange.end) {
days.push(cursor);
cursor = zonedStartOfDay(addDays(toZoned(cursor, settings.timeZone), 1), settings.timeZone);
}
const rows: Date[][] = [];
for (let i = 0; i < days.length; i += 7) rows.push(days.slice(i, i + 7));
if (effective.weekends) return rows;
return rows.map((row) => row.filter((day) => !settings.weekendDays.includes(toZoned(day, settings.timeZone).getDay())));
}, [visibleRange, settings.timeZone, settings.weekendDays, effective.weekends]);
const headerDays = weeks[0] ?? [];
const title = settings.i18n.functions.formatTitle('month', {
date: toZoned(anchorDate, settings.timeZone),
activeRange: instance.api.getActiveRange(),
visibleRange,
locale: settings.locale,
});
const gridTemplateColumns = `${effective.weekNumbers ? 'var(--ec-week-number-w, 2.75rem) ' : ''}repeat(${headerDays.length}, minmax(0, 1fr))`;
const cap = maxEventsPerCell ?? viewConfig.maxEventsPerCell;
const contained = viewConfig.scrollMode !== 'page';
// "auto" fits as many event rows as the cell height allows and rolls the rest
// into "+N more". Only the contained mode gives a cell a bounded height to
// measure; page mode grows to fit, so "auto" there keeps the fixed fallback.
const autoFit = cap === 'auto' && contained;
// slotProbe resolves the event-row height (--ec-month-bar-h) to px, honoring
// the current font size and any consumer override; contentProbe is the first
// cell's flex-1 content area, whose height is the event space per cell.
const slotProbeRef = useRef<HTMLDivElement | null>(null);
const contentProbeRef = useRef<HTMLDivElement | null>(null);
const [autoCap, setAutoCap] = useState<number | null>(null);
const measureCap = useCallback(() => {
const content = contentProbeRef.current;
const slot = slotProbeRef.current;
if (!content || !slot) return;
const laneH = slot.getBoundingClientRect().height;
if (laneH <= 0) return;
const cs = getComputedStyle(content);
const inner = content.clientHeight - (parseFloat(cs.paddingTop) || 0);
const gap = parseFloat(cs.rowGap) || 0;
// N rows occupy N*laneH - gap (the last row has no trailing gap)
setAutoCap(Math.max(1, Math.floor((inner + gap) / laneH)));
}, []);
useIsoLayoutEffect(() => {
if (!autoFit) {
setAutoCap(null);
return;
}
const content = contentProbeRef.current;
if (!content || typeof ResizeObserver === 'undefined') return;
measureCap();
const observer = new ResizeObserver(measureCap);
observer.observe(content);
return () => observer.disconnect();
// re-observe the first cell after a re-layout (row count or month change)
}, [autoFit, measureCap, weeks.length, anchorDate]);
const resolvedCap = cap === 'auto' ? (autoFit ? (autoCap ?? 3) : 3) : cap;
const defaultProps = {
'data-slot': 'event-calendar-month-view',
'data-view': 'month',
role: 'grid',
'aria-label': title,
className: cn('flex flex-col border-t', contained && 'min-h-0 flex-1 overflow-hidden', viewConfig.classNames?.monthView, className),
children: (
<>
<div
role="row"
data-slot="event-calendar-month-header"
// @container scopes the narrow-label breakpoint to the header row
className={cn('@container grid border-b', viewConfig.classNames?.monthHeader)}
style={{ gridTemplateColumns }}
>
{effective.weekNumbers && <div role="columnheader" aria-hidden className={cn('border-e px-2 py-1.5', viewConfig.classNames?.weekNumber)} />}
{headerDays.map((day) => (
<div
key={day.getTime()}
role="columnheader"
className={cn('text-muted-foreground truncate px-2 py-1.5 font-medium', viewConfig.classNames?.monthDayHeader)}
>
{viewConfig.renderDayHeader?.({
day,
view: 'month',
isToday: getDayKey(day, settings.timeZone) === getDayKey(new Date(), settings.timeZone),
}) ?? (
<>
<span className="@max-[36rem]:hidden">
{format(toZoned(day, settings.timeZone), settings.i18n.formats.monthDayHeader, {
locale: settings.locale,
})}
</span>
<span className="hidden @max-[36rem]:inline">
{format(toZoned(day, settings.timeZone), settings.i18n.formats.monthDayHeaderNarrow, {
locale: settings.locale,
})}
</span>
</>
)}
</div>
))}
</div>
<div
data-slot="event-calendar-month-body"
className={cn('grid', contained && 'min-h-0 flex-1', viewConfig.classNames?.monthBody)}
style={{
gridTemplateRows: contained
? `repeat(${weeks.length}, minmax(0, 1fr))`
: `repeat(${weeks.length}, minmax(var(--ec-month-row-min-h, 8rem), auto))`,
}}
>
{weeks.map((week, rowIndex) => (
<EventCalendarMonthWeek
key={rowIndex}
week={week}
gridTemplateColumns={gridTemplateColumns}
showWeekNumber={effective.weekNumbers}
cap={resolvedCap}
autoFit={autoFit}
contentRef={rowIndex === 0 ? contentProbeRef : undefined}
/>
))}
</div>
{autoFit && <div ref={slotProbeRef} aria-hidden className="pointer-events-none invisible absolute h-[var(--ec-month-bar-h,1.75rem)] w-0" />}
</>
),
};
return (
<EventCalendarViewContext.Provider value={{ view: 'month' }}>
{useRender({
defaultTagName: 'div',
render,
props: mergeProps<'div'>(defaultProps, props),
})}
</EventCalendarViewContext.Provider>
);
}
/**
* One month week row. Multi-day / all-day events render as CONTINUOUS bars in
* an overlay grid that spans day columns (colStart -> colSpan) and stacks by
* lane; single-day timed events render inside each cell below the reserved bar
* lanes. This is what makes a cross-day event read as one whole block instead
* of a chip repeated per cell.
*/
function EventCalendarMonthWeek({
week,
gridTemplateColumns,
showWeekNumber,
cap,
autoFit,
contentRef,
}: {
week: Date[];
gridTemplateColumns: string;
showWeekNumber: boolean;
cap: number;
autoFit: boolean;
/** Set on the first week only: forwarded to its first cell's content area so
* the view can measure the per-cell event height for "auto". */
contentRef?: Ref<HTMLDivElement>;
}) {
const settings = useEventCalendarSettings();
const viewConfig = useEventCalendarViewConfig();
const { bars, rowStart } = useEventCalendarWeek(week[0]);
const colOffset = showWeekNumber ? 1 : 0;
const dayMs = 86400000;
const rowStartMs = zonedStartOfDay(rowStart ?? week[0], settings.timeZone).getTime();
// Day offsets from the TRUE row start (0-6) for each visible column, so a
// weekends-hidden month still places bars on the right days.
const offsets = week.map((d) => Math.round((zonedStartOfDay(d, settings.timeZone).getTime() - rowStartMs) / dayMs));
/** Clamp a day-offset span onto the visible columns; null = fully hidden. */
const gridPos = (colStart: number, colSpan: number) => {
let start = -1;
let end = -1;
for (let o = colStart; o < colStart + colSpan; o++) {
const col = offsets.indexOf(o);
if (col === -1) continue;
if (start === -1) start = col;
end = col;
}
return start === -1 ? null : { col: start, span: end - start + 1 };
};
// bars fit within the cap; deeper lanes fall into each day's "+N more"
const visibleBars = bars.filter((b) => (b.lane ?? 0) < cap);
const covers = (b: EventCalendarSegment, dayOffset: number) => (b.colStart ?? 0) <= dayOffset && dayOffset < (b.colStart ?? 0) + (b.colSpan ?? 1);
// Occurrence keys of the bars hidden in each column (lane >= cap). Threaded to
// the cell so its "+N more" popover can list the hidden bars WITHOUT re-listing
// the visible ones (day buckets carry no lane, so the week row - which owns bar
// laning - is the only place that knows which bars are hidden).
const hiddenBarKeysByCol = week.map(
(_, col) => new Set(bars.filter((b) => (b.lane ?? 0) >= cap && covers(b, offsets[col])).map((b) => b.occurrence.key)),
);
// Live move/resize ghost at the PROPOSED day span. Standardized treatment
// (EVENT_CALENDAR_GHOST): move = the event carried as a full clone, resize =
// the same clone with a dashed boundary; invalid adds destructive marking
// while the engine shows the not-allowed cursor + validation hint.
const dragGhost = useEventCalendarSelector<
unknown,
| (Pick<EventCalendarDragState, 'kind' | 'valid' | 'occurrence' | 'proposedStart' | 'proposedEnd' | 'proposedAllDay'> & {
colStart: number;
colSpan: number;
isStart: boolean;
isEnd: boolean;
color?: string;
})
| null
>(
(state) => {
const drag = state.drag;
if (!drag) return null;
const rowEndMs = rowStartMs + 7 * dayMs;
const startDayMs = zonedStartOfDay(drag.proposedStart, settings.timeZone).getTime();
// exclusive end -> the last covered day
const lastDayMs = zonedStartOfDay(new Date(drag.proposedEnd.getTime() - 1), settings.timeZone).getTime();
if (startDayMs >= rowEndMs || lastDayMs < rowStartMs) return null;
const startCol = Math.max(0, Math.round((startDayMs - rowStartMs) / dayMs));
const endCol = Math.min(6, Math.round((lastDayMs - rowStartMs) / dayMs));
if (endCol < startCol) return null;
return {
kind: drag.kind,
valid: drag.valid,
occurrence: drag.occurrence,
proposedStart: drag.proposedStart,
proposedEnd: drag.proposedEnd,
proposedAllDay: drag.proposedAllDay,
colStart: startCol,
colSpan: endCol - startCol + 1,
isStart: startDayMs >= rowStartMs,
isEnd: lastDayMs < rowEndMs,
color: drag.occurrence.event.color,
};
},
{
isEqual: (a, b) =>
a === b ||
(a !== null &&
b !== null &&
a.colStart === b.colStart &&
a.colSpan === b.colSpan &&
a.valid === b.valid &&
a.kind === b.kind &&
a.proposedAllDay === b.proposedAllDay &&
a.proposedStart.getTime() === b.proposedStart.getTime() &&
a.proposedEnd.getTime() === b.proposedEnd.getTime()),
},
);
const ghostPos = dragGhost ? gridPos(dragGhost.colStart, dragGhost.colSpan) : null;
const ghostLane = dragGhost ? (bars.find((b) => b.occurrence.key === dragGhost.occurrence.key)?.lane ?? 0) : 0;
// A single-day timed MOVE is indicated INLINE in the target cell (a
// placeholder at the time-sorted position, rendered by EventCalendarMonthCell)
// rather than as a bar in this overlay, so only bar drags and every resize
// render the overlay ghost. Bars = all-day or multi-day (span > 1 day).
const ghostIsBar =
!!dragGhost &&
(dragGhost.kind !== 'move' || dragGhost.proposedAllDay || dragGhost.proposedEnd.getTime() - dragGhost.proposedStart.getTime() > dayMs);
return (
<div
role="row"
data-slot="event-calendar-month-row"
className={cn('relative grid min-h-0 border-b last:border-b-0', viewConfig.classNames?.monthRow)}
style={{ gridTemplateColumns }}
>
{showWeekNumber && (
<div
role="rowheader"
data-slot="event-calendar-week-number"
className={cn('text-muted-foreground border-e px-2 pt-1 tabular-nums', viewConfig.classNames?.weekNumber)}
>
{settings.i18n.labels.week(
getWeek(toZoned(week[0], settings.timeZone), {
// locale supplies firstWeekContainsDate, so a de/ISO calendar
// numbers the year-boundary weeks its own way instead of falling
// back to US numbering; weekStartsOn stays explicit so the number
// keeps matching the rendered grid
locale: settings.locale,
weekStartsOn: settings.weekStartsOn,
}),
)}
</div>
)}
{week.map((day, col) => (
<EventCalendarMonthCell
key={day.getTime()}
day={day}
cap={cap}
// Reserve lane space only for bars that pass through THIS cell, so a
// short multi-day event does not push down timed events in unrelated
// cells of the same row. Reserve down to the deepest covering bar
// lane so timed events always sit below every bar in their own cell.
reservedLanes={visibleBars.reduce((max, b) => (covers(b, offsets[col]) ? Math.max(max, (b.lane ?? 0) + 1) : max), 0)}
hiddenBarKeys={hiddenBarKeysByCol[col]}
isLast={col === week.length - 1}
autoFit={autoFit}
contentRef={col === 0 ? contentRef : undefined}
/>
))}
{/* Continuous bar overlay: one element per bar, placed by grid-column so
a cross-day span is a single unbroken block. pointer-events pass
through the gaps to the cells below. NOT aria-hidden - these are the
real interactive bars. */}
{(visibleBars.length > 0 || (dragGhost && ghostPos && ghostIsBar)) && (
<div
data-slot="event-calendar-month-bar-overlay"
className={cn('pointer-events-none absolute inset-x-0 top-0 z-10 grid pt-1.5', viewConfig.classNames?.monthBarOverlay)}
style={{
gridTemplateColumns,
gridAutoRows: 'var(--ec-month-bar-h, 1.75rem)',
}}
>
{visibleBars.map((bar) => {
const pos = gridPos(bar.colStart ?? 0, bar.colSpan ?? 1);
if (!pos) return null;
return (
<div
key={bar.occurrence.key}
className={cn('pointer-events-auto min-w-0 px-1', viewConfig.classNames?.monthBar)}
style={{
gridColumn: `${colOffset + pos.col + 1} / span ${pos.span}`,
gridRow: (bar.lane ?? 0) + 1,
}}
>
{/* lane height minus the 2px inter-lane gap */}
<EventCalendarEvent segment={bar} className="h-[calc(var(--ec-month-bar-h,1.75rem)-0.125rem)]" />
</div>
);
})}
{dragGhost && ghostPos && ghostIsBar && (
<div
aria-hidden
className={cn('min-w-0 px-1', viewConfig.classNames?.monthBar)}
style={{
gridColumn: `${colOffset + ghostPos.col + 1} / span ${ghostPos.span}`,
gridRow: ghostLane + 1,
}}
>
<div
data-slot="event-calendar-drag-ghost"
data-kind={dragGhost.kind}
data-drop-invalid={!dragGhost.valid || undefined}
className={cn(
'h-[calc(var(--ec-month-bar-h,1.75rem)-0.125rem)]',
dragGhost.kind === 'move'
? // faint drop placeholder only: the cursor-attached
// carry clone owns the visual during moves
cn(EVENT_CALENDAR_GHOST.move, !dragGhost.valid && EVENT_CALENDAR_GHOST.invalid)
: cn(EVENT_CALENDAR_GHOST.resize, !dragGhost.valid && EVENT_CALENDAR_GHOST.invalidResize),
viewConfig.classNames?.dragGhost,
)}
style={
{
'--ec-event-color': dragGhost.color ?? 'var(--color-primary)',
} as CSSProperties
}
>
{dragGhost.kind !== 'move' && (
<EventCalendarEvent
preview
segment={{
occurrence: {
...dragGhost.occurrence,
start: dragGhost.proposedStart,
end: dragGhost.proposedEnd,
},
day: week[ghostPos.col] ?? week[0],
isStart: dragGhost.isStart,
isEnd: dragGhost.isEnd,
continuesBefore: !dragGhost.isStart,
continuesAfter: !dragGhost.isEnd,
}}
className={cn('h-full inset-ring-0', !dragGhost.valid && EVENT_CALENDAR_GHOST.invalidContent)}
/>
)}
</div>
</div>
)}
</div>
)}
</div>
);
}
function EventCalendarMonthCell({
day,
cap,
reservedLanes,
hiddenBarKeys,
isLast,
autoFit,
contentRef,
}: {
day: Date;
cap: number;
reservedLanes: number;
/** Occurrence keys of the bars hidden in THIS column (lane >= cap), from the
* week row. Lets the cell list hidden bars in its overflow popover without
* re-listing the bars already visible in the row overlay. */
hiddenBarKeys: Set<string>;
/** Last column in the row - drops the right border so the grid's outer edge
* is owned by the container, not a doubled cell border. Passed explicitly
* because the bar overlay renders after the cells, so `:last-child` is
* unreliable on rows that have bars. */
isLast: boolean;
/** When true, the "+N more" chip is treated as taking a row so the visible
* chips + indicator always fit the measured cell height. */
autoFit: boolean;
/** Set on the first cell only: measured to derive the "auto" cap. */
contentRef?: Ref<HTMLDivElement>;
}) {
const instance = useEventCalendar();
const settings = useEventCalendarSettings();
const viewConfig = useEventCalendarViewConfig();
const gestures = useEventCalendarGestures();
const { segments, isToday, isOutside } = useEventCalendarDay(day);
const dayStart = zonedStartOfDay(day, settings.timeZone);
const dayEnd = addDays(toZoned(dayStart, settings.timeZone), 1);
const { effective } = useEventCalendarViewSettings();
const isOff = resolveOffDay(
day,
settings.timeZone,
effective.offDays ? (typeof viewConfig.offDays === 'object' ? viewConfig.offDays : true) : false,
settings.weekendDays,
);
const offClassName = (typeof viewConfig.offDays === 'object' && viewConfig.offDays.className) || 'bg-muted/25';
const isDropTarget = useEventCalendarSelector<unknown, 'valid' | 'invalid' | null>((state) => {
const drag = state.drag;
if (!drag) return null;
const covered = drag.proposedStart < dayEnd && drag.proposedEnd > dayStart;
if (!covered) return null;
return drag.valid ? 'valid' : 'invalid';
});
// Hide hover affordances mid-gesture: the only intent is the drop target.
// Gated on the one thing that reads it: a plain global boolean flips for all
// 42 cells the moment a gesture starts and again when it ends, which is pure
// waste in the default configuration where no add button renders.
const isInteracting = useEventCalendarSelector<unknown, boolean>((state) =>
viewConfig.showDayAddButton ? state.drag !== null || state.slotDraft !== null : false,
);
const inDraft = useEventCalendarSelector<unknown, { isStart: boolean; isEnd: boolean } | null>(
(state) => {
const draft = state.slotDraft;
if (!draft || !draft.allDay) return null;
if (draft.start >= dayEnd || draft.end <= dayStart) return null;
return {
isStart: draft.start >= dayStart,
isEnd: draft.end <= dayEnd,
};
},
{
isEqual: (a, b) => a === b || (a !== null && b !== null && a.isStart === b.isStart && a.isEnd === b.isEnd),
},
);
// Month drag-create selects whole DAYS, so the readout is a date range rather
// than a time range. Held separately from `inDraft` above, which only knows
// whether this cell is an edge of the selection, not what the selection is.
const draftRange = useEventCalendarSelector<unknown, { start: Date; end: Date } | null>(
(state) => {
const draft = state.slotDraft;
if (!draft || !draft.allDay) return null;
return { start: draft.start, end: draft.end };
},
{
isEqual: (a, b) => a === b || (a !== null && b !== null && a.start.getTime() === b.start.getTime() && a.end.getTime() === b.end.getTime()),
},
);
// A single-day timed MOVE landing on THIS day: expose the proposed
// minute-of-day (+ color/validity) so the cell can render a drop placeholder
// at the correct time-sorted position, instead of the overlay marking a bar
// over the first chip. Skipped for bars (they keep the overlay ghost) and for
// a no-op move back onto the event's own day (the dimmed source already marks
// the spot).
const inlineDrop = useEventCalendarSelector<unknown, { min: number; valid: boolean; color?: string } | null>(
(state) => {
const drag = state.drag;
if (!drag || drag.kind !== 'move' || drag.proposedAllDay) return null;
if (drag.proposedEnd.getTime() - drag.proposedStart.getTime() > 86400000) return null;
const dropDayMs = zonedStartOfDay(drag.proposedStart, settings.timeZone).getTime();
if (dropDayMs !== dayStart.getTime()) return null;
if (zonedStartOfDay(drag.occurrence.start, settings.timeZone).getTime() === dayStart.getTime()) return null;
return {
min: (drag.proposedStart.getTime() - dropDayMs) / 60000,
valid: drag.valid,
color: drag.occurrence.event.color,
};
},
{
isEqual: (a, b) => a === b || (a !== null && b !== null && a.min === b.min && a.valid === b.valid && a.color === b.color),
},
);
// Bars (allDay/multi-day) are drawn by the week-row overlay; the cell renders
// only single-day timed events, below the reserved bar lanes.
const extraHidden = hiddenBarKeys.size;
const hiddenBarSegs = segments.allDay.filter((s) => hiddenBarKeys.has(s.occurrence.key));
const m = segments.timed.length;
const timedSlots = Math.max(0, cap - reservedLanes);
// Static (at-rest) split: what the cell shows with no drag, and - crucially -
// what the "+N more" popover lists. The popover carries ONLY the hidden events
// (hidden bars + timed past the cap), never the chips already visible in the
// cell, so it never duplicates them. autoFit gives up one timed row to the
// "+N more" indicator so the visible chips fit the clipped cell height.
const staticOverflow = extraHidden > 0 || m > timedSlots;
const staticShown = autoFit && staticOverflow ? Math.max(0, timedSlots - 1) : timedSlots;
const overflowSegments = [...hiddenBarSegs, ...segments.timed.slice(staticShown)];
// Live split: while a timed chip is dragged onto this day, render the day
// exactly as it will look AFTER the drop. The dragged chip is a phantom in the
// time-sorted order and is shown as the placeholder - inline where it lands,
// or ON the "+N more" indicator when it lands in the overflow bucket (so the
// user sees the drop will push it into "more"). The "+N more" count always
// reflects the post-drop hidden total.
let visibleTimed: EventCalendarSegment[];
let overflowCount: number;
let placeholderIndex: number;
let placeholderAtMore: boolean;
if (!inlineDrop) {
visibleTimed = segments.timed.slice(0, staticShown);
overflowCount = overflowSegments.length;
placeholderIndex = -1;
placeholderAtMore = false;
} else {
// rank of the dragged chip in the resulting time-sorted list (chips are
// time-ordered, so this is the count starting at or before its time)
const insertRank = segments.timed.filter((s) => (s.startMin ?? 0) <= inlineDrop.min).length;
const dropOverflow = extraHidden > 0 || m + 1 > timedSlots;
// rows for timed items INCLUDING the phantom, before the "+N more" row
const vis = !dropOverflow ? m + 1 : autoFit ? Math.max(0, timedSlots - 1) : timedSlots;
placeholderAtMore = insertRank >= vis;
visibleTimed = placeholderAtMore ? segments.timed.slice(0, vis) : segments.timed.slice(0, Math.max(0, vis - 1));
placeholderIndex = placeholderAtMore ? -1 : insertRank;
overflowCount = extraHidden + (m - visibleTimed.length) + (placeholderAtMore ? 1 : 0);
}
// No dep array: the replacement for a chip that lost focus to a commit can
// appear on any re-render of any cell, and a cell with nothing to restore
// bails after two comparisons.
const rootRef = useRef<HTMLDivElement | null>(null);
useIsoLayoutEffect(() => {
restoreChipFocus(rootRef.current, visibleTimed);
});
// Faint dashed drop placeholder, tinted to the dragged event's color, echoing
// the move ghost (EVENT_CALENDAR_GHOST.move); one chip-height tall so chips
// shift by exactly one row when it is inserted.
const dropPlaceholder = inlineDrop ? (
<div
key="ec-drop-placeholder"
aria-hidden
data-slot="event-calendar-drop-placeholder"
data-drop-invalid={!inlineDrop.valid || undefined}
className={cn(
'shrink-0 rounded-sm border border-dashed',
inlineDrop.valid ? 'border-(--ec-event-color)/50 bg-(--ec-event-color)/8' : 'border-destructive/70 bg-destructive/10',
viewConfig.classNames?.dragGhost,
)}
style={
{
'--ec-event-color': inlineDrop.color ?? 'var(--color-primary)',
height: 'calc(var(--ec-month-bar-h, 1.75rem) - 0.125rem)',
} as CSSProperties
}
/>
) : null;
const defaultContent = (
<>
<div
ref={contentRef}
className={cn(
// gap-0.5 pairs with the 0.125rem subtraction in the lane spacer
// below; changing the gap requires renderMonthCell
// px-1 matches the all-day bar wrapper inset so single-day chips and
// multi-day bars line up on the same left/right edge in a cell
'flex min-h-0 flex-1 flex-col gap-0.5 overflow-hidden px-1 pt-1.5',
viewConfig.classNames?.monthCellContent,
)}
>
{reservedLanes > 0 && (
<div
aria-hidden
className="shrink-0"
style={{
// lane height already carries the 2px inter-lane gap; subtract
// it so spacer + the column's own gap-0.5 = the SAME 2px rhythm
// between the last bar and the first timed chip
height: `calc(${reservedLanes} * var(--ec-month-bar-h, 1.75rem) - 0.125rem)`,
}}
/>
)}
{visibleTimed.flatMap((segment, i) => {
const chip = (
<EventCalendarEvent
key={segment.occurrence.key}
segment={segment}
// Remember the chip holding focus so a commit that re-keys it can
// hand focus back to the remounted one (see restoreChipFocus)
onFocus={(e) => {
focusedChip = {
node: e.currentTarget,
eventId: segment.occurrence.eventId,
recurrenceIndex: segment.occurrence.recurrenceIndex,
};
}}
// A chip still in the tree lost focus on its own, so there is
// nothing to restore; only a blur from the remount is kept.
onBlur={(e) => {
if (e.currentTarget.isConnected) focusedChip = null;
}}
// Hold a fixed height like the all-day lane above; without this
// the chip flex-shrinks to whatever room the cell has left, so
// cells with a reserved bar lane or a second chip render shorter
// chips.
className="shrink-0"
/>
);
return i === placeholderIndex ? [dropPlaceholder, chip] : [chip];
})}
{placeholderIndex >= 0 && placeholderIndex >= visibleTimed.length && dropPlaceholder}
{overflowCount > 0 && (
<EventCalendarMoreIndicator
day={day}
count={overflowCount}
segments={overflowSegments}
dropInto={placeholderAtMore && inlineDrop ? { color: inlineDrop.color, valid: inlineDrop.valid } : undefined}
/>
)}
</div>
{/* Day number + add affordance, bottom-right (Notion-style) */}
<div className={cn('flex items-center justify-end gap-1 px-2 pb-1.5', viewConfig.classNames?.monthCellFooter)}>
{viewConfig.showDayAddButton && !isInteracting && (
<button
type="button"
data-slot="event-calendar-day-add"
aria-label={settings.i18n.labels.addEvent}
// a different icon/markup is a renderMonthCell job
className={cn(
'bg-primary text-primary-foreground flex size-5 cursor-pointer items-center justify-center rounded-sm opacity-0 transition-opacity group-hover/ec-cell:opacity-100 focus-visible:opacity-100',
viewConfig.classNames?.dayAddButton,
)}
onClick={(e) => {
e.stopPropagation();
settings.onSlotClick?.({ date: day, allDay: true, view: 'month' }, e);
}}
>
<PlusIcon className="size-3.5" aria-hidden="true" />
</button>
)}
<span
data-slot="event-calendar-month-day-number"
className={cn(
'flex size-5 items-center justify-center rounded-full',
isOutside && 'text-muted-foreground',
// the filled circle already marks today; keep the number the same
// weight/size as the other days so it does not read as larger
// Same font-size as every other day; a lighter weight cancels the
// way white digits on the filled circle read bolder/larger than the
// dark-on-light numbers around them.
isToday && 'bg-primary text-primary-foreground font-light',
viewConfig.classNames?.monthDayNumber,
)}
>
{format(toZoned(day, settings.timeZone), settings.i18n.formats.monthCellDay, { locale: settings.locale })}
</span>
</div>
</>
);
const content =
viewConfig.renderMonthCell?.({
day,
segments,
isToday,
isOutside,
overflowCount,
defaultContent,
}) ?? defaultContent;
return (
<div
ref={rootRef}
role="gridcell"
data-slot="event-calendar-month-cell"
data-today={isToday || undefined}
data-outside={isOutside || undefined}
data-weekend={settings.weekendDays.includes(toZoned(day, settings.timeZone).getDay()) || undefined}
data-ec-day={dayStart.getTime()}
data-drop-target={isDropTarget ?? undefined}
data-off={isOff || undefined}
data-draft={inDraft ? '' : undefined}
aria-label={format(toZoned(day, settings.timeZone), settings.i18n.formats.monthCellAriaLabel, {
locale: settings.locale,
})}
className={cn(
'group/ec-cell relative flex min-h-0 min-w-0 flex-col overflow-hidden',
!isLast && 'border-e',
isOutside && !settings.showOutsideDays && 'invisible',
isOff && offClassName,
isToday && cn('bg-primary/3 border-b-primary/40 relative border-b-2', viewConfig.todayClassName),
viewConfig.dayClassName?.(day),
// No drop-target bg fill on move/resize - the dragged bar + not-allowed
// cursor carry the feedback; a cell-wide color wash is too distracting.
// data-drop-target stays as an opt-in styling hook.
inDraft && EVENT_CALENDAR_SLOT_DRAFT.surface,
viewConfig.classNames?.monthCell,
)}
onPointerDown={(e) => {
const target = e.target as HTMLElement;
if (target.closest('[data-slot=event-calendar-event]')) return;
if (target.closest('[data-slot=event-calendar-more]')) return;
gestures.beginCreate(e, day, true);
}}
onClick={(e) => {
if (wasRecentDrag() || wasRecentChipPress()) return;
settings.onSlotClick?.({ date: day, allDay: true, view: 'month' }, e);
}}
>
{inDraft && (
<span
aria-hidden
data-slot="event-calendar-slot-draft"
className={cn(
'pointer-events-none absolute inset-0 z-10',
EVENT_CALENDAR_SLOT_DRAFT.segment,
inDraft.isStart && EVENT_CALENDAR_SLOT_DRAFT.segmentStart,
inDraft.isEnd && EVENT_CALENDAR_SLOT_DRAFT.segmentEnd,
viewConfig.classNames?.slotDraft,
)}
>
{/* Date-range readout, the month-view counterpart of the time-grid
one. Rendered only on the FIRST cell of the selection, otherwise
a three-day drag would repeat the same label three times. Pinned
to the bottom because the day number owns the top of the cell,
and given its own surface so it stays legible over event chips. */}
{inDraft.isStart && draftRange && (
<span className={cn('absolute inset-x-1 bottom-1', EVENT_CALENDAR_SLOT_DRAFT.label)}>
{settings.i18n.functions.formatDayRange(
{
start: toZoned(draftRange.start, settings.timeZone),
end: toZoned(draftRange.end, settings.timeZone),
},
{ locale: settings.locale },
)}
</span>
)}
</span>
)}
{content}
</div>
);
}
interface EventCalendarMoreIndicatorProps {
day: Date;
count: number;
/** The OVERFLOW (hidden) segments for this day - bars first, then timed. The
* popover lists only these, never the chips already visible in the cell. */
segments: EventCalendarSegment[];
/** Set while a timed chip is dragged and will land in THIS overflow bucket:
* the indicator itself becomes the drop placeholder (dashed, event-tinted) so
* it reads as "the chip joins the +N more list". */
dropInto?: { color?: string; valid: boolean };
}
/**
* "+N more" trigger opening a popover with the day's full event list.
* onMoreClick returning false suppresses the built-in popover.
*/
function EventCalendarMoreIndicator({ day, count, segments, dropInto }: EventCalendarMoreIndicatorProps) {
const settings = useEventCalendarSettings();
const viewConfig = useEventCalendarViewConfig();
const [open, setOpen] = useState(false);
const headerId = useId();
// Grabbing a chip from this list starts a drag; close the popover so it does
// not sit over the drop target while the event is carried to another day.
const isDragging = useEventCalendarSelector<unknown, boolean>((state) => state.drag !== null);
useEffect(() => {
if (isDragging) setOpen(false);
}, [isDragging]);
return (
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger
data-slot="event-calendar-more"
data-drop-into={dropInto ? '' : undefined}
data-drop-invalid={dropInto && !dropInto.valid ? '' : undefined}
className={cn(
'text-muted-foreground hover:text-foreground cursor-pointer truncate rounded-sm px-1.5 text-start',
// While a dragged chip will land in this overflow bucket, the "+N more"
// link itself becomes the drop placeholder: dashed, event-tinted, one
// chip tall, so the drop target is unmistakable.
dropInto &&
cn(
'flex shrink-0 items-center border border-dashed',
dropInto.valid
? 'text-foreground border-(--ec-event-color)/50 bg-(--ec-event-color)/8'
: 'border-destructive/70 bg-destructive/10 text-destructive',
),
viewConfig.classNames?.moreIndicator,
)}
style={
dropInto
? ({
'--ec-event-color': dropInto.color ?? 'var(--color-primary)',
height: 'calc(var(--ec-month-bar-h, 1.75rem) - 0.125rem)',
} as CSSProperties)
: undefined
}
onClick={(e: React.MouseEvent) => {
e.stopPropagation();
const verdict = settings.onMoreClick?.(
day,
segments.map((segment) => segment.occurrence),
e,
);
if (verdict === false) {
e.preventDefault();
setOpen(false);
}
}}
>
{viewConfig.renderMoreIndicator?.({ day, count, segments }) ?? settings.i18n.labels.more(count)}
</PopoverTrigger>
<PopoverContent
data-slot="event-calendar-more-popover"
align={viewConfig.morePopoverAlign}
// The popover is a dialog, so it needs a name. The built-in body already
// renders the day header this list belongs to, so point at that; a
// consumer body has no header to point at and gets the same formatted
// day as a label instead.
aria-labelledby={viewConfig.renderMoreContent ? undefined : headerId}
aria-label={
viewConfig.renderMoreContent
? format(toZoned(day, settings.timeZone), settings.i18n.formats.moreDayHeader, { locale: settings.locale })
: undefined
}
// PopoverContent is unlayered (flex-col gap-4 p-4); override with !.
// text-xs re-establishes the calendar's base type here because this
// content is portaled out of the root subtree and cannot inherit it.
className={cn('w-64 gap-1! p-2! text-xs', viewConfig.classNames?.morePopover)}
onClick={(e: React.MouseEvent) => e.stopPropagation()}
>
{viewConfig.renderMoreContent ? (
viewConfig.renderMoreContent({
day,
segments,
close: () => setOpen(false),
})
) : (
<EventCalendarMoreDefaultContent day={day} segments={segments} headerId={headerId} />
)}
</PopoverContent>
</Popover>
);
}
/** Built-in "+N more" popover body: day header + the day's chips. */
function EventCalendarMoreDefaultContent({
day,
segments,
headerId,
}: {
day: Date;
segments: EventCalendarSegment[];
/** Names the popover dialog: the header IS the list's accessible name. */
headerId?: string;
}) {
const settings = useEventCalendarSettings();
const viewConfig = useEventCalendarViewConfig();
return (
<>
<div id={headerId} className={cn('text-muted-foreground px-1 py-1 text-xs font-medium', viewConfig.classNames?.morePopoverHeader)}>
{format(toZoned(day, settings.timeZone), settings.i18n.formats.moreDayHeader, { locale: settings.locale })}
</div>
{/* The scroll region breaks out of the popover's right padding (-me-2)
so the scrollbar sits flush in the gutter; the list then pads itself
back (ps-1 aligns with the header, pe-4 clears the ~10px bar with a
gap) and adds py-1 so the first/last focus ring is not clipped by
the overflow. Layout is identical with or without a scrollbar. */}
{viewConfig.scrollbars === 'native' ? (
<div data-ec-native-scroll="" className="-me-2 max-h-(--ec-more-max-height,16rem) min-h-0 overflow-y-auto">
<div className="flex flex-col gap-1 py-1 ps-1 pe-4">
{segments.map((segment) => (
<EventCalendarEvent key={segment.occurrence.key} segment={segment} className="py-0.5" />
))}
</div>
</div>
) : (
<ScrollArea className="-me-2 min-h-0 **:data-[slot=scroll-area-viewport]:max-h-(--ec-more-max-height,16rem)">
<div className="flex flex-col gap-1 py-1 ps-1 pe-4">
{segments.map((segment) => (
<EventCalendarEvent key={segment.occurrence.key} segment={segment} className="py-0.5" />
))}
</div>
</ScrollArea>
)}
</>
);
}
export { EventCalendarMonthView, EventCalendarMoreIndicator };
export type { EventCalendarMonthViewProps, EventCalendarMoreIndicatorProps };import type {
CalendarEvent,
EventCalendarDateRange,
EventCalendarOccurrence,
EventCalendarRecurrenceRule,
EventCalendarWeekday,
} from '@/registry/vcare/ui/event-calendar/event-calendar-types';
import { TZDate } from '@date-fns/tz';
import { addDays, addMonths, addWeeks, addYears } from 'date-fns';
/** Guard: max window-intersecting occurrences per event per expansion. */
const MAX_OCCURRENCES = 1000;
/** Runaway guard: absolute cap on period iterations regardless of visibility. */
const MAX_ITERATIONS = 10000;
/** Gregorian mean period lengths for the O(1) fast-forward approximation. */
const PERIOD_MS: Record<EventCalendarRecurrenceRule['freq'], number> = {
daily: 86400000,
weekly: 604800000,
monthly: 2629746000, // 365.2425 / 12 days
yearly: 31556952000, // 365.2425 days
};
const WEEKDAYS: EventCalendarWeekday[] = ['SU', 'MO', 'TU', 'WE', 'TH', 'FR', 'SA'];
class EventCalendarRecurrenceError extends Error {
constructor(part: string) {
super(`Unsupported recurrence part: ${part}. Use the getOccurrences prop to plug a full RRULE engine for exotic rules.`);
this.name = 'EventCalendarRecurrenceError';
}
}
/**
* Parses a raw RRULE line (with or without the "RRULE:" prefix) into the
* structured subset. Pass the display time zone so Z-less UNTIL values are
* interpreted as wall time in that zone rather than the machine zone.
*/
function parseRRuleString(input: string, timeZone?: string): EventCalendarRecurrenceRule {
const body = input.trim().replace(/^RRULE:/i, '');
const rule: Partial<EventCalendarRecurrenceRule> = {};
for (const pair of body.split(';')) {
if (!pair) continue;
const [rawKey, rawValue] = pair.split('=');
const key = rawKey?.toUpperCase();
const value = rawValue ?? '';
switch (key) {
case 'FREQ': {
const freq = value.toLowerCase();
if (freq !== 'daily' && freq !== 'weekly' && freq !== 'monthly' && freq !== 'yearly') {
throw new EventCalendarRecurrenceError(`FREQ=${value}`);
}
rule.freq = freq;
break;
}
case 'INTERVAL':
rule.interval = Math.max(1, parseInt(value, 10) || 1);
break;
case 'COUNT':
rule.count = Math.max(1, parseInt(value, 10) || 1);
break;
case 'UNTIL':
rule.until = parseRRuleDate(value, timeZone);
break;
case 'BYDAY':
rule.byWeekday = value.split(',').map((token) => {
// RFC 5545 3.1: enumerated values are case-insensitive, and FREQ is
// already folded above - rejecting "mo" here would be inconsistent
const match = /^(-?\d+)?(SU|MO|TU|WE|TH|FR|SA)$/.exec(token.trim().toUpperCase());
if (!match) throw new EventCalendarRecurrenceError(`BYDAY=${token}`);
const day = match[2] as EventCalendarWeekday;
return match[1] ? { day, ordinal: parseInt(match[1], 10) } : day;
});
break;
case 'BYMONTHDAY':
rule.byMonthDay = value.split(',').map((v) => {
const day = parseInt(v, 10);
// NaN would survive parsing, match no day in any month and leave the
// event permanently invisible with no error anywhere
if (Number.isNaN(day)) {
throw new EventCalendarRecurrenceError(`BYMONTHDAY=${v}`);
}
return day;
});
break;
case 'BYMONTH':
rule.byMonth = value.split(',').map((v) => parseInt(v, 10));
break;
case 'WKST': {
const day = value.trim().toUpperCase() as EventCalendarWeekday;
if (!WEEKDAYS.includes(day)) {
throw new EventCalendarRecurrenceError(`WKST=${value}`);
}
rule.weekStart = day;
break;
}
default:
throw new EventCalendarRecurrenceError(key ?? pair);
}
}
if (!rule.freq) throw new EventCalendarRecurrenceError('missing FREQ');
return rule as EventCalendarRecurrenceRule;
}
function parseRRuleDate(value: string, timeZone?: string): Date {
// RFC 5545 basic formats: YYYYMMDD or YYYYMMDDTHHMMSS(Z). The T and Z
// designators are case-insensitive too (RFC 5545 3.1), so fold before matching.
const match = /^(\d{4})(\d{2})(\d{2})(?:T(\d{2})(\d{2})(\d{2})(Z)?)?$/.exec(value.trim().toUpperCase());
if (!match) throw new EventCalendarRecurrenceError(`UNTIL=${value}`);
const [, y, m, d, hh = '23', mm = '59', ss = '59', z] = match;
// Z-less values (including date-only ones, which mean end of that day
// inclusive) are wall time in the display zone, not the machine zone.
const date = z
? new Date(`${y}-${m}-${d}T${hh}:${mm}:${ss}Z`)
: timeZone
? new Date(new TZDate(+y, +m - 1, +d, +hh, +mm, +ss, timeZone).getTime())
: new Date(`${y}-${m}-${d}T${hh}:${mm}:${ss}`);
if (Number.isNaN(date.getTime())) {
throw new EventCalendarRecurrenceError(`UNTIL=${value}`);
}
return date;
}
/** Serializes the structured subset back to an RRULE line (without prefix). */
function formatRRuleString(rule: EventCalendarRecurrenceRule): string {
const parts: string[] = [`FREQ=${rule.freq.toUpperCase()}`];
if (rule.interval && rule.interval > 1) parts.push(`INTERVAL=${rule.interval}`);
if (rule.count) parts.push(`COUNT=${rule.count}`);
if (rule.until) {
const u = rule.until;
const pad = (n: number) => String(n).padStart(2, '0');
parts.push(
`UNTIL=${u.getUTCFullYear()}${pad(u.getUTCMonth() + 1)}${pad(u.getUTCDate())}T${pad(u.getUTCHours())}${pad(u.getUTCMinutes())}${pad(u.getUTCSeconds())}Z`,
);
}
if (rule.byWeekday?.length) {
parts.push(`BYDAY=${rule.byWeekday.map((d) => (typeof d === 'string' ? d : `${d.ordinal}${d.day}`)).join(',')}`);
}
if (rule.byMonthDay?.length) parts.push(`BYMONTHDAY=${rule.byMonthDay.join(',')}`);
if (rule.byMonth?.length) parts.push(`BYMONTH=${rule.byMonth.join(',')}`);
if (rule.weekStart) parts.push(`WKST=${rule.weekStart}`);
return parts.join(';');
}
function resolveRule(recurrence: EventCalendarRecurrenceRule | string, timeZone?: string): EventCalendarRecurrenceRule {
return typeof recurrence === 'string' ? parseRRuleString(recurrence, timeZone) : recurrence;
}
/**
* Expands one event into its occurrences intersecting the range.
* Non-recurring events yield at most one occurrence. Recurrence iteration is
* wall-time based in the display zone (DST-safe day/week/month steps), and a
* span that is a whole number of local days keeps that day count across a DST
* transition (timed spans keep their absolute length instead).
*
* exDates remove exactly-matching instants (after COUNT numbering,
* Google-style: an exception still consumes its COUNT slot); rDates add extra
* instants with the same duration. RECURRENCE-ID override replacement lives
* in buildEventIndex, where the override event and its parent series meet.
*/
function expandRecurrence<TData>(
event: CalendarEvent<TData>,
range: EventCalendarDateRange,
ctx: { timeZone: string },
): EventCalendarOccurrence<TData>[] {
const allDay = event.allDay ?? false;
if (!event.recurrence) {
// The exclusive `end > start` test is right for anything with duration,
// but it also drops a zero-length milestone pinned to the first visible
// instant - which reads as an event that randomly disappears until you
// page one period back. A point occurrence only has to be inside.
const isPoint = event.end.getTime() === event.start.getTime();
if (event.start < range.end && (event.end > range.start || (isPoint && event.start >= range.start))) {
return [
{
key: `${event.id}::${event.start.toISOString()}`,
eventId: event.id,
event,
start: event.start,
end: event.end,
allDay,
isRecurring: false,
},
];
}
return [];
}
const rule = resolveRule(event.recurrence, ctx.timeZone);
const interval = Math.max(1, rule.interval ?? 1);
const durationMs = event.end.getTime() - event.start.getTime();
const zonedStart = new TZDate(event.start.getTime(), ctx.timeZone);
// A span of whole local days is wall time, not an absolute delta: a 3 day
// all-day bar crossing spring forward would otherwise end at 01:00 and
// occupy a fourth day in the month grid. Timed spans stay absolute so a two
// hour meeting is still two hours.
const daySpan = Math.round(durationMs / 86400000);
const wallDaySpan = daySpan > 0 && addDays(zonedStart, daySpan).getTime() === event.end.getTime() ? daySpan : null;
const endFor = (start: Date): Date =>
wallDaySpan === null
? new Date(start.getTime() + durationMs)
: new Date(addDays(new TZDate(start.getTime(), ctx.timeZone), wallDaySpan).getTime());
// Excluded instants matched exactly; filtering happens at push time so an
// exception still consumes its COUNT slot (Google-style numbering).
const exTimes = new Set((rule.exDates ?? []).map((d) => d.getTime()));
const weeklyDays: number[] | null =
rule.freq === 'weekly' && rule.byWeekday?.length
? [
...new Set(
rule.byWeekday.map((d) => {
if (typeof d !== 'string') {
throw new EventCalendarRecurrenceError('BYDAY ordinal outside monthly/yearly');
}
return WEEKDAYS.indexOf(d);
}),
),
]
: null;
// BYDAY resolved inside a month: monthly, and yearly within each BYMONTH
// (FREQ=YEARLY;BYMONTH=11;BYDAY=4TH is Thanksgiving, not "the anchor's day")
const monthlyByDay = (rule.freq === 'monthly' || rule.freq === 'yearly') && rule.byWeekday?.length ? rule.byWeekday : null;
// RFC 5545 3.3.10 week numbering: with INTERVAL > 1 the week start decides
// which selected days share a period, so an ignored WKST puts half of every
// biweekly series a week off. Default MO, per the RFC.
const weekStartIndex = WEEKDAYS.indexOf(rule.weekStart ?? 'MO');
/** Days from the WKST-aligned week start to `day` (0-6). */
const fromWeekStart = (day: number) => (day - weekStartIndex + 7) % 7;
// yearly BYMONTH filter (1-12), ascending; defaults to the anchor's month
const validByMonth = rule.byMonth?.filter((m) => m >= 1 && m <= 12) ?? [];
const yearlyMonths: number[] = validByMonth.length > 0 ? [...new Set(validByMonth)].sort((a, b) => a - b) : [zonedStart.getMonth() + 1];
// month-shaped BY* parts make the per-period occurrence count variable
const hasMonthDayParts =
(rule.freq === 'monthly' && Boolean(rule.byMonthDay?.length || monthlyByDay)) ||
(rule.freq === 'yearly' && Boolean(rule.byMonth?.length || rule.byMonthDay?.length || monthlyByDay));
const daysInMonth = (year: number, month: number) => new Date(year, month + 1, 0).getDate();
// RFC 5545 3.3.10 LIMIT filters: at these frequencies a BY* part narrows the
// set instead of reshaping it. Dropping them silently expanded the series as
// if the part were absent (FREQ=DAILY;BYDAY=MO filled every day). Filtering
// here rather than at push time keeps COUNT numbering RFC-correct: a
// candidate the filter removes is not an occurrence and consumes no slot.
const limitByMonth = rule.freq !== 'yearly' && validByMonth.length > 0 ? validByMonth : null;
const limitByMonthDay = rule.freq === 'daily' && rule.byMonthDay?.length ? rule.byMonthDay : null;
const limitByWeekday =
rule.freq === 'daily' && rule.byWeekday?.length ? rule.byWeekday.map((d) => WEEKDAYS.indexOf(typeof d === 'string' ? d : d.day)) : null;
const hasLimits = Boolean(limitByMonth || limitByMonthDay || limitByWeekday);
const passesLimits = (candidate: TZDate): boolean => {
if (limitByMonth && !limitByMonth.includes(candidate.getMonth() + 1)) {
return false;
}
if (limitByWeekday && !limitByWeekday.includes(candidate.getDay())) {
return false;
}
if (limitByMonthDay) {
const total = daysInMonth(candidate.getFullYear(), candidate.getMonth());
const day = candidate.getDate();
// negative BYMONTHDAY counts back from month end, as in monthDays
if (!limitByMonthDay.some((n) => (n < 0 ? total + 1 + n : n) === day)) {
return false;
}
}
return true;
};
/** Wall-clock instant in the display zone carrying DTSTART's time-of-day. */
const zonedDate = (year: number, month: number, day: number) =>
new TZDate(year, month, day, zonedStart.getHours(), zonedStart.getMinutes(), zonedStart.getSeconds(), zonedStart.getMilliseconds(), ctx.timeZone);
/** Selected days-of-month, ascending: BYMONTHDAY (and) BYDAY, else the clamped anchor day. */
const monthDays = (year: number, month: number): number[] => {
const total = daysInMonth(year, month);
let days: number[] | null = null;
if (rule.byMonthDay?.length) {
// negative BYMONTHDAY counts back from month end; nonexistent days skip
days = rule.byMonthDay.map((n) => (n < 0 ? total + 1 + n : n)).filter((n) => n >= 1 && n <= total);
}
if (monthlyByDay) {
const byDayMatches: number[] = [];
for (const entry of monthlyByDay) {
const day = typeof entry === 'string' ? entry : entry.day;
const ordinal = typeof entry === 'string' ? 0 : entry.ordinal;
const weekday = WEEKDAYS.indexOf(day);
const matches: number[] = [];
for (let d = 1; d <= total; d++) {
if (new Date(year, month, d).getDay() === weekday) matches.push(d);
}
if (ordinal === 0) {
byDayMatches.push(...matches); // plain BYDAY: every matching weekday
} else {
// 2TU = 2nd Tuesday, -1FR = last Friday; absent ordinals skip
const pick = ordinal > 0 ? matches[ordinal - 1] : matches[matches.length + ordinal];
if (pick !== undefined) byDayMatches.push(pick);
}
}
days = days ? days.filter((n) => byDayMatches.includes(n)) : byDayMatches;
}
if (!days) days = [Math.min(zonedStart.getDate(), total)]; // clamp to month end
return [...new Set(days)].sort((a, b) => a - b);
};
/** Chronological candidates of one period, derived from the DTSTART anchor by index (no drift). */
const periodCandidates = (period: number): TZDate[] => {
if (rule.freq === 'daily') return [addDays(zonedStart, period * interval)];
if (rule.freq === 'weekly') {
const base = addWeeks(zonedStart, period * interval);
if (!weeklyDays) return [base];
const week: TZDate[] = [];
// walk the WKST-aligned week so candidates stay chronological
const baseOffset = fromWeekStart(base.getDay());
for (let offset = 0; offset < 7; offset++) {
const candidate = addDays(base, offset - baseOffset);
if (!weeklyDays.includes(candidate.getDay())) continue;
// days of the DTSTART week before DTSTART are not part of the series
if (candidate.getTime() < zonedStart.getTime()) continue;
week.push(candidate);
}
return week;
}
if (rule.freq === 'monthly') {
const anchor = addMonths(zonedStart, period * interval);
const year = anchor.getFullYear();
const month = anchor.getMonth();
return monthDays(year, month)
.map((day) => zonedDate(year, month, day))
.filter((c) => c.getTime() >= zonedStart.getTime());
}
// yearly
const year = addYears(zonedStart, period * interval).getFullYear();
const dates: TZDate[] = [];
for (const month of yearlyMonths) {
for (const day of monthDays(year, month - 1)) {
dates.push(zonedDate(year, month - 1, day));
}
}
return dates.filter((c) => c.getTime() >= zonedStart.getTime());
};
/** Candidates of one period with the LIMIT filters applied. */
const candidatesFor = (period: number): TZDate[] => (hasLimits ? periodCandidates(period).filter(passesLimits) : periodCandidates(period));
/** Earliest/latest instant a period can produce - loop bounds without expanding it. */
const periodEdge = (period: number, edge: 'first' | 'last'): TZDate => {
if (rule.freq === 'daily') return addDays(zonedStart, period * interval);
if (rule.freq === 'weekly') {
const base = addWeeks(zonedStart, period * interval);
if (!weeklyDays) return base;
return addDays(base, (edge === 'first' ? 0 : 6) - fromWeekStart(base.getDay()));
}
if (rule.freq === 'monthly') {
const anchor = addMonths(zonedStart, period * interval);
const year = anchor.getFullYear();
const month = anchor.getMonth();
return zonedDate(year, month, edge === 'first' ? 1 : daysInMonth(year, month));
}
const year = addYears(zonedStart, period * interval).getFullYear();
const month = (edge === 'first' ? yearlyMonths[0] : yearlyMonths[yearlyMonths.length - 1]) - 1;
return zonedDate(year, month, edge === 'first' ? 1 : daysInMonth(year, month));
};
// O(1) fast-forward: land a couple of periods before the window instead of
// iterating from DTSTART, so years-old series still reach the visible range.
const aheadMs = range.start.getTime() - durationMs - zonedStart.getTime();
const stepMs = PERIOD_MS[rule.freq] * interval;
let startPeriod = aheadMs > 0 ? Math.max(0, Math.floor(aheadMs / stepMs) - 2) : 0;
// mean-length drift is bounded well under one period - refine forward
while (periodEdge(startPeriod, 'last').getTime() + durationMs <= range.start.getTime()) {
startPeriod++;
}
// series ordinal at startPeriod, so COUNT and recurrenceIndex stay exact
let index = 0;
if (startPeriod > 0) {
if (hasMonthDayParts || hasLimits) {
// per-period counts vary (skipped days, 4-vs-5 weekday months, a LIMIT
// filter that empties a whole period) - sum them
for (let period = 0; period < startPeriod; period++) {
index += candidatesFor(period).length;
}
} else if (weeklyDays) {
// week 0 only counts selected weekdays at/after DTSTART's, inside the
// WKST-aligned week that holds it
const anchorOffset = fromWeekStart(zonedStart.getDay());
const firstWeek = weeklyDays.filter((d) => fromWeekStart(d) >= anchorOffset).length;
index = firstWeek + (startPeriod - 1) * weeklyDays.length;
} else {
index = startPeriod; // one occurrence per period
}
}
const occurrences: EventCalendarOccurrence<TData>[] = [];
const pushIfVisible = (rawStart: Date) => {
// normalize to a plain instant so consumers never receive zone-carrying
// TZDate instances (mixed-zone formatting bugs)
const start = new Date(rawStart.getTime());
if (exTimes.has(start.getTime())) return;
const end = endFor(start);
if (start < range.end && end > range.start) {
occurrences.push({
key: `${event.id}::${start.toISOString()}`,
eventId: event.id,
event,
start,
end,
allDay,
isRecurring: true,
recurrenceIndex: index,
});
}
};
let iterations = 0;
let period = startPeriod;
while (iterations < MAX_ITERATIONS && occurrences.length < MAX_OCCURRENCES) {
iterations++;
if (rule.count !== undefined && index >= rule.count) break;
// whole-period bounds: never break on a mid-period weekday/day-of-month,
// so earlier candidates of the final period are still emitted
const earliest = periodEdge(period, 'first');
if (earliest.getTime() >= range.end.getTime()) break;
if (rule.until && earliest.getTime() > rule.until.getTime()) break;
let ended = false;
for (const candidate of candidatesFor(period)) {
if (rule.count !== undefined && index >= rule.count) {
ended = true;
break;
}
if (rule.until && candidate.getTime() > rule.until.getTime()) {
ended = true;
break;
}
pushIfVisible(candidate);
index++;
if (occurrences.length >= MAX_OCCURRENCES) {
ended = true;
break;
}
}
if (ended) break;
period++;
}
// RDATE: extra instants join the set (deduped against generated starts and
// exclusions) with the same wall-time duration. Sorted so direct consumers
// still receive chronological order (buildEventIndex re-sorts regardless).
if (rule.rDates?.length) {
const seen = new Set(occurrences.map((o) => o.start.getTime()));
for (const rDate of rule.rDates) {
const start = new Date(rDate.getTime());
if (seen.has(start.getTime()) || exTimes.has(start.getTime())) continue;
const end = endFor(start);
if (start >= range.end || end <= range.start) continue;
seen.add(start.getTime());
occurrences.push({
key: `${event.id}::${start.toISOString()}`,
eventId: event.id,
event,
start,
end,
allDay,
isRecurring: true,
// keep counting past the generated instants: an RDATE with no index
// would fall back to undefined and break any consumer that identifies
// an instance by its position in the series
recurrenceIndex: index++,
});
}
occurrences.sort((a, b) => a.start.getTime() - b.start.getTime());
}
return occurrences;
}
export { EventCalendarRecurrenceError, expandRecurrence, formatRRuleString, MAX_OCCURRENCES, parseRRuleString };import { useEffect, useMemo, useRef, useState, type CSSProperties } from 'react';
import {
EventCalendarViewContext,
useEventCalendar,
useEventCalendarDay,
useEventCalendarSelector,
useEventCalendarSettings,
useEventCalendarViewConfig,
useEventCalendarViewSettings,
} from '@/registry/vcare/ui/event-calendar/event-calendar';
import { useEventCalendarGestures, wasRecentChipPress, wasRecentDrag } from '@/registry/vcare/ui/event-calendar/event-calendar-dnd';
import { EVENT_CALENDAR_GHOST, EVENT_CALENDAR_SLOT_DRAFT, EventCalendarEvent } from '@/registry/vcare/ui/event-calendar/event-calendar-event';
import {
flattenResources,
getDayKey,
getDayTotalMinutes,
packTimedSegments,
resolveOffDay,
snapMinutes,
toZoned,
zonedStartOfDay,
} from '@/registry/vcare/ui/event-calendar/event-calendar-lib';
import {
EVENT_TRACK_WIDTH,
EventCalendarNowIndicator,
EventCalendarTimeGutter,
minuteBlockStyle,
} from '@/registry/vcare/ui/event-calendar/event-calendar-time-grid';
import type { EventCalendarResource, EventCalendarSegment } from '@/registry/vcare/ui/event-calendar/event-calendar-types';
import { mergeProps } from '@base-ui/react/merge-props';
import { useRender } from '@base-ui/react/use-render';
import { addDays, addMinutes } from 'date-fns';
import { cn } from '@/registry/vcare/lib/utils';
import { ScrollArea } from '@/registry/vcare/ui/scroll-area';
const EMPTY_ALL_DAY_SEGMENTS: EventCalendarSegment[] = [];
interface EventCalendarResourceViewProps extends useRender.ComponentProps<'div'> {
dayStartHour?: number;
dayEndHour?: number;
showAllDay?: boolean;
/** Gutter/gridline interval in minutes; defaults to the interval view config. */
interval?: number;
}
/** Leaf resources become booking columns for the anchor day. */
function EventCalendarResourceView({
className,
render,
dayStartHour,
dayEndHour,
showAllDay = true,
interval: intervalProp,
...props
}: EventCalendarResourceViewProps) {
const instance = useEventCalendar();
const settings = useEventCalendarSettings();
const viewConfig = useEventCalendarViewConfig();
const { effective } = useEventCalendarViewSettings();
const anchorDate = useEventCalendarSelector((state) => state.date, {
isEqual: (a, b) => a.getTime() === b.getTime(),
});
const startHour = dayStartHour ?? settings.dayStartHour;
const endHour = dayEndHour ?? settings.dayEndHour;
const interval = Math.min(Math.max(intervalProp ?? viewConfig.interval, 5), 240);
const contained = viewConfig.scrollMode !== 'page';
const day = zonedStartOfDay(anchorDate, settings.timeZone);
const resources = useMemo(
() =>
flattenResources(settings.resources)
.filter(({ resource }) => !resource.children?.length)
.map(({ resource }) => resource),
[settings.resources],
);
// Initial scroll + api.scrollToTime (same contract as the time grid)
const scrollRef = useRef<HTMLDivElement | null>(null);
useEffect(() => {
if (!contained) return;
const el = scrollRef.current;
if (!el) return;
const viewport = el.querySelector<HTMLElement>('[data-slot=scroll-area-viewport]');
const slotRow = el.querySelector<HTMLElement>('[data-slot=event-calendar-time-gutter] > div');
const slotPx = slotRow?.getBoundingClientRect().height || 64;
const pxPerMinute = slotPx / interval;
const scrollTo = (minutes: number) => {
// keep the hour label above the target line visible (it hangs -top-2)
viewport?.scrollTo({
top: Math.max(0, (minutes - startHour * 60) * pxPerMinute - 12),
});
};
scrollTo(viewConfig.scrollToHour * 60);
instance.internals.registerScrollHandler((time) => {
const minutes =
typeof time === 'number' ? time : toZoned(time, settings.timeZone).getHours() * 60 + toZoned(time, settings.timeZone).getMinutes();
scrollTo(minutes);
});
// Classic (width-consuming) scrollbars squeeze the scrolling track while
// the header/all-day rows outside keep full width, drifting the column
// borders. Mirror the measured gutter onto those rows via a CSS var -
// 0px for overlay scrollbars and the custom ScrollArea, so both modes
// lay out identically.
const root = el.closest<HTMLElement>('[data-slot=event-calendar-time-grid], [data-slot=event-calendar-resource-view]');
const syncScrollbarGutter = () => {
root?.style.setProperty('--ec-scrollbar-w', `${viewport ? viewport.offsetWidth - viewport.clientWidth : 0}px`);
};
syncScrollbarGutter();
const gutterObserver = viewport ? new ResizeObserver(syncScrollbarGutter) : null;
if (viewport) gutterObserver?.observe(viewport);
return () => {
instance.internals.registerScrollHandler(null);
gutterObserver?.disconnect();
};
}, [
contained,
instance,
settings.timeZone,
startHour,
interval,
viewConfig.scrollToHour,
// scrollbars custom<->native swaps the scroller DOM: re-bind the
// viewport, the scroll wiring, and the measured --ec-scrollbar-w
viewConfig.scrollbars,
]);
const slots = useMemo(() => {
const result: number[] = [];
for (let m = startHour * 60; m < endHour * 60; m += interval) {
result.push(m);
}
return result;
}, [startHour, endHour, interval]);
// All-day segments for renderAllDaySection - the same index bucket the
// cells read; inert (stable empty array, so the subscription never
// re-renders) while the override is unset.
const allDaySegments = useEventCalendarSelector<unknown, EventCalendarSegment[]>(
() =>
viewConfig.renderAllDaySection
? (instance.internals.getIndex().byDay.get(getDayKey(day, settings.timeZone))?.allDay ?? EMPTY_ALL_DAY_SEGMENTS)
: EMPTY_ALL_DAY_SEGMENTS,
{
isEqual: (a, b) => a === b || (a.length === b.length && a.every((segment, i) => segment === b[i])),
},
);
const gridTemplateColumns = `repeat(${resources.length || 1}, minmax(var(--ec-resource-col-min,8rem), 1fr))`;
const track = (
<div className="relative flex">
{/* shared gutter component, so renderTimeGutterSlot and
classNames.timeGutter customizations apply here too */}
<EventCalendarTimeGutter days={[day]} slots={slots} startHour={startHour} interval={interval} />
<div className="grid min-w-0 flex-1" style={{ gridTemplateColumns }}>
{resources.map((resource) => (
<EventCalendarResourceColumn key={resource.id} resource={resource} day={day} startHour={startHour} endHour={endHour} interval={interval} />
))}
</div>
{effective.nowIndicator && <EventCalendarNowIndicator days={[day]} startHour={startHour} endHour={endHour} />}
</div>
);
const defaultProps = {
'data-slot': 'event-calendar-resource-view',
'data-view': 'resource',
className: cn('flex flex-col border-t', contained && 'min-h-0 flex-1 overflow-hidden', viewConfig.classNames?.timeGrid, className),
style: { '--ec-hour-height': '4rem' } as CSSProperties,
children: (
<>
{/* Resource header row */}
<div
className={cn(
'flex border-b pe-(--ec-scrollbar-w,0px)',
!contained && 'bg-background sticky top-(--ec-sticky-offset,0px) z-20',
viewConfig.classNames?.timeGridHeader,
)}
>
<div className="w-(--ec-gutter-width,4.5rem) shrink-0 border-e" />
<div className="grid min-w-0 flex-1" style={{ gridTemplateColumns }}>
{resources.map((resource) => (
<div
key={resource.id}
data-slot="event-calendar-resource-header"
className={cn('min-w-0 truncate border-e px-2 py-1.5 text-center font-medium last:border-e-0', viewConfig.classNames?.resourceHeader)}
>
{viewConfig.renderResourceHeader?.({ resource }) ?? resource.title}
</div>
))}
</div>
</div>
{/* All-day row per resource */}
{showAllDay && (
<div
data-slot="event-calendar-all-day-section"
className={cn('flex border-b pe-(--ec-scrollbar-w,0px)', viewConfig.classNames?.allDaySection)}
>
{viewConfig.renderAllDaySection?.({
days: [day],
segments: allDaySegments,
}) ?? (
<>
<div
className={cn(
// pt-1.5 matches the all-day cell's top inset; the inner box is
// one bar-row tall and centers the label so it sits on the SAME
// baseline as the first all-day chip and stays top-aligned when
// the chips wrap onto more lanes (mirrors the time-grid label)
'text-muted-foreground w-(--ec-gutter-width,4.5rem) shrink-0 border-e ps-2 pe-2.5 pt-1.5',
viewConfig.classNames?.allDayLabel,
)}
>
<span className="flex h-[calc(var(--ec-month-bar-h,1.625rem)-0.125rem)] items-center justify-end">
{settings.i18n.labels.allDay}
</span>
</div>
<div className="grid min-w-0 flex-1" style={{ gridTemplateColumns }}>
{resources.map((resource) => (
<EventCalendarResourceAllDayCell key={resource.id} resource={resource} day={day} />
))}
</div>
</>
)}
</div>
)}
{contained ? (
<div ref={scrollRef} className="min-h-0 flex-1">
{viewConfig.scrollbars === 'native' ? (
<div data-slot="scroll-area-viewport" data-ec-native-scroll="" className="h-full overflow-y-auto">
{track}
</div>
) : (
<ScrollArea className="h-full">{track}</ScrollArea>
)}
</div>
) : (
track
)}
</>
),
};
return (
<EventCalendarViewContext.Provider value={{ view: 'resource' }}>
{useRender({
defaultTagName: 'div',
render,
props: mergeProps<'div'>(defaultProps, props),
})}
</EventCalendarViewContext.Provider>
);
}
function EventCalendarResourceAllDayCell({ resource, day }: { resource: EventCalendarResource; day: Date }) {
const settings = useEventCalendarSettings();
const viewConfig = useEventCalendarViewConfig();
const { effective } = useEventCalendarViewSettings();
const gestures = useEventCalendarGestures();
const { segments } = useEventCalendarDay(day);
const mine = segments.allDay.filter((segment) => segment.occurrence.event.resourceId === resource.id);
const dayStart = zonedStartOfDay(day, settings.timeZone);
const dayEnd = addDays(toZoned(dayStart, settings.timeZone), 1);
const isOff = resolveOffDay(
day,
settings.timeZone,
effective.offDays ? (typeof viewConfig.offDays === 'object' ? viewConfig.offDays : true) : false,
settings.weekendDays,
);
const offClassName = (typeof viewConfig.offDays === 'object' && viewConfig.offDays.className) || 'bg-muted/25';
const isDropTarget = useEventCalendarSelector<unknown, 'valid' | 'invalid' | null>((state) => {
const drag = state.drag;
if (!drag || !drag.proposedDayGranular) return null;
const covered = drag.proposedStart < dayEnd && drag.proposedEnd > dayStart;
if (!covered) return null;
return drag.valid ? 'valid' : 'invalid';
});
// Slot-draft highlight, mirroring the time-grid all-day cell. The dnd
// layer's all-day create branch does not plumb resourceId into the draft,
// so every resource cell covering the day highlights together.
const inDraft = useEventCalendarSelector<unknown, boolean>((state) => {
const draft = state.slotDraft;
if (!draft || !draft.allDay) return false;
return draft.start < dayEnd && draft.end > dayStart;
});
return (
<div
data-slot="event-calendar-all-day-cell"
// data-ec-day makes this a DnD day target: without it collectSurface()
// finds no cells and dragging an all-day chip silently converts it to
// a timed event via the column branch
data-ec-day={dayStart.getTime()}
data-drop-target={isDropTarget ?? undefined}
data-off={isOff || undefined}
className={cn(
// reserve one bar row so the all-day row keeps the same height with or
// without events, matching the time-grid all-day row (which reserves
// the same via its bars-grid minHeight)
'relative flex min-h-[calc(var(--ec-month-bar-h,1.625rem)+0.625rem)] min-w-0 flex-col gap-0.5 border-e px-1 py-1.5 last:border-e-0',
isOff && offClassName,
viewConfig.dayClassName?.(day),
inDraft &&
cn(
EVENT_CALENDAR_SLOT_DRAFT.surface,
EVENT_CALENDAR_SLOT_DRAFT.segment,
EVENT_CALENDAR_SLOT_DRAFT.segmentStart,
EVENT_CALENDAR_SLOT_DRAFT.segmentEnd,
viewConfig.classNames?.slotDraft,
),
viewConfig.classNames?.allDayCell,
)}
onPointerDown={(e) => {
if (e.target === e.currentTarget) gestures.beginCreate(e, day, true);
}}
onClick={(e) => {
if (e.target === e.currentTarget && !wasRecentDrag() && !wasRecentChipPress()) {
settings.onSlotClick?.(
{
date: dayStart,
allDay: true,
view: 'resource',
resourceId: resource.id,
},
e,
);
}
}}
>
{mine.map((segment) => (
<EventCalendarEvent
key={segment.occurrence.key}
segment={segment}
// one bar-row tall, matching the time-grid all-day bars so the row
// height stays identical across views (and equals the reserved min)
className="h-[calc(var(--ec-month-bar-h,1.625rem)-0.125rem)]"
/>
))}
{isDropTarget && (
<span
aria-hidden
data-slot="event-calendar-drop-indicator"
data-drop-target={isDropTarget}
className={cn(
'pointer-events-none absolute inset-0.5 z-10 rounded-sm border border-dashed',
isDropTarget === 'valid' ? 'border-primary/50' : 'border-destructive/60',
viewConfig.classNames?.dropIndicator,
)}
/>
)}
</div>
);
}
function EventCalendarResourceColumn({
resource,
day,
startHour,
endHour,
interval,
}: {
resource: EventCalendarResource;
day: Date;
startHour: number;
endHour: number;
interval: number;
}) {
const settings = useEventCalendarSettings();
const viewConfig = useEventCalendarViewConfig();
const { effective } = useEventCalendarViewSettings();
const gestures = useEventCalendarGestures();
const { segments, isToday } = useEventCalendarDay(day);
const isOff = resolveOffDay(
day,
settings.timeZone,
effective.offDays ? (typeof viewConfig.offDays === 'object' ? viewConfig.offDays : true) : false,
settings.weekendDays,
);
const offClassName = (typeof viewConfig.offDays === 'object' && viewConfig.offDays.className) || 'bg-muted/25';
const timeZone = settings.timeZone;
const dayStart = zonedStartOfDay(day, timeZone);
const totalMinutes = getDayTotalMinutes(day, timeZone);
const boundsStartMin = startHour * 60;
const boundsEndMin = Math.min(endHour * 60, totalMinutes);
const boundsMinutes = Math.max(60, boundsEndMin - boundsStartMin);
// Filter this resource's timed segments and repack per column.
// Clones keep the shared index cache untouched. Segments the day bounds clip
// away are dropped here too, otherwise they hold a column nobody can see and
// leave a phantom empty half beside the first in-bounds chip.
const packed = useMemo(() => {
const mine = segments.timed
.filter((segment) => {
if (segment.occurrence.event.resourceId !== resource.id) return false;
const startMin = Math.max(segment.startMin ?? 0, boundsStartMin);
const endMin = Math.min(segment.endMin ?? startMin, boundsEndMin);
return endMin > boundsStartMin && startMin < boundsEndMin;
})
.map((segment) => ({ ...segment }) as EventCalendarSegment);
packTimedSegments(mine);
return mine;
}, [segments.timed, resource.id, boundsStartMin, boundsEndMin]);
const dragGhost = useEventCalendarSelector<
unknown,
{
window: [number, number];
valid: boolean;
kind: string;
color?: string;
title: string;
occurrence: EventCalendarSegment['occurrence'];
proposedStart: Date;
proposedEnd: Date;
} | null
>(
(state) => {
const drag = state.drag;
if (!drag || drag.proposedDayGranular) return null;
// Moves carry a proposedResourceId (they can cross columns); resizes stay
// in place and leave it undefined, so fall back to the event's own
// resource - otherwise the resize ghost is filtered out of every column.
const targetResourceId = drag.proposedResourceId ?? drag.occurrence.event.resourceId;
if (targetResourceId !== resource.id) return null;
const from = Math.max((drag.proposedStart.getTime() - dayStart.getTime()) / 60000, boundsStartMin);
const to = Math.min((drag.proposedEnd.getTime() - dayStart.getTime()) / 60000, boundsEndMin);
if (to <= from) return null;
return {
window: [from, to] as [number, number],
valid: drag.valid,
kind: drag.kind,
color: drag.occurrence.event.color,
title: drag.occurrence.event.title,
occurrence: drag.occurrence,
proposedStart: drag.proposedStart,
proposedEnd: drag.proposedEnd,
};
},
{
isEqual: (a, b) =>
a === b ||
(a !== null &&
b !== null &&
a.window[0] === b.window[0] &&
a.window[1] === b.window[1] &&
a.valid === b.valid &&
a.proposedStart.getTime() === b.proposedStart.getTime() &&
a.proposedEnd.getTime() === b.proposedEnd.getTime()),
},
);
// Instants behind `draftWindow` below, for the range readout. Same
// resource filter, so a draft on a neighbouring resource never labels this
// column.
const draftRange = useEventCalendarSelector<unknown, { start: Date; end: Date } | null>(
(state) => {
const draft = state.slotDraft;
if (!draft || draft.allDay || draft.resourceId !== resource.id) {
return null;
}
return { start: draft.start, end: draft.end };
},
{
isEqual: (a, b) => a === b || (a !== null && b !== null && a.start.getTime() === b.start.getTime() && a.end.getTime() === b.end.getTime()),
},
);
const draftWindow = useEventCalendarSelector<unknown, [number, number] | null>(
(state) => {
const draft = state.slotDraft;
if (!draft || draft.allDay || draft.resourceId !== resource.id) {
return null;
}
const from = Math.max((draft.start.getTime() - dayStart.getTime()) / 60000, boundsStartMin);
const to = Math.min((draft.end.getTime() - dayStart.getTime()) / 60000, boundsEndMin);
return to > from ? [from, to] : null;
},
{
isEqual: (a, b) => a === b || (a !== null && b !== null && a[0] === b[0] && a[1] === b[1]),
},
);
return (
<div
data-slot="event-calendar-day-column"
data-today={isToday || undefined}
data-off={isOff || undefined}
data-ec-day={dayStart.getTime()}
data-ec-bounds-start={boundsStartMin}
data-ec-bounds-end={boundsEndMin}
data-ec-resource={resource.id}
data-drop-target={dragGhost ? (dragGhost.valid ? 'valid' : 'invalid') : undefined}
role="group"
aria-label={resource.title}
className={cn(
'relative min-w-0 border-e last:border-e-0',
isOff && offClassName,
// the resource view is a single day, so today gets no column tint (the
// header marks it); only a consumer todayClassName can tint it
isToday && viewConfig.todayClassName,
viewConfig.dayClassName?.(day),
viewConfig.classNames?.dayColumn,
)}
style={{
height: `calc(var(--ec-hour-height) * ${boundsMinutes / 60})`,
backgroundImage: `repeating-linear-gradient(to bottom, transparent, transparent calc(var(--ec-hour-height) * ${interval / 60} - var(--ec-slot-line-width, 1px)), var(--ec-slot-line-color, var(--color-border)) calc(var(--ec-hour-height) * ${interval / 60} - var(--ec-slot-line-width, 1px)), var(--ec-slot-line-color, var(--color-border)) calc(var(--ec-hour-height) * ${interval / 60}))`,
}}
onPointerDown={(e) => {
if (e.target === e.currentTarget) gestures.beginCreate(e, day, false);
}}
onClick={(e) => {
if (e.target !== e.currentTarget || wasRecentDrag() || wasRecentChipPress()) return;
const rect = e.currentTarget.getBoundingClientRect();
const pxPerMinute = rect.height / boundsMinutes;
const minutes = snapMinutes(boundsStartMin + (e.clientY - rect.top) / pxPerMinute, settings.snapDuration);
const clamped = Math.min(Math.max(minutes, boundsStartMin), boundsEndMin - settings.slotDuration);
settings.onSlotClick?.(
{
date: addMinutes(dayStart, clamped),
end: addMinutes(dayStart, clamped + settings.slotDuration),
allDay: false,
view: 'resource',
resourceId: resource.id,
},
e,
);
}}
>
{packed.map((segment) => {
const startMin = Math.max(segment.startMin ?? 0, boundsStartMin);
const endMin = Math.min(segment.endMin ?? startMin, boundsEndMin);
if (endMin <= boundsStartMin || startMin >= boundsEndMin) return null;
const columnCount = segment.columnCount ?? 1;
const column = segment.column ?? 0;
const span = segment.columnSpan ?? 1;
const zIndex = segment.occurrence.event.zIndex ?? 10 + column;
// Strict side-by-side columns - no cascade overlap (fade-truncate +
// hover reveal carry the legibility); the ring separates neighbors.
return (
<div
key={segment.occurrence.key}
// min-h keeps 15-min chips readable (Google-style: the block may
// slightly outgrow its true window); hover raises a squeezed
// cascade chip above its overlapping neighbors
className="absolute z-(--ec-z) min-h-(--ec-event-min-h,1.5rem) px-0.5 hover:z-40"
style={
{
...minuteBlockStyle(startMin, endMin, boundsStartMin),
left: `calc(${EVENT_TRACK_WIDTH} * ${column / columnCount})`,
width: `calc(${EVENT_TRACK_WIDTH} * ${span / columnCount})`,
'--ec-z': zIndex,
} as CSSProperties
}
>
<EventCalendarEvent
segment={segment}
className={cn(
columnCount > 1 && 'ring-background ring-1',
// short chips: single centered row, exact-fit line height so
// the title never slices mid-glyph
endMin - startMin < viewConfig.compactEventMinutes
? 'h-full gap-1 py-0 leading-4'
: 'h-full flex-col items-start justify-start gap-0 py-1',
viewConfig.classNames?.timedChip,
)}
/>
</div>
);
})}
{/* Standardized ghost (EVENT_CALENDAR_GHOST): faint drop placeholder
for moves (the cursor-attached carry clone owns the visual), dashed
clone for resizes, destructive marking when invalid. */}
{dragGhost && (
<div
data-slot="event-calendar-drag-ghost"
data-kind={dragGhost.kind}
data-drop-invalid={!dragGhost.valid || undefined}
className={cn(
'pointer-events-none absolute inset-x-0.5 z-50 min-h-(--ec-event-min-h,1.5rem)',
dragGhost.kind === 'move'
? cn(EVENT_CALENDAR_GHOST.move, !dragGhost.valid && EVENT_CALENDAR_GHOST.invalid)
: cn(EVENT_CALENDAR_GHOST.resize, !dragGhost.valid && EVENT_CALENDAR_GHOST.invalidResize),
viewConfig.classNames?.dragGhost,
)}
style={
{
...minuteBlockStyle(dragGhost.window[0], dragGhost.window[1], boundsStartMin),
'--ec-event-color': dragGhost.color ?? 'var(--color-primary)',
} as CSSProperties
}
>
{dragGhost.kind !== 'move' && (
<EventCalendarEvent
preview
segment={{
occurrence: {
...dragGhost.occurrence,
start: dragGhost.proposedStart,
end: dragGhost.proposedEnd,
allDay: false,
},
day,
isStart: true,
isEnd: true,
continuesBefore: false,
continuesAfter: false,
startMin: dragGhost.window[0],
endMin: dragGhost.window[1],
}}
className={cn(
dragGhost.window[1] - dragGhost.window[0] < viewConfig.compactEventMinutes
? 'h-full gap-1 py-0 leading-4'
: 'h-full flex-col items-start justify-start gap-0 py-1',
viewConfig.classNames?.timedChip,
'inset-ring-0',
!dragGhost.valid && EVENT_CALENDAR_GHOST.invalidContent,
)}
/>
)}
</div>
)}
{draftWindow && (
<div
data-slot="event-calendar-slot-draft"
className={cn(
EVENT_CALENDAR_SLOT_DRAFT.box,
'pointer-events-none absolute inset-x-0.5 z-40 overflow-hidden',
viewConfig.classNames?.slotDraft,
)}
style={minuteBlockStyle(draftWindow[0], draftWindow[1], boundsStartMin)}
>
{draftRange && (
<span className={cn('block', EVENT_CALENDAR_SLOT_DRAFT.label)}>
{settings.i18n.functions.formatEventTime(
toZoned(draftRange.start, settings.timeZone),
toZoned(draftRange.end, settings.timeZone),
false,
{ locale: settings.locale },
)}
</span>
)}
</div>
)}
</div>
);
}
export { EventCalendarResourceView };
export type { EventCalendarResourceViewProps };'use client';
import { useEffect, useMemo, useRef, useState, type CSSProperties, type ReactNode } from 'react';
import {
EventCalendarViewContext,
useEventCalendar,
useEventCalendarDay,
useEventCalendarSelector,
useEventCalendarSettings,
useEventCalendarViewConfig,
useEventCalendarViewContext,
useEventCalendarViewSettings,
} from '@/registry/vcare/ui/event-calendar/event-calendar';
import { useEventCalendarGestures, wasRecentChipPress, wasRecentDrag } from '@/registry/vcare/ui/event-calendar/event-calendar-dnd';
import { EVENT_CALENDAR_GHOST, EVENT_CALENDAR_SLOT_DRAFT, EventCalendarEvent } from '@/registry/vcare/ui/event-calendar/event-calendar-event';
import {
getDayKey,
getDayTotalMinutes,
getRangeKey,
packTimedSegments,
resolveOffDay,
snapMinutes,
toZoned,
zonedStartOfDay,
} from '@/registry/vcare/ui/event-calendar/event-calendar-lib';
import type {
CalendarView,
EventCalendarDateRange,
EventCalendarDragState,
EventCalendarSegment,
EventCalendarSlotDraft,
} from '@/registry/vcare/ui/event-calendar/event-calendar-types';
import { mergeProps } from '@base-ui/react/merge-props';
import { useRender } from '@base-ui/react/use-render';
import { addDays, addMinutes, differenceInMinutes, format } from 'date-fns';
import { cn } from '@/registry/vcare/lib/utils';
import { ScrollArea } from '@/registry/vcare/ui/scroll-area';
/** Current time, refreshed on an interval and on tab focus. */
function useNow(intervalMs = 30_000): Date {
const [now, setNow] = useState(() => new Date());
useEffect(() => {
const tick = () => setNow(new Date());
const id = setInterval(tick, intervalMs);
document.addEventListener('visibilitychange', tick);
window.addEventListener('focus', tick);
return () => {
clearInterval(id);
document.removeEventListener('visibilitychange', tick);
window.removeEventListener('focus', tick);
};
}, [intervalMs]);
return now;
}
const EMPTY_ALL_DAY_SEGMENTS: EventCalendarSegment[] = [];
interface EventCalendarTimeGridProps extends useRender.ComponentProps<'div'> {
view: Extract<CalendarView, 'week' | 'day' | 'days'>;
dayStartHour?: number;
dayEndHour?: number;
showAllDay?: boolean;
/** Gutter/gridline interval in minutes; defaults to the interval view config. */
interval?: number;
}
function EventCalendarTimeGrid({
view,
className,
render,
dayStartHour,
dayEndHour,
showAllDay = true,
interval: intervalProp,
...props
}: EventCalendarTimeGridProps) {
const instance = useEventCalendar();
const settings = useEventCalendarSettings();
const viewConfig = useEventCalendarViewConfig();
const visibleRange = useEventCalendarSelector<unknown, EventCalendarDateRange>((state) => state.visibleRange, {
isEqual: (a, b) => getRangeKey(a) === getRangeKey(b),
});
const startHour = dayStartHour ?? settings.dayStartHour;
const endHour = dayEndHour ?? settings.dayEndHour;
const interval = Math.min(Math.max(intervalProp ?? viewConfig.interval, 5), 240);
const contained = viewConfig.scrollMode !== 'page';
const { effective } = useEventCalendarViewSettings();
const days = useMemo(() => {
const result: Date[] = [];
let cursor = zonedStartOfDay(visibleRange.start, settings.timeZone);
while (cursor < visibleRange.end) {
result.push(cursor);
cursor = zonedStartOfDay(addDays(toZoned(cursor, settings.timeZone), 1), settings.timeZone);
}
if (effective.weekends || view === 'day') return result;
// Same weekend definition the month view filters on, so the toggle cannot
// hide one set of days here and another one there.
const filtered = result.filter((day) => !settings.weekendDays.includes(toZoned(day, settings.timeZone).getDay()));
// A short N-days window landing entirely on the weekend would otherwise
// filter to nothing and emit an invalid repeat(0, ...) track.
return filtered.length ? filtered : result;
}, [visibleRange, settings.timeZone, settings.weekendDays, effective.weekends, view]);
// Initial scroll to scrollToHour + api.scrollToTime registration (contained)
const scrollRef = useRef<HTMLDivElement | null>(null);
useEffect(() => {
if (!contained) return;
const el = scrollRef.current;
if (!el) return;
const viewport = el.querySelector<HTMLElement>('[data-slot=scroll-area-viewport]');
// Measure a rendered slot row - the CSS var is in rem, rects are in px.
const slotRow = el.querySelector<HTMLElement>('[data-slot=event-calendar-time-gutter] > div');
const slotPx = slotRow?.getBoundingClientRect().height || 64;
const pxPerMinute = slotPx / interval;
const scrollTo = (minutes: number) => {
// keep the hour label above the target line visible (it hangs -top-2)
viewport?.scrollTo({
top: Math.max(0, (minutes - startHour * 60) * pxPerMinute - 12),
});
};
scrollTo(viewConfig.scrollToHour * 60);
instance.internals.registerScrollHandler((time) => {
const minutes =
typeof time === 'number' ? time : toZoned(time, settings.timeZone).getHours() * 60 + toZoned(time, settings.timeZone).getMinutes();
scrollTo(minutes);
});
// Classic (width-consuming) scrollbars squeeze the scrolling track while
// the header/all-day rows outside keep full width, drifting the column
// borders. Mirror the measured gutter onto those rows via a CSS var -
// 0px for overlay scrollbars and the custom ScrollArea, so both modes
// lay out identically.
const root = el.closest<HTMLElement>('[data-slot=event-calendar-time-grid], [data-slot=event-calendar-resource-view]');
const syncScrollbarGutter = () => {
root?.style.setProperty('--ec-scrollbar-w', `${viewport ? viewport.offsetWidth - viewport.clientWidth : 0}px`);
};
syncScrollbarGutter();
const gutterObserver = viewport ? new ResizeObserver(syncScrollbarGutter) : null;
if (viewport) gutterObserver?.observe(viewport);
return () => {
instance.internals.registerScrollHandler(null);
gutterObserver?.disconnect();
};
}, [
contained,
instance,
settings.timeZone,
startHour,
interval,
viewConfig.scrollToHour,
// scrollbars custom<->native swaps the scroller DOM: re-bind the
// viewport, the scroll wiring, and the measured --ec-scrollbar-w
viewConfig.scrollbars,
]);
// Gutter slots in minutes from the zoned day start
const slots = useMemo(() => {
const result: number[] = [];
for (let m = startHour * 60; m < endHour * 60; m += interval) {
result.push(m);
}
return result;
}, [startHour, endHour, interval]);
// Section-level all-day segments for renderAllDaySection - reads the same
// per-day index buckets the cells subscribe to; inert (stable empty array,
// so the subscription never re-renders) while the override is unset.
const allDaySegments = useEventCalendarSelector<unknown, EventCalendarSegment[]>(
() => {
if (!viewConfig.renderAllDaySection) return EMPTY_ALL_DAY_SEGMENTS;
const byDay = instance.internals.getIndex().byDay;
const result = days.flatMap((day) => byDay.get(getDayKey(day, settings.timeZone))?.allDay ?? []);
return result.length ? result : EMPTY_ALL_DAY_SEGMENTS;
},
{
isEqual: (a, b) => a === b || (a.length === b.length && a.every((segment, i) => segment === b[i])),
},
);
const gridTemplateColumns = `repeat(${days.length}, minmax(var(--ec-day-col-min,0px), 1fr))`;
const track = (
<div className="relative flex">
<EventCalendarTimeGutter days={days} slots={slots} startHour={startHour} interval={interval} />
<div className="grid min-w-0 flex-1" style={{ gridTemplateColumns }}>
{days.map((day) => (
<EventCalendarDayColumn key={day.getTime()} day={day} startHour={startHour} endHour={endHour} interval={interval} />
))}
</div>
{effective.nowIndicator && <EventCalendarNowIndicator days={days} startHour={startHour} endHour={endHour} />}
</div>
);
const defaultProps = {
'data-slot': 'event-calendar-time-grid',
'data-view': view,
className: cn('flex flex-col border-t', contained && 'min-h-0 flex-1 overflow-hidden', viewConfig.classNames?.timeGrid, className),
style: { '--ec-hour-height': '4rem' } as CSSProperties,
children: (
<>
{/* Day-header row (sticky below the nav in page scroll mode) */}
<div
className={cn(
'flex border-b pe-(--ec-scrollbar-w,0px)',
!contained && 'bg-background sticky top-(--ec-sticky-offset,0px) z-20',
viewConfig.classNames?.timeGridHeader,
)}
>
<div className="w-(--ec-gutter-width,4.5rem) shrink-0 border-e" />
<div className="grid min-w-0 flex-1" style={{ gridTemplateColumns }}>
{days.map((day) => (
<EventCalendarDayHeader key={day.getTime()} day={day} view={view} />
))}
</div>
</div>
{/* All-day row */}
{showAllDay && (
<div
data-slot="event-calendar-all-day-section"
className={cn('flex border-b pe-(--ec-scrollbar-w,0px)', viewConfig.classNames?.allDaySection)}
>
{viewConfig.renderAllDaySection?.({
days,
segments: allDaySegments,
}) ?? (
<>
<div
className={cn(
// pt-1.5 matches the bar overlay's top inset; the inner box
// is one bar-row tall and centers the label so it sits on
// the SAME baseline as the first all-day chip and stays top-
// aligned when the chips wrap onto more lanes
'text-muted-foreground w-(--ec-gutter-width,4.5rem) shrink-0 border-e ps-2 pe-2.5 pt-1.5',
viewConfig.classNames?.allDayLabel,
)}
>
<span className="flex h-[calc(var(--ec-month-bar-h,1.625rem)-0.125rem)] items-center justify-end">
{settings.i18n.labels.allDay}
</span>
</div>
<EventCalendarAllDayBars days={days} gridTemplateColumns={gridTemplateColumns} />
</>
)}
</div>
)}
{/* Time track: internal scroll (contained) or document flow (page) */}
{contained ? (
<div ref={scrollRef} className="min-h-0 flex-1">
{viewConfig.scrollbars === 'native' ? (
<div data-slot="scroll-area-viewport" data-ec-native-scroll="" className="h-full overflow-y-auto">
{track}
</div>
) : (
<ScrollArea className="h-full">{track}</ScrollArea>
)}
</div>
) : (
track
)}
</>
),
};
return (
<EventCalendarViewContext.Provider value={{ view }}>
{useRender({
defaultTagName: 'div',
render,
props: mergeProps<'div'>(defaultProps, props),
})}
</EventCalendarViewContext.Provider>
);
}
function EventCalendarDayHeader({ day, view }: { day: Date; view: CalendarView }) {
const settings = useEventCalendarSettings();
const viewConfig = useEventCalendarViewConfig();
const { isToday } = useEventCalendarDay(day);
return (
<div
data-slot="event-calendar-day-header"
data-today={isToday || undefined}
className={cn(
'data-today:text-primary min-w-0 truncate border-e px-2 py-1.5 font-medium last:border-e-0',
isToday && viewConfig.todayClassName,
)}
>
{viewConfig.renderDayHeader?.({ day, view, isToday }) ??
format(toZoned(day, settings.timeZone), settings.i18n.formats.timeGridDayHeader, { locale: settings.locale })}
</div>
);
}
/**
* Continuous all-day bars for the week/N-days all-day row: consecutive-day
* segments of one occurrence merge into a single bar spanning its columns
* (same treatment as the month view), lane-packed. Returns CLONED segments -
* the shared per-day segments must stay pristine (see packWeekRowLanes).
*/
function useEventCalendarAllDayBars(days: Date[]): {
bars: EventCalendarSegment[];
laneCount: number;
} {
const instance = useEventCalendar();
const settings = useEventCalendarSettings();
return useEventCalendarSelector<unknown, { bars: EventCalendarSegment[]; laneCount: number }>(
() => {
const byDay = instance.internals.getIndex().byDay;
type Bar = {
seg: EventCalendarSegment;
colStart: number;
colEnd: number;
isStart: boolean;
isEnd: boolean;
lane: number;
};
const merged = new Map<string, Bar>();
days.forEach((day, col) => {
for (const seg of byDay.get(getDayKey(day, settings.timeZone))?.allDay ?? []) {
const key = seg.occurrence.key;
const bar = merged.get(key);
if (bar) {
bar.colEnd = col;
bar.isEnd = seg.isEnd;
} else {
merged.set(key, {
seg,
colStart: col,
colEnd: col,
isStart: seg.isStart,
isEnd: seg.isEnd,
lane: 0,
});
}
}
});
const packed = Array.from(merged.values()).sort(
(a, b) =>
a.colStart - b.colStart || b.colEnd - b.colStart - (a.colEnd - a.colStart) || a.seg.occurrence.key.localeCompare(b.seg.occurrence.key),
);
const lanes: boolean[][] = [];
for (const bar of packed) {
let lane = 0;
for (;;) {
lanes[lane] ??= new Array(days.length).fill(false);
let free = true;
for (let c = bar.colStart; c <= bar.colEnd; c++) {
if (lanes[lane][c]) {
free = false;
break;
}
}
if (free) break;
lane++;
}
for (let c = bar.colStart; c <= bar.colEnd; c++) lanes[lane][c] = true;
bar.lane = lane;
}
return {
bars: packed.map((bar) => ({
...bar.seg,
isStart: bar.isStart,
isEnd: bar.isEnd,
continuesBefore: !bar.isStart,
continuesAfter: !bar.isEnd,
colStart: bar.colStart,
colSpan: bar.colEnd - bar.colStart + 1,
lane: bar.lane,
})),
laneCount: lanes.length,
};
},
{
calendar: instance,
isEqual: (a, b) =>
a.laneCount === b.laneCount &&
a.bars.length === b.bars.length &&
a.bars.every((s, i) => {
const o = b.bars[i];
// Compare the OCCURRENCE by identity, not by key: the key encodes
// id+start only, so a title/color/data edit compared equal and the
// all-day row kept its stale bars. Occurrences come from the
// memoized index (rebuilt exactly when events change), so identity
// also subsumes the end-time check it replaces. The positional
// fields stay because they are recomputed on every read.
return (
s.occurrence === o.occurrence &&
s.colStart === o.colStart &&
s.colSpan === o.colSpan &&
s.lane === o.lane &&
s.isStart === o.isStart &&
s.isEnd === o.isEnd
);
}),
},
);
}
/**
* The all-day row body: drop-target cells underneath, one continuous bar per
* occurrence in an overlay grid on top (month-view treatment), plus the
* standardized day-granular drag ghost for moves/resizes in this lane.
*/
function EventCalendarAllDayBars({ days, gridTemplateColumns }: { days: Date[]; gridTemplateColumns: string }) {
const settings = useEventCalendarSettings();
const viewConfig = useEventCalendarViewConfig();
const { bars, laneCount } = useEventCalendarAllDayBars(days);
const dragGhost = useEventCalendarSelector<
unknown,
| (Pick<EventCalendarDragState, 'kind' | 'valid' | 'occurrence' | 'proposedStart' | 'proposedEnd'> & {
colStart: number;
colSpan: number;
isStart: boolean;
isEnd: boolean;
color?: string;
})
| null
>(
(state) => {
const drag = state.drag;
if (!drag || !drag.proposedDayGranular) return null;
const tz = settings.timeZone;
const startMs = zonedStartOfDay(drag.proposedStart, tz).getTime();
const lastMs = zonedStartOfDay(new Date(drag.proposedEnd.getTime() - 1), tz).getTime();
let colStart = -1;
let colEnd = -1;
days.forEach((day, i) => {
const t = zonedStartOfDay(day, tz).getTime();
if (t >= startMs && t <= lastMs) {
if (colStart === -1) colStart = i;
colEnd = i;
}
});
if (colStart === -1) return null;
return {
kind: drag.kind,
valid: drag.valid,
occurrence: drag.occurrence,
proposedStart: drag.proposedStart,
proposedEnd: drag.proposedEnd,
colStart,
colSpan: colEnd - colStart + 1,
isStart: zonedStartOfDay(days[colStart], tz).getTime() <= startMs,
isEnd: zonedStartOfDay(days[colEnd], tz).getTime() >= lastMs,
color: drag.occurrence.event.color,
};
},
{
isEqual: (a, b) =>
a === b ||
(a !== null &&
b !== null &&
a.colStart === b.colStart &&
a.colSpan === b.colSpan &&
a.valid === b.valid &&
a.kind === b.kind &&
a.proposedStart.getTime() === b.proposedStart.getTime() &&
a.proposedEnd.getTime() === b.proposedEnd.getTime()),
},
);
const ghostLane = dragGhost ? (bars.find((s) => s.occurrence.key === dragGhost.occurrence.key)?.lane ?? laneCount) : 0;
const effectiveLanes = Math.max(laneCount, dragGhost ? ghostLane + 1 : 0);
return (
<div className="relative min-w-0 flex-1">
<div
className="grid h-full"
style={{
gridTemplateColumns,
// always reserve at least one bar row so the all-day row keeps the
// same height whether or not the day has all-day events (an empty
// row would otherwise collapse to the label height and misalign)
minHeight: `calc(${Math.max(effectiveLanes, 1)} * var(--ec-month-bar-h, 1.625rem) + 0.625rem)`,
}}
>
{days.map((day) => (
<EventCalendarAllDayCell key={day.getTime()} day={day} />
))}
</div>
{(bars.length > 0 || dragGhost) && (
<div
data-slot="event-calendar-all-day-bar-overlay"
className="pointer-events-none absolute inset-x-0 top-0 grid pt-1.5"
style={{
gridTemplateColumns,
gridAutoRows: 'var(--ec-month-bar-h, 1.625rem)',
}}
>
{bars.map((segment) => (
<div
key={segment.occurrence.key}
className={cn('pointer-events-auto min-w-0 px-1', viewConfig.classNames?.monthBar)}
style={{
gridColumn: `${(segment.colStart ?? 0) + 1} / span ${segment.colSpan ?? 1}`,
gridRow: (segment.lane ?? 0) + 1,
}}
>
<EventCalendarEvent segment={segment} className="h-[calc(var(--ec-month-bar-h,1.625rem)-0.125rem)]" />
</div>
))}
{dragGhost && (
<div
aria-hidden
className={cn('min-w-0 px-1', viewConfig.classNames?.monthBar)}
style={{
gridColumn: `${dragGhost.colStart + 1} / span ${dragGhost.colSpan}`,
gridRow: ghostLane + 1,
}}
>
<div
data-slot="event-calendar-drag-ghost"
data-kind={dragGhost.kind}
data-drop-invalid={!dragGhost.valid || undefined}
className={cn(
'h-[calc(var(--ec-month-bar-h,1.625rem)-0.125rem)]',
dragGhost.kind === 'move'
? cn(EVENT_CALENDAR_GHOST.move, !dragGhost.valid && EVENT_CALENDAR_GHOST.invalid)
: cn(EVENT_CALENDAR_GHOST.resize, !dragGhost.valid && EVENT_CALENDAR_GHOST.invalidResize),
viewConfig.classNames?.dragGhost,
)}
style={
{
'--ec-event-color': dragGhost.color ?? 'var(--color-primary)',
} as CSSProperties
}
>
{dragGhost.kind !== 'move' && (
<EventCalendarEvent
preview
segment={{
occurrence: {
...dragGhost.occurrence,
start: dragGhost.proposedStart,
end: dragGhost.proposedEnd,
},
day: days[dragGhost.colStart] ?? days[0],
isStart: dragGhost.isStart,
isEnd: dragGhost.isEnd,
continuesBefore: !dragGhost.isStart,
continuesAfter: !dragGhost.isEnd,
}}
className={cn('h-full inset-ring-0', !dragGhost.valid && EVENT_CALENDAR_GHOST.invalidContent)}
/>
)}
</div>
</div>
)}
</div>
)}
</div>
);
}
function EventCalendarAllDayCell({ day }: { day: Date }) {
const settings = useEventCalendarSettings();
const viewConfig = useEventCalendarViewConfig();
const { view } = useEventCalendarViewContext();
const { effective } = useEventCalendarViewSettings();
const gestures = useEventCalendarGestures();
const dayStart = zonedStartOfDay(day, settings.timeZone);
const dayEnd = addDays(toZoned(dayStart, settings.timeZone), 1);
const isOff = resolveOffDay(
day,
settings.timeZone,
effective.offDays ? (typeof viewConfig.offDays === 'object' ? viewConfig.offDays : true) : false,
settings.weekendDays,
);
const offClassName = (typeof viewConfig.offDays === 'object' && viewConfig.offDays.className) || 'bg-muted/25';
const isDropTarget = useEventCalendarSelector<unknown, 'valid' | 'invalid' | null>((state) => {
const drag = state.drag;
if (!drag || !drag.proposedDayGranular) return null;
const covered = drag.proposedStart < dayEnd && drag.proposedEnd > dayStart;
if (!covered) return null;
return drag.valid ? 'valid' : 'invalid';
});
const inDraft = useEventCalendarSelector<unknown, { isStart: boolean; isEnd: boolean } | null>(
(state) => {
const draft = state.slotDraft;
if (!draft || !draft.allDay) return null;
if (draft.start >= dayEnd || draft.end <= dayStart) return null;
return {
isStart: draft.start >= dayStart,
isEnd: draft.end <= dayEnd,
};
},
{
isEqual: (a, b) => a === b || (a !== null && b !== null && a.isStart === b.isStart && a.isEnd === b.isEnd),
},
);
// All-day drags select whole DAYS, so this row reads a date range, matching
// the month grid. Without it, dragging the all-day strip in week view would
// be the one create gesture in the calendar with no readout at all.
const allDayDraftRange = useEventCalendarSelector<unknown, { start: Date; end: Date } | null>(
(state) => {
const draft = state.slotDraft;
if (!draft || !draft.allDay) return null;
return { start: draft.start, end: draft.end };
},
{
isEqual: (a, b) => a === b || (a !== null && b !== null && a.start.getTime() === b.start.getTime() && a.end.getTime() === b.end.getTime()),
},
);
return (
<div
data-slot="event-calendar-all-day-cell"
data-ec-day={dayStart.getTime()}
data-drop-target={isDropTarget ?? undefined}
data-off={isOff || undefined}
className={cn(
'relative flex min-w-0 flex-col gap-0.5 border-e px-1 py-1.5 last:border-e-0',
isOff && offClassName,
viewConfig.dayClassName?.(day),
// No drop-target bg fill on move/resize (see month view) - a subtle
// dashed inset outline below marks the target instead.
inDraft &&
cn(
EVENT_CALENDAR_SLOT_DRAFT.surface,
EVENT_CALENDAR_SLOT_DRAFT.segment,
inDraft.isStart && EVENT_CALENDAR_SLOT_DRAFT.segmentStart,
inDraft.isEnd && EVENT_CALENDAR_SLOT_DRAFT.segmentEnd,
viewConfig.classNames?.slotDraft,
),
viewConfig.classNames?.allDayCell,
)}
onPointerDown={(e) => {
if (e.target === e.currentTarget) gestures.beginCreate(e, day, true);
}}
onClick={(e) => {
if (e.target === e.currentTarget && !wasRecentDrag() && !wasRecentChipPress()) {
settings.onSlotClick?.({ date: dayStart, allDay: true, view }, e);
}
}}
>
{/* Only on the first cell of the selection, same rule as the month grid,
so a three-day all-day drag labels itself once rather than three
times. pointer-events-none keeps the cell's own pointerdown guard
(`e.target === e.currentTarget`) intact. */}
{inDraft?.isStart && allDayDraftRange && (
<span aria-hidden className={cn('pointer-events-none absolute inset-x-1 top-1/2 -translate-y-1/2', EVENT_CALENDAR_SLOT_DRAFT.label)}>
{settings.i18n.functions.formatDayRange(
{
start: toZoned(allDayDraftRange.start, settings.timeZone),
end: toZoned(allDayDraftRange.end, settings.timeZone),
},
{ locale: settings.locale },
)}
</span>
)}
</div>
);
}
function EventCalendarTimeGutter({ days, slots, startHour, interval }: { days: Date[]; slots: number[]; startHour: number; interval: number }) {
const settings = useEventCalendarSettings();
const viewConfig = useEventCalendarViewConfig();
const referenceDay = days[0] ?? new Date();
const labelFormat = interval % 60 === 0 ? settings.i18n.formats.timeGutter : settings.i18n.formats.timeGutterMinute;
return (
<div
data-slot="event-calendar-time-gutter"
className={cn('relative w-(--ec-gutter-width,4.5rem) shrink-0 border-e', viewConfig.classNames?.timeGutter)}
>
{slots.map((minutes) => {
const time = addMinutes(zonedStartOfDay(referenceDay, settings.timeZone), minutes);
// Always consult renderTimeGutterSlot (a consumer may label the first
// slot); only the DEFAULT label is suppressed at the day-start edge.
const label =
viewConfig.renderTimeGutterSlot?.({
time,
hour: Math.floor(minutes / 60),
minute: minutes % 60,
}) ?? (minutes > startHour * 60 ? format(time, labelFormat, { locale: settings.locale }) : null);
return (
<div key={minutes} className="relative" style={{ height: `calc(var(--ec-hour-height) * ${interval / 60})` }}>
{label != null && (
<span className={cn('text-muted-foreground absolute end-2.5 -top-2', viewConfig.classNames?.timeGutterLabel)}>{label}</span>
)}
</div>
);
})}
</div>
);
}
/**
* Inline size of the timed-block track. It stops short of the day column's end
* edge so the bare strip beside a full-width block is still the column itself,
* and a press there reaches the column's own create handler - the empty space
* Google Calendar and Notion Calendar both reserve for "new event next to this
* one". Consumers opt out with classNames.dayColumn: "[--ec-event-gutter:0px]".
*/
const EVENT_TRACK_WIDTH = '(100% - var(--ec-event-gutter, 0.75rem))';
/** Absolute overlay block positioned by minutes (ghosts + drafts). */
function minuteBlockStyle(startMin: number, endMin: number, boundsStartMin: number): CSSProperties {
const top = (startMin - boundsStartMin) / 60;
const height = Math.max((endMin - startMin) / 60, 0.25);
return {
top: `calc(var(--ec-hour-height) * ${top})`,
height: `calc(var(--ec-hour-height) * ${height})`,
};
}
function EventCalendarDayColumn({ day, startHour, endHour, interval }: { day: Date; startHour: number; endHour: number; interval: number }) {
const settings = useEventCalendarSettings();
const viewConfig = useEventCalendarViewConfig();
const { effective } = useEventCalendarViewSettings();
const { view } = useEventCalendarViewContext();
const gestures = useEventCalendarGestures();
const { segments, isToday } = useEventCalendarDay(day);
const isOff = resolveOffDay(
day,
settings.timeZone,
effective.offDays ? (typeof viewConfig.offDays === 'object' ? viewConfig.offDays : true) : false,
settings.weekendDays,
);
const offClassName = (typeof viewConfig.offDays === 'object' && viewConfig.offDays.className) || 'bg-muted/25';
const timeZone = settings.timeZone;
const dayStart = zonedStartOfDay(day, timeZone);
const dayEnd = addDays(toZoned(dayStart, timeZone), 1);
const totalMinutes = getDayTotalMinutes(day, timeZone);
const boundsStartMin = startHour * 60;
const boundsEndMin = Math.min(endHour * 60, totalMinutes);
const boundsMinutes = Math.max(60, boundsEndMin - boundsStartMin);
// Minute window of a proposal intersecting THIS day, or null
const windowFor = (start: Date, end: Date): [number, number] | null => {
if (start >= dayEnd || end <= dayStart) return null;
const from = Math.max(differenceInMinutes(start > dayStart ? start : dayStart, dayStart), boundsStartMin);
const to = Math.min(differenceInMinutes(end < dayEnd ? end : dayEnd, dayStart), boundsEndMin);
return to > from ? [from, to] : null;
};
const dragGhost = useEventCalendarSelector<
unknown,
| (Pick<EventCalendarDragState, 'valid' | 'kind' | 'occurrence' | 'proposedStart' | 'proposedEnd'> & {
window: [number, number];
color?: string;
title: string;
})
| null
>(
(state) => {
const drag = state.drag;
if (!drag || drag.proposedDayGranular) return null;
const window = windowFor(drag.proposedStart, drag.proposedEnd);
if (!window) return null;
return {
valid: drag.valid,
kind: drag.kind,
occurrence: drag.occurrence,
proposedStart: drag.proposedStart,
proposedEnd: drag.proposedEnd,
window,
color: drag.occurrence.event.color,
title: drag.occurrence.event.title,
};
},
{
isEqual: (a, b) =>
a === b ||
(a !== null &&
b !== null &&
a.window[0] === b.window[0] &&
a.window[1] === b.window[1] &&
a.valid === b.valid &&
a.kind === b.kind &&
a.proposedStart.getTime() === b.proposedStart.getTime() &&
a.proposedEnd.getTime() === b.proposedEnd.getTime()),
},
);
const draftWindow = useEventCalendarSelector<unknown, [number, number] | null>(
(state) => {
const draft = state.slotDraft;
if (!draft || draft.allDay) return null;
return windowFor(draft.start, draft.end);
},
{
isEqual: (a, b) => a === b || (a !== null && b !== null && a[0] === b[0] && a[1] === b[1]),
},
);
// The draft's true instants, kept separate from `draftWindow` above because
// that one is clipped to this column's day bounds - the readout has to show
// what the user actually drew, not the clipped remainder.
const draftRange = useEventCalendarSelector<unknown, { start: Date; end: Date } | null>(
(state) => {
const draft = state.slotDraft;
if (!draft || draft.allDay) return null;
return { start: draft.start, end: draft.end };
},
{
isEqual: (a, b) => a === b || (a !== null && b !== null && a.start.getTime() === b.start.getTime() && a.end.getTime() === b.end.getTime()),
},
);
// Segments the day bounds clip away still occupy a column in the shared
// index's packing, leaving a phantom empty half beside the first in-bounds
// chip. Repack the visible subset; clones keep the index cache untouched.
const packedTimed = useMemo(() => {
const visible = segments.timed.filter((segment) => {
const startMin = Math.max(segment.startMin ?? 0, boundsStartMin);
const endMin = Math.min(segment.endMin ?? startMin, boundsEndMin);
return endMin > boundsStartMin && startMin < boundsEndMin;
});
if (visible.length === segments.timed.length) return segments.timed;
const clones = visible.map((segment) => ({ ...segment }) as EventCalendarSegment);
packTimedSegments(clones);
return clones;
}, [segments.timed, boundsStartMin, boundsEndMin]);
const slotFromPointer = (e: React.MouseEvent): { date: Date; end: Date } => {
const rect = e.currentTarget.getBoundingClientRect();
const pxPerMinute = rect.height / boundsMinutes;
const minutes = snapMinutes(boundsStartMin + (e.clientY - rect.top) / pxPerMinute, settings.snapDuration);
const clamped = Math.min(Math.max(minutes, boundsStartMin), boundsEndMin - settings.slotDuration);
return {
date: addMinutes(dayStart, clamped),
end: addMinutes(dayStart, clamped + settings.slotDuration),
};
};
return (
<div
data-slot="event-calendar-day-column"
data-today={isToday || undefined}
data-off={isOff || undefined}
data-ec-day={dayStart.getTime()}
data-ec-bounds-start={boundsStartMin}
data-ec-bounds-end={boundsEndMin}
role="group"
aria-label={format(toZoned(day, timeZone), settings.i18n.formats.dayAria, { locale: settings.locale })}
className={cn(
'relative min-w-0 border-e last:border-e-0',
isOff && offClassName,
// time grid keeps today's column on the normal background (the header
// marks today); only a consumer todayClassName can tint it
isToday && viewConfig.todayClassName,
viewConfig.dayClassName?.(day),
viewConfig.classNames?.dayColumn,
)}
style={{
height: `calc(var(--ec-hour-height) * ${boundsMinutes / 60})`,
backgroundImage: `repeating-linear-gradient(to bottom, transparent, transparent calc(var(--ec-hour-height) * ${interval / 60} - var(--ec-slot-line-width, 1px)), var(--ec-slot-line-color, var(--color-border)) calc(var(--ec-hour-height) * ${interval / 60} - var(--ec-slot-line-width, 1px)), var(--ec-slot-line-color, var(--color-border)) calc(var(--ec-hour-height) * ${interval / 60}))`,
}}
onPointerDown={(e) => {
if (e.target === e.currentTarget) gestures.beginCreate(e, day, false);
}}
onClick={(e) => {
if (e.target !== e.currentTarget || wasRecentDrag() || wasRecentChipPress()) return;
const slot = slotFromPointer(e);
settings.onSlotClick?.({ ...slot, allDay: false, view }, e);
}}
>
{viewConfig.renderDayColumnBackground && (
<div className="pointer-events-none absolute inset-0">
{viewConfig.renderDayColumnBackground({
day,
boundsStartMin,
boundsEndMin,
totalMinutes,
})}
</div>
)}
{packedTimed.map((segment) => {
const startMin = Math.max(segment.startMin ?? 0, boundsStartMin);
const endMin = Math.min(segment.endMin ?? startMin, boundsEndMin);
if (endMin <= boundsStartMin || startMin >= boundsEndMin) return null;
const columnCount = segment.columnCount ?? 1;
const column = segment.column ?? 0;
const span = segment.columnSpan ?? 1;
const zIndex = segment.occurrence.event.zIndex ?? 10 + column;
// Strict side-by-side columns - no cascade overlap (fade-truncate +
// hover reveal carry the legibility); the ring separates neighbors.
return (
<div
key={segment.occurrence.key}
// min-h keeps 15-min chips readable (Google-style: the block may
// slightly outgrow its true window); hover raises a squeezed
// cascade chip above its overlapping neighbors
className="absolute z-(--ec-z) min-h-(--ec-event-min-h,1.5rem) px-0.5 hover:z-40"
style={
{
...minuteBlockStyle(startMin, endMin, boundsStartMin),
left: `calc(${EVENT_TRACK_WIDTH} * ${column / columnCount})`,
width: `calc(${EVENT_TRACK_WIDTH} * ${span / columnCount})`,
'--ec-z': zIndex,
} as CSSProperties
}
>
<EventCalendarEvent
segment={segment}
className={cn(
columnCount > 1 && 'ring-background ring-1',
// short chips: single centered row, exact-fit line height so
// the title never slices mid-glyph
endMin - startMin < viewConfig.compactEventMinutes
? 'h-full gap-1 py-0 leading-4'
: 'h-full flex-col items-start justify-start gap-0 py-1',
viewConfig.classNames?.timedChip,
)}
/>
</div>
);
})}
{/* Drag ghost, standardized (EVENT_CALENDAR_GHOST). Move: a faint
dashed placeholder at the snapped slot - the cursor-attached carry
clone owns the visual. Resize: the chip clone with a dashed boundary
at the proposed extent. Invalid: destructive marking. */}
{dragGhost && (
<div
data-slot="event-calendar-drag-ghost"
data-kind={dragGhost.kind}
data-drop-invalid={!dragGhost.valid || undefined}
className={cn(
'pointer-events-none absolute inset-x-0.5 z-50 min-h-(--ec-event-min-h,1.5rem)',
dragGhost.kind === 'move'
? cn(EVENT_CALENDAR_GHOST.move, !dragGhost.valid && EVENT_CALENDAR_GHOST.invalid)
: cn(EVENT_CALENDAR_GHOST.resize, !dragGhost.valid && EVENT_CALENDAR_GHOST.invalidResize),
viewConfig.classNames?.dragGhost,
)}
style={
{
...minuteBlockStyle(dragGhost.window[0], dragGhost.window[1], boundsStartMin),
'--ec-event-color': dragGhost.color ?? 'var(--color-primary)',
} as CSSProperties
}
>
{dragGhost.kind !== 'move' && (
<EventCalendarEvent
preview
segment={{
occurrence: {
...dragGhost.occurrence,
start: dragGhost.proposedStart,
end: dragGhost.proposedEnd,
allDay: false,
},
day,
isStart: true,
isEnd: true,
continuesBefore: false,
continuesAfter: false,
startMin: dragGhost.window[0],
endMin: dragGhost.window[1],
}}
className={cn(
dragGhost.window[1] - dragGhost.window[0] < viewConfig.compactEventMinutes
? 'h-full gap-1 py-0 leading-4'
: 'h-full flex-col items-start justify-start gap-0 py-1',
viewConfig.classNames?.timedChip,
'inset-ring-0',
!dragGhost.valid && EVENT_CALENDAR_GHOST.invalidContent,
)}
/>
)}
</div>
)}
{/* Drag-create draft */}
{draftWindow && (
<div
data-slot="event-calendar-slot-draft"
className={cn(
EVENT_CALENDAR_SLOT_DRAFT.box,
'pointer-events-none absolute inset-x-0.5 z-40 overflow-hidden',
viewConfig.classNames?.slotDraft,
)}
style={minuteBlockStyle(draftWindow[0], draftWindow[1], boundsStartMin)}
>
{/* Live range readout while dragging, the way Outlook and Google
Calendar do it: the entire point of the gesture is to pick a
time, so show the time being picked instead of an empty box.
Reuses `formatEventTime`, the same formatter the chips use, so
locale, time zone and 12/24-hour all match the rest of the
calendar for free. `truncate` plus the wrapper's overflow-hidden
keeps a 15-minute draft from spilling past its own border. */}
{draftRange && (
<span className={cn('block', EVENT_CALENDAR_SLOT_DRAFT.label)}>
{settings.i18n.functions.formatEventTime(toZoned(draftRange.start, timeZone), toZoned(draftRange.end, timeZone), false, {
locale: settings.locale,
})}
</span>
)}
</div>
)}
</div>
);
}
function EventCalendarNowIndicator({ days, startHour, endHour }: { days: Date[]; startHour: number; endHour: number }): ReactNode {
const settings = useEventCalendarSettings();
const viewConfig = useEventCalendarViewConfig();
const now = useNow(viewConfig.nowIndicatorInterval);
const timeZone = settings.timeZone;
const todayKey = getDayKey(now, timeZone);
const todayIndex = days.findIndex((day) => getDayKey(day, timeZone) === todayKey);
if (todayIndex === -1) return null;
const dayStart = zonedStartOfDay(now, timeZone);
const minutes = differenceInMinutes(now, dayStart);
if (minutes < startHour * 60 || minutes > endHour * 60) return null;
const top = minutes / 60 - startHour;
if (viewConfig.renderNowIndicator) {
return (
<div className="pointer-events-none absolute inset-x-0 z-40" style={{ top: `calc(var(--ec-hour-height) * ${top})` }}>
{viewConfig.renderNowIndicator({ time: now })}
</div>
);
}
const columnWidthPct = 100 / days.length;
return (
<div
data-slot="event-calendar-now-indicator"
className="pointer-events-none absolute inset-x-0 z-40"
style={{ top: `calc(var(--ec-hour-height) * ${top})` }}
>
{/* hairline across the content columns only (clear of the time gutter) */}
<div className="bg-destructive/40 absolute start-(--ec-gutter-width,4.5rem) end-0 h-px" />
{/* stronger segment + dot over today's column */}
<div
className="absolute h-px"
style={{
left: `calc(var(--ec-gutter-width, 4.5rem) + (100% - var(--ec-gutter-width, 4.5rem)) * ${(todayIndex * columnWidthPct) / 100})`,
width: `calc((100% - var(--ec-gutter-width, 4.5rem)) * ${columnWidthPct / 100})`,
}}
>
<div className="bg-destructive absolute inset-x-0 top-0 h-px" />
{/* dot leads the line at today's column-start border: pulled 1px left of
center (-start-1 = -4px vs the 6px/size-1.5 circle) so it reads as a
distinct bullet instead of merging into the line to its right */}
<div className="bg-destructive absolute -start-1 top-0 size-1.5 -translate-y-1/2 rounded-full" />
</div>
</div>
);
}
type TimeGridViewProps = Omit<EventCalendarTimeGridProps, 'view'>;
function EventCalendarWeekView(props: TimeGridViewProps) {
return <EventCalendarTimeGrid view="week" {...props} />;
}
function EventCalendarDayView(props: TimeGridViewProps) {
return <EventCalendarTimeGrid view="day" {...props} />;
}
function EventCalendarDaysView(props: TimeGridViewProps) {
return <EventCalendarTimeGrid view="days" {...props} />;
}
export {
EVENT_TRACK_WIDTH,
EventCalendarDayView,
EventCalendarDaysView,
EventCalendarNowIndicator,
EventCalendarTimeGrid,
EventCalendarTimeGutter,
EventCalendarWeekView,
minuteBlockStyle,
useNow,
};
export type { EventCalendarTimeGridProps };type EventCalendarEventId = string;
type CalendarView = 'month' | 'week' | 'day' | 'days' | 'agenda' | 'resource';
/** Bookable resource. The resource view flattens children and renders leaves
* only, as booking columns; a parent's own title never renders. */
interface EventCalendarResource {
id: string;
title: string;
color?: string;
children?: EventCalendarResource[];
}
/** Half-open: start is inclusive, end is exclusive. */
interface EventCalendarDateRange {
start: Date;
end: Date;
}
type EventCalendarWeekday = 'MO' | 'TU' | 'WE' | 'TH' | 'FR' | 'SA' | 'SU';
interface EventCalendarRecurrenceRule {
freq: 'daily' | 'weekly' | 'monthly' | 'yearly';
interval?: number;
count?: number;
/** Inclusive instant. */
until?: Date;
byWeekday?: Array<EventCalendarWeekday | { day: EventCalendarWeekday; ordinal: number }>;
byMonthDay?: number[];
byMonth?: number[];
weekStart?: EventCalendarWeekday;
exDates?: Date[];
rDates?: Date[];
}
interface CalendarEvent<TData = unknown> {
id: EventCalendarEventId;
title: string;
start: Date;
/** Exclusive; must be >= start. */
end: Date;
/** Start and end must be midnights in the display time zone: segmentation
* walks raw instants, so another zone's midnight paints the wrong days. */
allDay?: boolean;
/** Structured rule or a raw "RRULE:..." line. */
recurrence?: EventCalendarRecurrenceRule | string;
/** This event is an edited single occurrence of that series. */
recurringEventId?: EventCalendarEventId;
/** Which occurrence it replaces (RECURRENCE-ID semantics). */
originalStart?: Date;
/** Token or css color; flows to the --ec-event-color css var. */
color?: string;
/** Excluded from drag and resize regardless of interactions state. */
readOnly?: boolean;
/** Per-event overrides; defaults come from interactions.drag / .resize. */
draggable?: boolean;
resizable?: boolean;
/** Packing prominence; feeds getEventPriority ordering. */
priority?: number;
/** Verbatim stacking override; replaces the computed 10 + column. */
zIndex?: number;
resourceId?: string;
data?: TData;
}
interface EventCalendarOccurrence<TData = unknown> {
/** Stable per instance: `${event.id}::${startISO}`. */
key: string;
eventId: EventCalendarEventId;
event: CalendarEvent<TData>;
start: Date;
end: Date;
allDay: boolean;
isRecurring: boolean;
recurrenceIndex?: number;
}
interface EventCalendarSegment<TData = unknown> {
occurrence: EventCalendarOccurrence<TData>;
/** Zoned midnight of the segment's day; startMin/endMin count from it. */
day: Date;
isStart: boolean;
isEnd: boolean;
continuesBefore: boolean;
continuesAfter: boolean;
/** Timed only: minutes from the zoned day start. */
startMin?: number;
endMin?: number;
/** Layout output: lane stacks month bars and all-day lanes;
* column/columnCount/columnSpan pack time-grid overlaps;
* rowIndex/colStart/colSpan place a bar in the week row. */
lane?: number;
column?: number;
columnCount?: number;
columnSpan?: number;
rowIndex?: number;
colStart?: number;
colSpan?: number;
}
interface EventCalendarSelection {
eventKeys: string[];
/** Committed slot selection; EventCalendarSlotDraft holds the in-gesture one. */
slot: { start: Date; end: Date; allDay: boolean } | null;
}
interface EventCalendarInteractions {
drag: boolean;
resize: boolean;
selectSlot: boolean;
}
interface EventCalendarDragState<TData = unknown> {
kind: 'move' | 'resize-start' | 'resize-end';
occurrence: EventCalendarOccurrence<TData>;
proposedStart: Date;
proposedEnd: Date;
proposedAllDay: boolean;
/** Day-granular proposal (month cells, all-day lane), not minute columns; the
* all-day ghost keys on it: proposedAllDay misses timed MULTI-DAY bars. */
proposedDayGranular: boolean;
proposedResourceId?: string;
/** Last canDropEvent verdict; drives data-drop-invalid styling. */
valid: boolean;
}
/** The in-progress drag-create rectangle only; cleared on commit or cancel. */
interface EventCalendarSlotDraft {
start: Date;
end: Date;
allDay: boolean;
view: CalendarView;
resourceId?: string;
}
/** "View settings" toggles; undefined defers to the root view-config prop. */
interface EventCalendarViewSettings {
weekends?: boolean;
weekNumbers?: boolean;
nowIndicator?: boolean;
offDays?: boolean;
}
interface EventCalendarState<TData = unknown> {
view: CalendarView;
/** Anchor date; navigation steps this, and both ranges derive from it. */
date: Date;
/** Read by the "days" view only; other views ignore it. */
dayCount: number;
/** Full rendered grid incl. outside days - fetch remote data for THIS. */
visibleRange: EventCalendarDateRange;
/** The logical period (the month/week itself). */
activeRange: EventCalendarDateRange;
events: CalendarEvent<TData>[];
selection: EventCalendarSelection;
interactions: EventCalendarInteractions;
loading: boolean;
drag: EventCalendarDragState<TData> | null;
slotDraft: EventCalendarSlotDraft | null;
viewSettings: EventCalendarViewSettings;
}
interface EventCalendarRangeInfo {
range: EventCalendarDateRange;
activeRange: EventCalendarDateRange;
view: CalendarView;
date: Date;
timeZone: string;
}
interface EventCalendarProposedUpdate<TData = unknown> {
event: CalendarEvent<TData>;
/** null when source === "api". */
occurrence: EventCalendarOccurrence<TData> | null;
start: Date;
end: Date;
allDay: boolean;
resourceId?: string;
source: 'drag' | 'resize-start' | 'resize-end' | 'keyboard' | 'api';
}
/** false = reject/revert; void or true = accept; object = accept with adjustment. */
type EventCalendarUpdateResult = boolean | void | { start?: Date; end?: Date; allDay?: boolean };
/** A click is a point, not a range; `end` is present for timed slots. */
interface EventCalendarSlotInfo {
date: Date;
end?: Date;
allDay: boolean;
view: CalendarView;
resourceId?: string;
}
/** Off-days; `true` = weekend defaults. Marked cells carry `data-off`. */
interface EventCalendarOffDaysConfig {
/** Weekday numbers treated as off (0 = Sunday). Default [0, 6]. */
weekendDays?: number[];
/** Additional explicit off dates (compared by day in the display zone). */
dates?: Date[];
/** Full custom predicate; runs in addition to weekendDays/dates. */
isOffDay?: (day: Date) => boolean;
/** Marker classes; default "bg-muted/25". */
className?: string;
}
interface EventCalendarDataAdapter<TData = unknown> {
getEvents(range: EventCalendarDateRange, signal?: AbortSignal): Promise<CalendarEvent<TData>[]>;
}
export type {
CalendarEvent,
CalendarView,
EventCalendarDataAdapter,
EventCalendarDateRange,
EventCalendarDragState,
EventCalendarEventId,
EventCalendarInteractions,
EventCalendarOccurrence,
EventCalendarOffDaysConfig,
EventCalendarProposedUpdate,
EventCalendarRangeInfo,
EventCalendarRecurrenceRule,
EventCalendarResource,
EventCalendarSegment,
EventCalendarSelection,
EventCalendarSlotDraft,
EventCalendarSlotInfo,
EventCalendarState,
EventCalendarViewSettings,
EventCalendarUpdateResult,
EventCalendarWeekday,
};import {
createContext,
useCallback,
useContext,
useEffect,
useLayoutEffect,
useRef,
useState,
useSyncExternalStore,
type ComponentType,
type ReactNode,
type RefObject,
} from 'react';
import {
mergeEventCalendarI18n,
type EventCalendarI18nConfig,
type EventCalendarI18nOverrides,
} from '@/registry/vcare/ui/event-calendar/event-calendar-i18n';
import {
buildEventIndex,
defaultEventOrder,
eventsOverlap,
getDayKey,
getRangeKey,
getViewDateRange,
stepDate,
toZoned,
zonedStartOfDay,
type EventCalendarDayBucket,
type EventCalendarIndex,
type WeekStartsOn,
} from '@/registry/vcare/ui/event-calendar/event-calendar-lib';
import type {
CalendarEvent,
CalendarView,
EventCalendarDateRange,
EventCalendarDragState,
EventCalendarEventId,
EventCalendarInteractions,
EventCalendarOccurrence,
EventCalendarOffDaysConfig,
EventCalendarProposedUpdate,
EventCalendarRangeInfo,
EventCalendarResource,
EventCalendarSegment,
EventCalendarSelection,
EventCalendarSlotDraft,
EventCalendarSlotInfo,
EventCalendarState,
EventCalendarUpdateResult,
EventCalendarViewSettings,
} from '@/registry/vcare/ui/event-calendar/event-calendar-types';
import { mergeProps } from '@base-ui/react/merge-props';
import { useRender } from '@base-ui/react/use-render';
import { addDays, type Locale } from 'date-fns';
import { cn } from '@/registry/vcare/lib/utils';
const BASE_VIEWS: CalendarView[] = ['month', 'week', 'day', 'days', 'agenda'];
const ALL_VIEWS: CalendarView[] = [...BASE_VIEWS, 'resource'];
const DEFAULT_INTERACTIONS: EventCalendarInteractions = {
drag: true,
resize: true,
selectSlot: true,
};
const EMPTY_SELECTION: EventCalendarSelection = { eventKeys: [], slot: null };
// resolveSettings runs on every render, so a freshly allocated default would
// bust the view memos keyed on it (the month grid rebuilds its 42 zoned day
// starts whenever weekendDays changes identity). Shared, never mutated.
const DEFAULT_WEEKEND_DAYS: number[] = [0, 6];
const EMPTY_RESOURCES: EventCalendarResource[] = [];
const DEFAULT_EVENT_PRIORITY = (event: CalendarEvent<never>) => event.priority ?? 0;
// Priority-aware default order, cached on the resolver identity: eventOrder is
// part of the index cache key, so a fresh closure per render would rebuild the
// whole index on every render.
const priorityOrderCache = new WeakMap<object, unknown>();
type EventOrder<TData> = (a: EventCalendarOccurrence<TData>, b: EventCalendarOccurrence<TData>) => number;
function priorityEventOrder<TData>(getEventPriority: (event: CalendarEvent<TData>) => number): EventOrder<TData> {
const cached = priorityOrderCache.get(getEventPriority);
if (cached) return cached as EventOrder<TData>;
// higher priority packs and orders first; ties fall through to the
// start/duration/key default
const order: EventOrder<TData> = (a, b) => getEventPriority(b.event) - getEventPriority(a.event) || defaultEventOrder(a, b);
priorityOrderCache.set(getEventPriority, order);
return order;
}
interface EventCalendarCallbacks<TData = unknown> {
onEventClick?: (occurrence: EventCalendarOccurrence<TData>, e: React.MouseEvent) => void;
onEventDoubleClick?: (occurrence: EventCalendarOccurrence<TData>, e: React.MouseEvent) => void;
onEventUpdate?: (update: EventCalendarProposedUpdate<TData>) => EventCalendarUpdateResult;
canDropEvent?: (update: EventCalendarProposedUpdate<TData>) => boolean;
/**
* A move/resize was attempted on an event that cannot be dragged (readOnly,
* per-event draggable/resizable false, or the interaction is off). Fires once
* per gesture when the pointer crosses the activation threshold; the calendar
* shows a not-allowed cursor for the duration but never picks the message -
* broadcast it here so the consumer can surface a custom one.
*/
onDragBlocked?: (
occurrence: EventCalendarOccurrence<TData>,
info: {
gesture: 'move' | 'resize';
reason: 'readOnly' | 'disabled' | 'interactions-off';
},
) => void;
onSlotClick?: (slot: EventCalendarSlotInfo, e: React.MouseEvent) => void;
onSelectSlot?: (slot: EventCalendarSlotDraft) => void;
canSelectSlot?: (slot: EventCalendarSlotDraft) => boolean;
onRangeChange?: (info: EventCalendarRangeInfo) => void;
onViewChange?: (view: CalendarView) => void;
onDateChange?: (date: Date) => void;
onDayCountChange?: (count: number) => void;
onSelectionChange?: (selection: EventCalendarSelection) => void;
onInteractionsChange?: (interactions: EventCalendarInteractions) => void;
onViewSettingsChange?: (viewSettings: EventCalendarViewSettings) => void;
onEventsChange?: (events: CalendarEvent<TData>[]) => void;
onMoreClick?: (day: Date, segments: EventCalendarOccurrence<TData>[], e: React.MouseEvent) => void | false;
}
interface UseEventCalendarStateOptions<TData = unknown> extends EventCalendarCallbacks<TData> {
events?: CalendarEvent<TData>[];
defaultEvents?: CalendarEvent<TData>[];
view?: CalendarView;
defaultView?: CalendarView;
date?: Date;
defaultDate?: Date;
dayCount?: number;
defaultDayCount?: number;
selection?: EventCalendarSelection;
defaultSelection?: EventCalendarSelection;
interactions?: Partial<EventCalendarInteractions>;
defaultInteractions?: Partial<EventCalendarInteractions>;
viewSettings?: EventCalendarViewSettings;
defaultViewSettings?: EventCalendarViewSettings;
loading?: boolean;
views?: CalendarView[];
timeZone?: string;
locale?: Locale;
weekStartsOn?: WeekStartsOn;
dayStartHour?: number;
dayEndHour?: number;
slotDuration?: number;
snapDuration?: number;
agendaDayCount?: number;
fixedWeeks?: boolean;
showOutsideDays?: boolean;
i18n?: EventCalendarI18nOverrides;
/** Bookable resources for the resource view. */
resources?: EventCalendarResource[];
getEventPriority?: (event: CalendarEvent<TData>) => number;
eventOrder?: (a: EventCalendarOccurrence<TData>, b: EventCalendarOccurrence<TData>) => number;
getOccurrences?: (
event: CalendarEvent<TData>,
range: EventCalendarDateRange,
ctx: { timeZone: string },
) => Array<{ start: Date; end: Date }> | null;
/**
* Weekday numbers (0 = Sunday) treated as the weekend by the "weekends"
* view toggle. @default [0, 6]
*/
weekendDays?: number[];
/** Pointer-gesture tuning (activation distances, touch delay, autoscroll). */
activation?: Partial<EventCalendarActivationConfig>;
}
interface EventCalendarActivationConfig {
moveDistancePx: number;
createDistancePx: number;
touchDelayMs: number;
touchTolerancePx: number;
autoScrollEdgePx: number;
autoScrollMaxStepPx: number;
}
/**
* Resolved configuration: every UseEventCalendarStateOptions field except the
* controlled/uncontrolled state pairs, with defaults applied and i18n merged.
* Read via ref semantics - callback identity changes never re-render the grid.
*/
interface EventCalendarSettings<TData = unknown> extends EventCalendarCallbacks<TData> {
timeZone: string;
locale?: Locale;
weekStartsOn: WeekStartsOn;
views: CalendarView[];
dayStartHour: number;
dayEndHour: number;
slotDuration: number;
snapDuration: number;
agendaDayCount: number;
fixedWeeks: boolean;
showOutsideDays: boolean;
i18n: EventCalendarI18nConfig;
resources: EventCalendarResource[];
weekendDays: number[];
activation?: Partial<EventCalendarActivationConfig>;
getEventPriority: (event: CalendarEvent<TData>) => number;
eventOrder: (a: EventCalendarOccurrence<TData>, b: EventCalendarOccurrence<TData>) => number;
getOccurrences?: (
event: CalendarEvent<TData>,
range: EventCalendarDateRange,
ctx: { timeZone: string },
) => Array<{ start: Date; end: Date }> | null;
}
interface EventCalendarApi<TData = unknown> {
next(): void;
prev(): void;
today(): void;
goTo(date: Date): void;
setView(view: CalendarView, opts?: { dayCount?: number }): void;
setDayCount(count: number): void;
getEvents(): CalendarEvent<TData>[];
getEvent(id: EventCalendarEventId): CalendarEvent<TData> | undefined;
setEvents(events: CalendarEvent<TData>[]): void;
addEvent(event: CalendarEvent<TData>): void;
updateEvent(id: EventCalendarEventId, patch: Partial<CalendarEvent<TData>>): void;
removeEvent(id: EventCalendarEventId): void;
getOccurrences(range?: EventCalendarDateRange): EventCalendarOccurrence<TData>[];
getOccurrencesForDay(day: Date): EventCalendarOccurrence<TData>[];
findOverlapping(candidate: { start: Date; end: Date; excludeEventId?: string }): EventCalendarOccurrence<TData>[];
select(selection: Partial<EventCalendarSelection>): void;
selectEvent(key: string, opts?: { additive?: boolean }): void;
clearSelection(): void;
setInteractions(patch: Partial<EventCalendarInteractions>): void;
setViewSettings(patch: EventCalendarViewSettings): void;
getVisibleRange(): EventCalendarDateRange;
getActiveRange(): EventCalendarDateRange;
/** TZDate in the calendar's display time zone. */
toZoned(date: Date): Date;
/** number = minutes from the zoned day start; no-op outside time-grid views. */
scrollToTime(time: Date | number): void;
}
/** Cross-file plumbing for sibling view/interaction modules; not public API. */
interface EventCalendarInternals<TData = unknown> {
getIndex(): EventCalendarIndex<TData>;
setDrag(drag: EventCalendarDragState<TData> | null): void;
setSlotDraft(draft: EventCalendarSlotDraft | null): void;
registerScrollHandler(handler: ((time: Date | number) => void) | null): void;
applyProposedUpdate(update: EventCalendarProposedUpdate<TData>, extraPatch?: Partial<CalendarEvent<TData>>): boolean;
getSettingsVersion(): number;
/** The rendered calendar root element, or null before mount. */
getRootEl(): HTMLElement | null;
setRootEl(el: HTMLElement | null): void;
}
interface EventCalendarInstance<TData = unknown> {
getState(): EventCalendarState<TData>;
subscribe(listener: () => void): () => void;
api: EventCalendarApi<TData>;
settings: EventCalendarSettings<TData>;
internals: EventCalendarInternals<TData>;
}
function resolveSettings<TData>(options: UseEventCalendarStateOptions<TData>): EventCalendarSettings<TData> {
const {
// strip state pairs; the rest flows into settings
events: _e,
defaultEvents: _de,
view: _v,
defaultView: _dv,
date: _d,
defaultDate: _dd,
dayCount: _dc,
defaultDayCount: _ddc,
selection: _s,
defaultSelection: _ds,
interactions: _i,
defaultInteractions: _di,
viewSettings: _vs,
defaultViewSettings: _dvs,
loading: _l,
...rest
} = options;
const getEventPriority = options.getEventPriority ?? (DEFAULT_EVENT_PRIORITY as (event: CalendarEvent<TData>) => number);
return {
...rest,
timeZone: options.timeZone ?? Intl.DateTimeFormat().resolvedOptions().timeZone,
locale: options.locale,
// locale-first default: a de/fr locale gets Monday weeks without also
// having to set weekStartsOn; an explicit weekStartsOn always wins
weekStartsOn: options.weekStartsOn ?? options.locale?.options?.weekStartsOn ?? 0,
// the resource view only makes sense with resources configured
views: options.views ?? (options.resources?.length ? ALL_VIEWS : BASE_VIEWS),
dayStartHour: options.dayStartHour ?? 0,
dayEndHour: options.dayEndHour ?? 24,
slotDuration: options.slotDuration ?? 30,
snapDuration: options.snapDuration ?? 15,
agendaDayCount: options.agendaDayCount ?? 30,
fixedWeeks: options.fixedWeeks ?? true,
showOutsideDays: options.showOutsideDays ?? true,
i18n: mergeEventCalendarI18n(options.i18n),
resources: options.resources ?? EMPTY_RESOURCES,
getEventPriority,
eventOrder: options.eventOrder ?? priorityEventOrder(getEventPriority),
getOccurrences: options.getOccurrences,
weekendDays: options.weekendDays ?? DEFAULT_WEEKEND_DAYS,
activation: options.activation,
};
}
const warned = new Set<string>();
function warnOnce(key: string, message: string) {
if (process.env.NODE_ENV !== 'production' && !warned.has(key)) {
warned.add(key);
console.warn(`[event-calendar] ${message}`);
}
}
interface EventCalendarStore<TData> {
instance: EventCalendarInstance<TData>;
setOptions(next: UseEventCalendarStateOptions<TData>): boolean;
notify(): void;
emitRangeIfChanged(): void;
}
function createEventCalendarStore<TData>(initial: UseEventCalendarStateOptions<TData>): EventCalendarStore<TData> {
let options = initial;
let settings = resolveSettings(initial);
let settingsVersion = 0;
const listeners = new Set<() => void>();
const resolveView = (view: CalendarView): CalendarView => {
if (settings.views.includes(view)) return view;
const fallback = settings.views[0] ?? 'month';
warnOnce(`view-${view}`, `view "${view}" is not in views [${settings.views.join(', ')}]; falling back to "${fallback}".`);
return fallback;
};
const internal = {
view: resolveView(initial.defaultView ?? 'month'),
date: initial.defaultDate ?? new Date(),
dayCount: initial.defaultDayCount ?? 3,
events: initial.defaultEvents ?? [],
selection: initial.defaultSelection ?? EMPTY_SELECTION,
interactions: { ...DEFAULT_INTERACTIONS, ...initial.defaultInteractions },
viewSettings: initial.defaultViewSettings ?? {},
drag: null as EventCalendarDragState<TData> | null,
slotDraft: null as EventCalendarSlotDraft | null,
};
let snapshot: EventCalendarState<TData> | null = null;
let indexCache: {
events: CalendarEvent<TData>[];
rangeKey: string;
timeZone: string;
weekStartsOn: WeekStartsOn;
eventOrder: EventCalendarSettings<TData>['eventOrder'];
getOccurrences: EventCalendarSettings<TData>['getOccurrences'];
index: EventCalendarIndex<TData>;
} | null = null;
// Second single-entry cache, for api.getOccurrences(range) outside the
// visible range: that branch builds a throwaway index, so without it every
// call hands back brand new occurrence OBJECTS and the identity-based
// isEqual in useEventCalendarOccurrences can never settle - an unstable
// getSnapshot is a hard render loop under useSyncExternalStore, not a slow
// render.
let rangeCache: {
events: CalendarEvent<TData>[];
rangeKey: string;
timeZone: string;
weekStartsOn: WeekStartsOn;
eventOrder: EventCalendarSettings<TData>['eventOrder'];
getOccurrences: EventCalendarSettings<TData>['getOccurrences'];
occurrences: EventCalendarOccurrence<TData>[];
} | null = null;
let scrollHandler: ((time: Date | number) => void) | null = null;
// The rendered calendar root element, registered by the <EventCalendar> host.
// The drag engine falls back to it to find day cells when a gesture starts
// from a portaled surface (e.g. a chip inside the "+N more" popover), whose
// DOM ancestors do not include the calendar.
let rootEl: HTMLElement | null = null;
let lastEmittedRangeKey: string | null = null;
// Controlled interactions merge, cached on input identity: rebuilding the
// merged object per snapshot would break Object.is for selector hooks.
let interactionsCache: {
input: Partial<EventCalendarInteractions>;
merged: EventCalendarInteractions;
} | null = null;
const mergedInteractions = (input: Partial<EventCalendarInteractions>): EventCalendarInteractions => {
if (interactionsCache?.input !== input) {
interactionsCache = {
input,
merged: { ...DEFAULT_INTERACTIONS, ...input },
};
}
return interactionsCache.merged;
};
const invalidate = () => {
snapshot = null;
};
const notify = () => {
listeners.forEach((listener) => listener());
emitRangeIfChanged();
};
const getState = (): EventCalendarState<TData> => {
if (snapshot) return snapshot;
const view = resolveView(options.view ?? internal.view);
const date = options.date ?? internal.date;
const dayCount = Math.max(1, options.dayCount ?? internal.dayCount);
const { visibleRange, activeRange } = getViewDateRange(view, date, {
timeZone: settings.timeZone,
weekStartsOn: settings.weekStartsOn,
dayCount,
agendaDayCount: settings.agendaDayCount,
fixedWeeks: settings.fixedWeeks,
});
snapshot = {
view,
date,
dayCount,
visibleRange,
activeRange,
events: options.events ?? internal.events,
selection: options.selection ?? internal.selection,
interactions: options.interactions ? mergedInteractions(options.interactions) : internal.interactions,
loading: options.loading ?? false,
drag: internal.drag,
slotDraft: internal.slotDraft,
viewSettings: options.viewSettings ?? internal.viewSettings,
};
return snapshot;
};
const emitRangeIfChanged = () => {
if (!settings.onRangeChange) return;
const state = getState();
const key = `${state.view}:${getRangeKey(state.visibleRange)}:${settings.timeZone}`;
if (key === lastEmittedRangeKey) return;
lastEmittedRangeKey = key;
settings.onRangeChange({
range: state.visibleRange,
activeRange: state.activeRange,
view: state.view,
date: state.date,
timeZone: settings.timeZone,
});
};
type ControlledKey = 'view' | 'date' | 'dayCount' | 'events' | 'selection' | 'interactions' | 'viewSettings';
const setField = <K extends ControlledKey>(key: K, value: EventCalendarState<TData>[K extends 'events' ? 'events' : K]) => {
const controlled = options[key] !== undefined;
if (!controlled) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(internal as any)[key] = value;
invalidate();
}
const callbacks: Record<ControlledKey, ((v: never) => void) | undefined> = {
view: settings.onViewChange as never,
date: settings.onDateChange as never,
dayCount: settings.onDayCountChange as never,
events: settings.onEventsChange as never,
selection: settings.onSelectionChange as never,
interactions: settings.onInteractionsChange as never,
viewSettings: settings.onViewSettingsChange as never,
};
callbacks[key]?.(value as never);
if (!controlled) notify();
};
// An occurrence key encodes the start instant (id::startISO), so committing a
// move re-keys the occurrence and a selection holding the old key would point
// at nothing. Remapped in the same commit and emitted BEFORE the events write
// so a controlled consumer applies the two in a consistent order.
const remapSelectionKey = (id: EventCalendarEventId, oldKey: string, nextStart: Date) => {
const newKey = `${id}::${nextStart.toISOString()}`;
if (newKey === oldKey) return;
const selection = getState().selection;
if (!selection.eventKeys.includes(oldKey)) return;
setField('selection', {
...selection,
eventKeys: selection.eventKeys.map((key) => (key === oldKey ? newKey : key)),
});
};
// extraPatch: non-timing fields committed in the SAME write. Two sequential
// setField("events") calls break controlled mode - the second one re-reads
// the still-stale controlled array and its onEventsChange payload silently
// reverts the timing change the first one emitted.
const applyProposedUpdate = (update: EventCalendarProposedUpdate<TData>, extraPatch?: Partial<CalendarEvent<TData>>): boolean => {
const result = settings.onEventUpdate?.(update);
if (result === false) return false;
const adjusted: Partial<CalendarEvent<TData>> =
result && typeof result === 'object'
? {
start: result.start ?? update.start,
end: result.end ?? update.end,
allDay: result.allDay ?? update.allDay,
}
: { start: update.start, end: update.end, allDay: update.allDay };
if (update.resourceId !== undefined) adjusted.resourceId = update.resourceId;
// the STORED event holds the pre-commit start, which is what the live
// occurrence key was built from (update.event already carries the proposal
// when the call comes from api.updateEvent)
const stored = getState().events.find((event) => event.id === update.event.id);
const oldKey = update.occurrence?.key ?? (stored ? `${stored.id}::${stored.start.toISOString()}` : null);
if (oldKey) {
remapSelectionKey(update.event.id, oldKey, adjusted.start ?? update.start);
}
const events = getState().events;
const next = events.map((event) => (event.id === update.event.id ? { ...event, ...extraPatch, ...adjusted } : event));
setField('events', next);
return true;
};
const getIndex = (): EventCalendarIndex<TData> => {
const state = getState();
const rangeKey = getRangeKey(state.visibleRange);
if (
indexCache &&
indexCache.events === state.events &&
indexCache.rangeKey === rangeKey &&
indexCache.timeZone === settings.timeZone &&
indexCache.weekStartsOn === settings.weekStartsOn &&
indexCache.eventOrder === settings.eventOrder &&
indexCache.getOccurrences === settings.getOccurrences
) {
return indexCache.index;
}
const index = buildEventIndex(state.events, state.visibleRange, {
timeZone: settings.timeZone,
weekStartsOn: settings.weekStartsOn,
eventOrder: settings.eventOrder,
getOccurrences: settings.getOccurrences,
});
indexCache = {
events: state.events,
rangeKey,
timeZone: settings.timeZone,
weekStartsOn: settings.weekStartsOn,
eventOrder: settings.eventOrder,
getOccurrences: settings.getOccurrences,
index,
};
return index;
};
const api: EventCalendarApi<TData> = {
next() {
const state = getState();
setField(
'date',
stepDate(state.view, state.date, 1, {
timeZone: settings.timeZone,
dayCount: state.dayCount,
agendaDayCount: settings.agendaDayCount,
}),
);
},
prev() {
const state = getState();
setField(
'date',
stepDate(state.view, state.date, -1, {
timeZone: settings.timeZone,
dayCount: state.dayCount,
agendaDayCount: settings.agendaDayCount,
}),
);
},
today() {
setField('date', new Date());
},
goTo(date) {
setField('date', date);
},
setView(view, opts) {
if (opts?.dayCount !== undefined) {
setField('dayCount', Math.max(1, opts.dayCount));
}
setField('view', resolveView(view));
},
setDayCount(count) {
setField('dayCount', Math.max(1, count));
},
getEvents() {
return getState().events;
},
getEvent(id) {
return getState().events.find((event) => event.id === id);
},
setEvents(events) {
setField('events', events);
},
addEvent(event) {
setField('events', [...getState().events, event]);
},
updateEvent(id, patch) {
const event = api.getEvent(id);
if (!event) return;
const merged = { ...event, ...patch };
const timingChanged = patch.start !== undefined || patch.end !== undefined || patch.allDay !== undefined;
if (timingChanged && settings.onEventUpdate) {
// single write: the non-timing rest rides along as extraPatch so
// controlled mode sees one consistent onEventsChange payload
const rest = { ...patch };
delete rest.start;
delete rest.end;
delete rest.allDay;
applyProposedUpdate(
{
event: merged,
occurrence: null,
start: merged.start,
end: merged.end,
allDay: merged.allDay ?? false,
source: 'api',
},
rest,
);
return;
}
if (timingChanged) {
remapSelectionKey(id, `${id}::${event.start.toISOString()}`, merged.start);
}
setField(
'events',
getState().events.map((e) => (e.id === id ? merged : e)),
);
},
removeEvent(id) {
setField(
'events',
getState().events.filter((event) => event.id !== id),
);
},
getOccurrences(range) {
if (!range) return getIndex().occurrences;
const state = getState();
const within = range.start >= state.visibleRange.start && range.end <= state.visibleRange.end;
if (within) {
return getIndex().occurrences.filter((occ) => eventsOverlap(occ, range));
}
const rangeKey = getRangeKey(range);
if (
rangeCache &&
rangeCache.events === state.events &&
rangeCache.rangeKey === rangeKey &&
rangeCache.timeZone === settings.timeZone &&
rangeCache.weekStartsOn === settings.weekStartsOn &&
rangeCache.eventOrder === settings.eventOrder &&
rangeCache.getOccurrences === settings.getOccurrences
) {
return rangeCache.occurrences;
}
const { occurrences } = buildEventIndex(state.events, range, {
timeZone: settings.timeZone,
weekStartsOn: settings.weekStartsOn,
eventOrder: settings.eventOrder,
getOccurrences: settings.getOccurrences,
});
rangeCache = {
events: state.events,
rangeKey,
timeZone: settings.timeZone,
weekStartsOn: settings.weekStartsOn,
eventOrder: settings.eventOrder,
getOccurrences: settings.getOccurrences,
occurrences,
};
return occurrences;
},
getOccurrencesForDay(day) {
const bucket = getIndex().byDay.get(getDayKey(day, settings.timeZone));
if (!bucket) return [];
const seen = new Set<string>();
const result: EventCalendarOccurrence<TData>[] = [];
for (const seg of [...bucket.allDay, ...bucket.timed]) {
if (seen.has(seg.occurrence.key)) continue;
seen.add(seg.occurrence.key);
result.push(seg.occurrence);
}
return result;
},
findOverlapping({ start, end, excludeEventId }) {
return api.getOccurrences({ start, end }).filter((occ) => occ.eventId !== excludeEventId);
},
select(partial) {
const current = getState().selection;
setField('selection', {
eventKeys: partial.eventKeys ?? current.eventKeys,
slot: partial.slot !== undefined ? partial.slot : current.slot,
});
},
selectEvent(key, opts) {
const current = getState().selection;
const eventKeys = opts?.additive
? current.eventKeys.includes(key)
? current.eventKeys.filter((k) => k !== key)
: [...current.eventKeys, key]
: [key];
setField('selection', { ...current, eventKeys });
},
clearSelection() {
setField('selection', EMPTY_SELECTION);
},
setInteractions(patch) {
setField('interactions', { ...getState().interactions, ...patch });
},
setViewSettings(patch) {
setField('viewSettings', { ...getState().viewSettings, ...patch });
},
getVisibleRange() {
return getState().visibleRange;
},
getActiveRange() {
return getState().activeRange;
},
toZoned(date) {
return toZoned(date, settings.timeZone);
},
scrollToTime(time) {
scrollHandler?.(time);
},
};
const internals: EventCalendarInternals<TData> = {
getIndex,
setDrag(drag) {
internal.drag = drag;
invalidate();
notify();
},
setSlotDraft(draft) {
internal.slotDraft = draft;
invalidate();
notify();
},
registerScrollHandler(handler) {
scrollHandler = handler;
},
applyProposedUpdate,
getSettingsVersion() {
return settingsVersion;
},
getRootEl() {
return rootEl;
},
setRootEl(el) {
rootEl = el;
},
};
const instance: EventCalendarInstance<TData> = {
getState,
subscribe(listener) {
listeners.add(listener);
return () => listeners.delete(listener);
},
api,
get settings() {
return settings;
},
internals,
};
const STATE_KEYS = ['events', 'view', 'date', 'dayCount', 'selection', 'interactions', 'viewSettings', 'loading'] as const;
const SETTINGS_KEYS = [
'timeZone',
'locale',
'weekStartsOn',
'views',
'dayStartHour',
'dayEndHour',
'slotDuration',
'snapDuration',
'agendaDayCount',
'fixedWeeks',
'showOutsideDays',
'i18n',
'resources',
'getEventPriority',
'eventOrder',
'getOccurrences',
'weekendDays',
'activation',
] as const;
return {
instance,
setOptions(next) {
const prev = options;
options = next;
let changed = false;
for (const key of STATE_KEYS) {
if (prev[key] !== next[key]) {
changed = true;
break;
}
}
let settingsChanged = false;
for (const key of SETTINGS_KEYS) {
if (prev[key] !== next[key]) {
settingsChanged = true;
break;
}
}
settings = resolveSettings(next);
if (settingsChanged) {
settingsVersion++;
changed = true;
}
if (changed) invalidate();
return changed;
},
notify,
emitRangeIfChanged,
};
}
/**
* Headless root hook - the full calendar engine without any markup.
* Pass the returned instance to <EventCalendar calendar={instance}> or drive
* fully custom UI from instance.getState()/subscribe/api.
*/
function useEventCalendarState<TData = unknown>(options: UseEventCalendarStateOptions<TData> = {}): EventCalendarInstance<TData> {
const [store] = useState(() => createEventCalendarStore<TData>(options));
const changed = store.setOptions(options);
const changedRef = useRef(false);
if (changed) changedRef.current = true;
useLayoutEffect(() => {
if (changedRef.current) {
changedRef.current = false;
store.notify();
}
});
useEffect(() => {
store.emitRangeIfChanged();
// mount-only: onRangeChange fires once for the initial range
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
return store.instance;
}
const EventCalendarContext =
// eslint-disable-next-line @typescript-eslint/no-explicit-any
createContext<EventCalendarInstance<any> | null>(null);
/** The stable calendar instance; throws outside <EventCalendar>. */
function useEventCalendar<TData = unknown>(): EventCalendarInstance<TData> {
const instance = useContext(EventCalendarContext);
if (!instance) {
throw new Error('useEventCalendar must be used within <EventCalendar>');
}
return instance as EventCalendarInstance<TData>;
}
interface UseEventCalendarSelectorOptions<TData, TSelected> {
calendar?: EventCalendarInstance<TData>;
isEqual?: (a: TSelected, b: TSelected) => boolean;
}
/** Fine-grained subscription with equality memoization (Object.is default). */
function useEventCalendarSelector<TData = unknown, TSelected = unknown>(
selector: (state: EventCalendarState<TData>) => TSelected,
options?: UseEventCalendarSelectorOptions<TData, TSelected>,
): TSelected {
const contextInstance = useContext(EventCalendarContext);
const instance = options?.calendar ?? contextInstance;
if (!instance) {
throw new Error('useEventCalendarSelector needs an <EventCalendar> ancestor or an explicit `calendar` option');
}
const isEqual = options?.isEqual ?? Object.is;
const lastRef = useRef<{ value: TSelected } | null>(null);
const selectorRef = useRef(selector);
selectorRef.current = selector;
const getSnapshot = () => {
const next = selectorRef.current(instance.getState() as EventCalendarState<TData>);
if (lastRef.current && isEqual(lastRef.current.value, next)) {
return lastRef.current.value;
}
lastRef.current = { value: next };
return next;
};
return useSyncExternalStore(instance.subscribe, getSnapshot, getSnapshot);
}
function useEventCalendarView(): {
view: CalendarView;
dayCount: number;
/** The resolved `views` option from settings. */
availableViews: CalendarView[];
setView: (view: CalendarView, opts?: { dayCount?: number }) => void;
} {
const instance = useEventCalendar();
const view = useEventCalendarSelector((state) => state.view);
const dayCount = useEventCalendarSelector((state) => state.dayCount);
useEventCalendarSettingsVersion(instance);
return {
view,
dayCount,
availableViews: instance.settings.views,
setView: instance.api.setView,
};
}
/**
* isToday is a wall-clock read, so no store write ever invalidates it and a
* calendar left open overnight keeps highlighting yesterday. One timer per
* display zone, armed for the next zoned midnight and re-armed on fire, wakes
* every day-scoped hook exactly when the answer changes; an interval would
* tick thousands of times a day to catch one transition.
*/
const midnightTicker = (() => {
const zones = new Map<string, { listeners: Set<() => void>; timer: ReturnType<typeof setTimeout> | null }>();
let version = 0;
const arm = (timeZone: string) => {
const entry = zones.get(timeZone);
if (!entry) return;
const now = new Date();
const next = zonedStartOfDay(addDays(toZoned(now, timeZone), 1), timeZone).getTime();
entry.timer = setTimeout(
() => {
version++;
entry.listeners.forEach((listener) => listener());
arm(timeZone);
},
Math.max(1000, next - now.getTime()),
);
};
return {
subscribe(timeZone: string, listener: () => void) {
let entry = zones.get(timeZone);
if (!entry) {
entry = { listeners: new Set(), timer: null };
zones.set(timeZone, entry);
entry.listeners.add(listener);
arm(timeZone);
} else {
entry.listeners.add(listener);
}
const current = entry;
return () => {
current.listeners.delete(listener);
if (current.listeners.size > 0) return;
if (current.timer) clearTimeout(current.timer);
zones.delete(timeZone);
};
},
getVersion: () => version,
};
})();
/** Re-renders the caller on the next midnight in `timeZone`. */
function useMidnightTick(timeZone: string): number {
const subscribe = useCallback((listener: () => void) => midnightTicker.subscribe(timeZone, listener), [timeZone]);
return useSyncExternalStore(subscribe, midnightTicker.getVersion, midnightTicker.getVersion);
}
function useEventCalendarNavigation(): {
date: Date;
/** i18n.functions.formatTitle output for the current view. */
title: string;
visibleRange: EventCalendarDateRange;
activeRange: EventCalendarDateRange;
next: () => void;
prev: () => void;
today: () => void;
goTo: (date: Date) => void;
/** True when the anchor period contains now in the display time zone. */
isToday: boolean;
} {
const instance = useEventCalendar();
const { settings } = instance;
const slice = useEventCalendarSelector(
(state) => ({
date: state.date,
view: state.view,
visibleRange: state.visibleRange,
activeRange: state.activeRange,
}),
{
isEqual: (a, b) => a.date.getTime() === b.date.getTime() && a.view === b.view && getRangeKey(a.visibleRange) === getRangeKey(b.visibleRange),
},
);
useEventCalendarSettingsVersion(instance);
useMidnightTick(settings.timeZone);
const now = new Date();
return {
date: slice.date,
title: settings.i18n.functions.formatTitle(slice.view, {
date: toZoned(slice.date, settings.timeZone),
activeRange: slice.activeRange,
visibleRange: slice.visibleRange,
locale: settings.locale,
}),
visibleRange: slice.visibleRange,
activeRange: slice.activeRange,
next: instance.api.next,
prev: instance.api.prev,
today: instance.api.today,
goTo: instance.api.goTo,
isToday: now >= slice.activeRange.start && now < slice.activeRange.end,
};
}
function useEventCalendarSelection(): {
selection: EventCalendarSelection;
select: (selection: Partial<EventCalendarSelection>) => void;
selectEvent: (key: string, opts?: { additive?: boolean }) => void;
clearSelection: () => void;
} {
const instance = useEventCalendar();
const selection = useEventCalendarSelector((state) => state.selection);
return {
selection,
select: instance.api.select,
selectEvent: instance.api.selectEvent,
clearSelection: instance.api.clearSelection,
};
}
function useEventCalendarInteractions(): {
interactions: EventCalendarInteractions;
setInteractions: (patch: Partial<EventCalendarInteractions>) => void;
} {
const instance = useEventCalendar();
const interactions = useEventCalendarSelector((state) => state.interactions);
return { interactions, setInteractions: instance.api.setInteractions };
}
/** Expanded, sorted occurrences; defaults to the visible range. */
function useEventCalendarOccurrences<TData = unknown>(range?: EventCalendarDateRange): EventCalendarOccurrence<TData>[] {
const instance = useEventCalendar<TData>();
return useEventCalendarSelector<TData, EventCalendarOccurrence<TData>[]>(() => instance.api.getOccurrences(range), {
calendar: instance,
// element identity, not keys: keys encode id+start only, so an end-only
// resize or a title/color/data edit would never invalidate a key-based
// memo. The index rebuilds occurrence objects precisely when events
// change, so identity is the correct (and cheapest) change signal.
isEqual: (a, b) => a === b || (a.length === b.length && a.every((occ, i) => occ === b[i])),
});
}
const EMPTY_BUCKET: EventCalendarDayBucket = { allDay: [], timed: [] };
/** Per-cell subscription: only cells whose segments changed re-render. */
function useEventCalendarDay<TData = unknown>(
day: Date,
): {
segments: EventCalendarDayBucket<TData>;
isToday: boolean;
isOutside: boolean;
} {
const instance = useEventCalendar<TData>();
const { timeZone } = instance.settings;
const dayKey = getDayKey(day, timeZone);
const bucket = useEventCalendarSelector<TData, EventCalendarDayBucket<TData>>(
() => instance.internals.getIndex().byDay.get(dayKey) ?? (EMPTY_BUCKET as EventCalendarDayBucket<TData>),
{
calendar: instance,
// Element identity, not a content key: an occurrence key encodes
// id+start only, so a title/color/data edit produced an identical key
// and this cell kept serving its STALE segments. Buckets come straight
// out of the memoized index, which rebuilds precisely when events
// change, so identity is both correct and the cheapest signal.
isEqual: (a, b) =>
a === b ||
(a.allDay.length === b.allDay.length &&
a.timed.length === b.timed.length &&
a.allDay.every((segment, i) => segment === b.allDay[i]) &&
a.timed.every((segment, i) => segment === b.timed[i])),
},
);
const activeRange = useEventCalendarSelector<TData, EventCalendarDateRange>((state) => state.activeRange, {
calendar: instance,
isEqual: (a, b) => getRangeKey(a) === getRangeKey(b),
});
useMidnightTick(timeZone);
const dayStart = zonedStartOfDay(day, timeZone);
return {
segments: bucket,
isToday: getDayKey(new Date(), timeZone) === dayKey,
isOutside: dayStart < activeRange.start || dayStart >= activeRange.end,
};
}
const EMPTY_BARS: EventCalendarSegment[] = [];
/**
* Per-week-row subscription for the month view: the laned multi-day/all-day
* bar segments (one per occurrence per row, colStart/colSpan/lane set) that
* render as continuous cross-day bars. `laneCount` is the row's bar height.
* Matched by CONTAINMENT - any day inside the row resolves it - so a
* weekends-hidden month (first visible day Monday) still finds its row;
* `rowStart` returns the row's TRUE start for colStart/colSpan day math.
*/
function useEventCalendarWeek<TData = unknown>(
day: Date,
): {
bars: EventCalendarSegment<TData>[];
laneCount: number;
rowStart: Date | null;
} {
const instance = useEventCalendar<TData>();
const { timeZone } = instance.settings;
const dayStartMs = zonedStartOfDay(day, timeZone).getTime();
const row = useEventCalendarSelector<TData, { bars: EventCalendarSegment<TData>[]; rowStart: Date | null }>(
() => {
const index = instance.internals.getIndex();
const match = index.weekRows.find((r) => {
const startMs = zonedStartOfDay(r.rowStart, timeZone).getTime();
// calendar-aware row end: a fixed 168h window would let the first
// day AFTER a spring-forward week (167h long) match the wrong row
const endMs = zonedStartOfDay(addDays(toZoned(r.rowStart, timeZone), 7), timeZone).getTime();
return dayStartMs >= startMs && dayStartMs < endMs;
});
return {
bars: match?.bars ?? (EMPTY_BARS as EventCalendarSegment<TData>[]),
rowStart: match?.rowStart ?? null,
};
},
{
calendar: instance,
// Same reasoning as the day bucket above: `bars` is the array held by
// the memoized index, so element identity catches content edits that a
// key built from id+start could never see.
isEqual: (a, b) =>
(a.rowStart?.getTime() ?? 0) === (b.rowStart?.getTime() ?? 0) &&
(a.bars === b.bars || (a.bars.length === b.bars.length && a.bars.every((segment, i) => segment === b.bars[i]))),
},
);
const laneCount = row.bars.reduce((m, s) => Math.max(m, (s.lane ?? 0) + 1), 0);
return { bars: row.bars, laneCount, rowStart: row.rowStart };
}
/**
* User view settings (weekends, week numbers, now line, off days, schedule
* hint) + the effective values after falling back to the root view-config
* props. Drives the nav submenu; fully controllable from outside via
* `viewSettings`/`onViewSettingsChange` or api.setViewSettings.
*/
function useEventCalendarViewSettings(): {
viewSettings: EventCalendarViewSettings;
setViewSettings: (patch: EventCalendarViewSettings) => void;
effective: Required<EventCalendarViewSettings>;
} {
const instance = useEventCalendar();
const viewConfig = useEventCalendarViewConfig();
const viewSettings = useEventCalendarSelector((state) => state.viewSettings);
return {
viewSettings,
setViewSettings: instance.api.setViewSettings,
effective: {
weekends: viewSettings.weekends ?? true,
weekNumbers: viewSettings.weekNumbers ?? viewConfig.showWeekNumbers,
nowIndicator: viewSettings.nowIndicator ?? viewConfig.nowIndicator,
offDays: viewSettings.offDays ?? (viewConfig.offDays !== undefined && viewConfig.offDays !== false),
},
};
}
/** Subscribes to settings changes only (version counter, not state). */
function useEventCalendarSettingsVersion<TData>(instance: EventCalendarInstance<TData>): number {
return useSyncExternalStore(instance.subscribe, instance.internals.getSettingsVersion, instance.internals.getSettingsVersion);
}
/** Resolved settings incl. merged i18n; re-renders only when settings change. */
function useEventCalendarSettings<TData = unknown>(): EventCalendarSettings<TData> {
const instance = useEventCalendar<TData>();
useEventCalendarSettingsVersion(instance);
return instance.settings;
}
const EventCalendarViewContext = createContext<{ view: CalendarView } | null>(null);
/**
* Per-element class hooks, cn()-merged AFTER the built-in classes (so tailwind
* variants and ! overrides win). Metric CSS variables can ride on any parent
* key, e.g. classNames.timeGrid: "[--ec-gutter-width:4.5rem]".
*/
interface EventCalendarClassNames {
nav?: string;
toolbar?: string;
content?: string;
monthView?: string;
monthCell?: string;
timeGrid?: string;
timeGutter?: string;
dayColumn?: string;
allDaySection?: string;
agendaView?: string;
event?: string;
/** The styled hover tooltip popup (viewConfig.eventTooltip). */
eventTooltip?: string;
moreIndicator?: string;
/** The "+N more" popover panel. Control the on-demand scroll cap through
* the CSS variable, e.g. "[--ec-more-max-height:20rem]". */
morePopover?: string;
/** "+N more" popover day header row. */
morePopoverHeader?: string;
// nav family (reachable without recomposing the default nav)
navButton?: string;
title?: string;
navTooltip?: string;
viewSwitcherContent?: string;
viewSwitcherLabel?: string;
viewShortcut?: string;
datePickerContent?: string;
// month view
monthHeader?: string;
monthDayHeader?: string;
monthBody?: string;
monthRow?: string;
weekNumber?: string;
monthBarOverlay?: string;
monthBar?: string;
monthCellContent?: string;
monthCellFooter?: string;
monthDayNumber?: string;
dayAddButton?: string;
// time grid / resource
timeGridHeader?: string;
timeGutterLabel?: string;
allDayLabel?: string;
allDayCell?: string;
timedChip?: string;
resourceHeader?: string;
// interaction surfaces (shared by every view)
dragGhost?: string;
dragCarry?: string;
dragCarryInvalid?: string;
dropHint?: string;
dropIndicator?: string;
slotDraft?: string;
resizeHandle?: string;
resizeGrip?: string;
// agenda
noEvents?: string;
agendaDay?: string;
agendaDayHeader?: string;
agendaDayGutter?: string;
agendaDate?: string;
agendaDayToggle?: string;
agendaDayContent?: string;
agendaItem?: string;
agendaItemSurface?: string;
agendaItemToggle?: string;
agendaDaySummary?: string;
agendaSummaryDot?: string;
}
interface EventCalendarRenderEventProps<TData = unknown> {
occurrence: EventCalendarOccurrence<TData>;
segment: EventCalendarSegment<TData>;
view: CalendarView;
isDragging: boolean;
isSelected: boolean;
}
/**
* View-layer configuration: display props and render overrides. These live on
* <EventCalendar> (and per-view components), never in the headless options.
*/
interface EventCalendarViewConfig<TData = unknown> {
scrollToHour: number;
nowIndicator: boolean;
/**
* Grid interval in minutes for the time-based views (day, week, N-days,
* time grid): gutter slots and gridlines follow it. Also accepted as a
* prop on each view component.
*/
interval: number;
maxEventsPerCell: number | 'auto';
showWeekNumbers: boolean;
enableShortcuts: boolean;
shortcutsScope: 'focus-within' | 'global';
/**
* "contained" (default): the calendar fills its container and views scroll
* internally. "page": content flows with the document, the page scrolls,
* and day headers stick below `--ec-sticky-offset` (default 0px).
*/
scrollMode: 'contained' | 'page';
/** Stick the default nav to the top while the page scrolls. */
stickyNav: boolean;
/**
* Custom per-day indication (light background classes work in both themes,
* e.g. "bg-amber-500/10"). Applied to month cells, time-grid day columns,
* and all-day cells; content stays readable on top of it.
*/
dayClassName?: (day: Date) => string | undefined;
/**
* Extra classes for the CURRENT day, appended after the built-in highlight
* (primary-tinted background + accent top border) on month cells, time-grid
* day columns, and day headers.
*/
todayClassName?: string;
/**
* Show a hover "+" add affordance on month cells next to the day number.
* It fires the same onSlotClick as clicking the day. Calendar-level config
* (consistent affordance, wired to the create flow); use renderMonthCell
* when a fully custom cell is needed instead.
*/
showDayAddButton: boolean;
/**
* Scroll implementation for every internally scrolling surface (time grid,
* agenda, time-grid resources, month "+N more" popover):
* "custom" (default, shadcn ScrollArea) or "native" (browser scrollbars
* via overflow auto).
*/
scrollbars: 'custom' | 'native';
/** Nav button variant; all nav buttons follow it. Default "ghost". */
navButtonVariant: 'ghost' | 'outline' | 'secondary' | 'default';
/** Nav button size; icon buttons use the icon twin. Default "sm". */
navButtonSize: 'sm' | 'default';
/**
* Off-day (non-working day) marking. true = weekends with a muted
* background; a config object customizes weekdays, explicit dates, a
* predicate, and the marker class. Marked cells carry data-off.
*/
offDays?: boolean | EventCalendarOffDaysConfig;
classNames?: EventCalendarClassNames;
components?: Partial<Record<CalendarView, ComponentType>>;
renderEvent?: (props: EventCalendarRenderEventProps<TData>) => ReactNode;
renderAgendaEvent?: (props: EventCalendarRenderEventProps<TData>) => ReactNode;
/**
* Content for the styled hover tooltip (viewConfig.eventTooltip). Return a
* falsy value (null / undefined, or the `false` a `cond && <node>` yields)
* to fall back to the default label (title + time); `label` itself is
* undefined when a consumer i18n.formatEventLabel opts out.
*/
renderEventTooltip?: (props: {
occurrence: EventCalendarOccurrence<TData>;
segment: EventCalendarSegment<TData>;
view: CalendarView;
label: string | undefined;
}) => ReactNode;
renderDragPreview?: (props: { drag: EventCalendarDragState<TData> }) => ReactNode;
renderMonthCell?: (props: {
day: Date;
segments: EventCalendarDayBucket<TData>;
isToday: boolean;
isOutside: boolean;
overflowCount: number;
defaultContent: ReactNode;
}) => ReactNode;
/**
* Time-grid business-logic layer, rendered pointer-events-none BEHIND event
* segments in each day column. Position overlays with
* top/height: calc(var(--ec-hour-height) * minutes / 60).
*/
renderDayColumnBackground?: (props: { day: Date; boundsStartMin: number; boundsEndMin: number; totalMinutes: number }) => ReactNode;
renderDayHeader?: (props: { day: Date; view: CalendarView; isToday: boolean }) => ReactNode;
renderTimeGutterSlot?: (props: { time: Date; hour: number; minute: number }) => ReactNode;
renderAllDaySection?: (props: { days: Date[]; segments: EventCalendarSegment<TData>[] }) => ReactNode;
renderMoreIndicator?: (props: { day: Date; count: number; segments: EventCalendarSegment<TData>[] }) => ReactNode;
/**
* Replaces the ENTIRE body of the built-in "+N more" popover (header +
* chip list) while keeping its trigger and positioning; `close` dismisses
* it. For a fully custom surface, return false from onMoreClick instead
* and open your own UI.
*/
renderMoreContent?: (props: { day: Date; segments: EventCalendarSegment<TData>[]; close: () => void }) => ReactNode;
/**
* Agenda-only expandable details. When it returns a node for an occurrence,
* the agenda row gains an expand/collapse toggle revealing the details
* below the chip (the calendar itself never knows the consumer's fields).
*/
renderAgendaEventDetails?: (occurrence: EventCalendarOccurrence<TData>) => ReactNode;
renderNowIndicator?: (props: { time: Date }) => ReactNode;
renderNoEvents?: () => ReactNode;
/** Resource column header cell content; default is resource.title. */
renderResourceHeader?: (props: { resource: EventCalendarResource }) => ReactNode;
/** Agenda date gutter (day badge + weekday + collapse toggle). */
renderAgendaDayHeader?: (props: { day: Date; collapsed: boolean; count: number; toggle: () => void; defaultContent: ReactNode }) => ReactNode;
/** Collapsed agenda day summary row content. */
renderAgendaDaySummary?: (props: {
day: Date;
occurrences: EventCalendarOccurrence<TData>[];
count: number;
expand: () => void;
defaultContent: ReactNode;
}) => ReactNode;
/**
* N-day presets offered by the view switcher when the "days" view is
* enabled. @default [5]
*/
dayCountPresets: number[];
/**
* Nav tooltips: false disables them all; an object tunes placement and
* timings. @default { side: "bottom", delay: 600, closeDelay: 0, timeout: 300 }
*/
navTooltips?:
| false
| {
side?: 'top' | 'bottom' | 'left' | 'right';
delay?: number;
closeDelay?: number;
timeout?: number;
};
/**
* Styled tooltip on event hover / keyboard focus. `false` (default) keeps
* only the native title attribute; `true` shows the standard Tooltip with
* the event label; an object also tunes the side and open delay. Content is
* overridable with renderEventTooltip. @default false
*/
eventTooltip?:
| boolean
| {
side?: 'top' | 'bottom' | 'left' | 'right';
delay?: number;
};
/**
* Timed events shorter than this render the compact single-row chip layout.
* @default 45
*/
compactEventMinutes: number;
/** "+N more" popover alignment against its trigger. @default "start" */
morePopoverAlign: 'start' | 'center' | 'end';
/** Now-indicator refresh cadence in milliseconds. @default 30000 */
nowIndicatorInterval: number;
/** Max color dots in a collapsed agenda day summary. @default 6 */
agendaSummaryMaxDots: number;
}
const DEFAULT_VIEW_CONFIG: EventCalendarViewConfig = {
scrollToHour: 7,
nowIndicator: true,
interval: 60,
maxEventsPerCell: 'auto',
showWeekNumbers: false,
enableShortcuts: true,
shortcutsScope: 'focus-within',
scrollMode: 'contained',
stickyNav: false,
showDayAddButton: false,
scrollbars: 'custom',
navButtonVariant: 'ghost',
navButtonSize: 'sm',
dayCountPresets: [5],
eventTooltip: false,
compactEventMinutes: 45,
morePopoverAlign: 'start',
nowIndicatorInterval: 30_000,
agendaSummaryMaxDots: 6,
};
const EventCalendarViewConfigContext = createContext<
// eslint-disable-next-line @typescript-eslint/no-explicit-any
EventCalendarViewConfig<any>
>(DEFAULT_VIEW_CONFIG);
/** Root-level display props + render overrides, for view components. */
function useEventCalendarViewConfig<TData = unknown>(): EventCalendarViewConfig<TData> {
return useContext(EventCalendarViewConfigContext);
}
const VIEW_CONFIG_KEYS: Array<keyof EventCalendarViewConfig> = [
'scrollToHour',
'nowIndicator',
'interval',
'maxEventsPerCell',
'showWeekNumbers',
'enableShortcuts',
'shortcutsScope',
'scrollMode',
'stickyNav',
'dayClassName',
'todayClassName',
'showDayAddButton',
'scrollbars',
'navButtonVariant',
'navButtonSize',
'offDays',
'classNames',
'components',
'renderEvent',
'renderAgendaEvent',
'renderEventTooltip',
'renderDragPreview',
'renderMonthCell',
'renderDayColumnBackground',
'renderDayHeader',
'renderTimeGutterSlot',
'renderAllDaySection',
'renderMoreIndicator',
'renderMoreContent',
'renderNowIndicator',
'renderNoEvents',
'renderAgendaEventDetails',
'renderResourceHeader',
'renderAgendaDayHeader',
'renderAgendaDaySummary',
'dayCountPresets',
'navTooltips',
'eventTooltip',
'compactEventMinutes',
'morePopoverAlign',
'nowIndicatorInterval',
'agendaSummaryMaxDots',
];
/** The rendering view of the nearest view component ("month", "week", ...). */
function useEventCalendarViewContext(): { view: CalendarView } {
const ctx = useContext(EventCalendarViewContext);
if (!ctx) {
throw new Error('useEventCalendarViewContext must be used inside a calendar view');
}
return ctx;
}
interface EventCalendarProps<TData = unknown>
extends
UseEventCalendarStateOptions<TData>,
Partial<EventCalendarViewConfig<TData>>,
Omit<useRender.ComponentProps<'div'>, 'children' | 'defaultValue'> {
/** Adopt a hoisted useEventCalendarState instance; option props are then ignored. */
calendar?: EventCalendarInstance<TData>;
/** Imperative escape hatch usable from outside the tree. */
apiRef?: RefObject<EventCalendarApi<TData> | null>;
children?: ReactNode;
}
const OPTION_KEYS: Array<keyof UseEventCalendarStateOptions> = [
'events',
'defaultEvents',
'view',
'defaultView',
'date',
'defaultDate',
'dayCount',
'defaultDayCount',
'selection',
'defaultSelection',
'interactions',
'defaultInteractions',
'viewSettings',
'defaultViewSettings',
'loading',
'views',
'timeZone',
'locale',
'weekStartsOn',
'dayStartHour',
'dayEndHour',
'slotDuration',
'snapDuration',
'agendaDayCount',
'fixedWeeks',
'showOutsideDays',
'i18n',
'resources',
'getEventPriority',
'eventOrder',
'getOccurrences',
'weekendDays',
'activation',
'onEventClick',
'onEventDoubleClick',
'onEventUpdate',
'canDropEvent',
'onDragBlocked',
'onSlotClick',
'onSelectSlot',
'canSelectSlot',
'onRangeChange',
'onViewChange',
'onDateChange',
'onDayCountChange',
'onSelectionChange',
'onInteractionsChange',
'onViewSettingsChange',
'onEventsChange',
'onMoreClick',
];
function splitOptions<TData>(props: Record<string, unknown>): {
options: UseEventCalendarStateOptions<TData>;
viewConfig: EventCalendarViewConfig<TData>;
rest: Record<string, unknown>;
} {
const options: Record<string, unknown> = {};
const viewConfig: Record<string, unknown> = { ...DEFAULT_VIEW_CONFIG };
const rest: Record<string, unknown> = {};
for (const [key, value] of Object.entries(props)) {
if ((OPTION_KEYS as string[]).includes(key)) options[key] = value;
else if ((VIEW_CONFIG_KEYS as string[]).includes(key)) {
if (value !== undefined) viewConfig[key] = value;
} else rest[key] = value;
}
return {
options: options as UseEventCalendarStateOptions<TData>,
viewConfig: viewConfig as unknown as EventCalendarViewConfig<TData>,
rest,
};
}
/**
* Root provider + container. Composition contract:
* <EventCalendar><EventCalendarNav/><EventCalendarToolbar/><EventCalendarContent/></EventCalendar>
*/
function EventCalendar<TData = unknown>({ calendar, apiRef, className, render, children, ...props }: EventCalendarProps<TData>) {
const { options, viewConfig, rest } = splitOptions<TData>(props as Record<string, unknown>);
if (calendar && Object.keys(options).length > 0) {
warnOnce('calendar-and-options', 'both `calendar` and option props were passed; option props are ignored when adopting an instance.');
}
const own = useEventCalendarState<TData>(calendar ? {} : options);
const instance = calendar ?? own;
useEffect(() => {
if (apiRef) apiRef.current = instance.api;
}, [apiRef, instance]);
// Register the root element so the drag engine can find day cells even when a
// gesture starts from a portaled surface (the "+N more" popover).
const registerRoot = useCallback((el: HTMLElement | null) => instance.internals.setRootEl(el), [instance]);
const defaultProps = {
'data-slot': 'event-calendar',
ref: registerRoot,
// text-xs is the calendar-wide default type size; because it sits before
// `className`, a consumer can override the whole scale with e.g.
// <EventCalendar className="text-sm"> and every inheriting element follows.
// Inner elements omit their own text-size so they cascade from here (the
// few portaled surfaces - "+N more" popover, drag carry clone - pin the
// size explicitly since DOM inheritance does not cross a portal).
className: cn('flex min-h-0 min-w-0 flex-col text-xs', className),
children: (
<>
{children}
<div data-slot="event-calendar-announcer" aria-live="polite" className="sr-only" />
</>
),
};
return (
<EventCalendarContext.Provider value={instance}>
<EventCalendarViewConfigContext.Provider value={viewConfig}>
{useRender({
defaultTagName: 'div',
render,
props: mergeProps<'div'>(defaultProps, rest),
})}
</EventCalendarViewConfigContext.Provider>
</EventCalendarContext.Provider>
);
}
export {
ALL_VIEWS,
BASE_VIEWS,
DEFAULT_VIEW_CONFIG,
EventCalendar,
EventCalendarContext,
EventCalendarViewConfigContext,
EventCalendarViewContext,
useEventCalendar,
useEventCalendarDay,
useEventCalendarWeek,
useEventCalendarInteractions,
useEventCalendarNavigation,
useEventCalendarOccurrences,
useEventCalendarSelection,
useEventCalendarSelector,
useEventCalendarSettings,
useEventCalendarSettingsVersion,
useEventCalendarState,
useEventCalendarView,
useEventCalendarViewConfig,
useEventCalendarViewContext,
useEventCalendarViewSettings,
};
export type {
EventCalendarActivationConfig,
EventCalendarApi,
EventCalendarCallbacks,
EventCalendarClassNames,
EventCalendarInstance,
EventCalendarInternals,
EventCalendarProps,
EventCalendarRenderEventProps,
EventCalendarSettings,
EventCalendarViewConfig,
UseEventCalendarStateOptions,
};Usage
import { ALL_VIEWS, BASE_VIEWS, DEFAULT_VIEW_CONFIG, EventCalendar, EventCalendarContext, EventCalendarViewConfigContext } from "@/components/ui/event-calendar/event-calendar"Exports
ALL_VIEWS, BASE_VIEWS, DEFAULT_VIEW_CONFIG, EventCalendar, EventCalendarContext, EventCalendarViewConfigContext, EventCalendarViewContext, useEventCalendar, useEventCalendarDay, useEventCalendarWeek, useEventCalendarInteractions, useEventCalendarNavigation, useEventCalendarOccurrences, useEventCalendarSelection, useEventCalendarSelector, useEventCalendarSettings, useEventCalendarSettingsVersion, useEventCalendarState, useEventCalendarView, useEventCalendarViewConfig, useEventCalendarViewContext, useEventCalendarViewSettings
Dependencies
@base-ui/react@^1.9.0(npm)@date-fns/tz@^1.5.0(npm)date-fns@^4.4.0(npm)lucide-react@^1.80.0(npm)@vcare/icon-stack(registry)@vcare/popover(registry)@vcare/scroll-area(registry)@vcare/tooltip(registry)@vcare/utils(registry)
Raw item: /r/event-calendar.json