Rallly is an open-source scheduling and collaboration tool designed to make organizing events and meetings easier.
TypeScript i18nextnext-authnextjspostgresqlprismareact-emailt3-stacktailwindcsstrpcturborepotypescriptzod
♻️ Replace react-big-calendar with vendored ReUI event calendar (RAL-1409) (#2746)
Luke Vella4a0f6971a6c5
diff --git a/apps/web/package.json b/apps/web/package.jsonindex 5045e345a..c4fb92efb 100644--- a/apps/web/package.json+++ b/apps/web/package.json@@ -88,7 +88,6 @@"php-serialize": "^4.1.1","postcss": "^8.5.6","react": "19.2.6",- "react-big-calendar": "^1.8.1","react-dom": "19.2.6","react-hook-form": "^7.68.0","react-hook-form-persist": "^3.0.0",@@ -117,7 +116,6 @@"@types/lodash": "^4.14.178","@types/node": "^24.1.0","@types/react": "19.2.13",- "@types/react-big-calendar": "^1.8.8","@types/react-dom": "19.2.3","@types/smoothscroll-polyfill": "^0.3.1","@types/zxcvbn": "^4.4.5",diff --git a/apps/web/public/locales/en/app.json b/apps/web/public/locales/en/app.jsonindex 2d7fe4aeb..1c4d15400 100644--- a/apps/web/public/locales/en/app.json+++ b/apps/web/public/locales/en/app.json@@ -445,6 +445,7 @@"newPassword": "New Password","newPoll": "New Poll","nextMonth": "Next month",+ "nextWeek": "Next week","no": "No","noApiKeys": "No API keys found","noApiKeysDescription": "Create an API key to access your space programmatically",@@ -539,6 +540,7 @@"preferences": "Preferences","preferencesDescription": "Manage your preferences","previousMonth": "Previous month",+ "previousWeek": "Previous week","priceFree": "Free","primaryColor": "Primary Color","primaryColorDark": "Primary Color (Dark Mode)",diff --git a/apps/web/src/features/poll/components/forms/poll-options-form/date-navigation-toolbar.tsx b/apps/web/src/features/poll/components/forms/poll-options-form/date-navigation-toolbar.tsxindex 70a5873ab..008ad2dab 100644--- a/apps/web/src/features/poll/components/forms/poll-options-form/date-navigation-toolbar.tsx+++ b/apps/web/src/features/poll/components/forms/poll-options-form/date-navigation-toolbar.tsx@@ -5,7 +5,6 @@ import type * as React from "react";import { useTranslation } from "@/i18n/client";export interface DateNavigationToolbarProps {- year: number;label: string;onPrevious: () => void;onNext: () => void;@@ -14,26 +13,38 @@ export interface DateNavigationToolbarProps {const DateNavigationToolbar: React.FunctionComponent<DateNavigationToolbarProps-> = ({ year, label, onPrevious, onToday, onNext }) => {+> = ({ label, onPrevious, onToday, onNext }) => {const { t } = useTranslation();return (- <div className="flex h-14 w-full shrink-0 items-center px-4">- <div className="grow font-semibold tracking-tight">- <span className="mr-2 font-normal text-muted-foreground text-sm">- {year}- </span>- <span className="font-semibold">{label}</span>+ <div className="flex w-full shrink-0 items-center gap-4 px-4 py-3">+ <div className="grow">+ <span className="text-sm">{label}</span></div>- <div className="flex items-center space-x-2">- <div className="flex items-center gap-x-2">- <Button type="button" onClick={onPrevious}>- <ChevronLeftIcon className="size-4" />- </Button>- <Button onClick={onToday}>{t("today")}</Button>- <Button onClick={onNext}>- <ChevronRightIcon className="size-4" />- </Button>- </div>+ <div className="flex items-center gap-1">+ <Button variant="ghost" size="sm" onClick={onToday}>+ {t("today")}+ </Button>+ <Button+ variant="ghost"+ size="icon-sm"+ type="button"+ onClick={onPrevious}+ >+ <ChevronLeftIcon className="size-4" />+ <span className="sr-only">+ {t("previousWeek", {+ defaultValue: "Previous week",+ })}+ </span>+ </Button>+ <Button variant="ghost" size="icon-sm" onClick={onNext}>+ <ChevronRightIcon className="size-4" />+ <span className="sr-only">+ {t("nextWeek", {+ defaultValue: "Next week",+ })}+ </span>+ </Button></div></div>);diff --git a/apps/web/src/features/poll/components/forms/poll-options-form/dayjs-localizer.test.ts b/apps/web/src/features/poll/components/forms/poll-options-form/dayjs-localizer.test.tsdeleted file mode 100644index 2bec7fdf2..000000000--- a/apps/web/src/features/poll/components/forms/poll-options-form/dayjs-localizer.test.ts+++ /dev/null@@ -1,64 +0,0 @@-import { describe, expect, it } from "vitest";-import { dayjs } from "@/lib/dayjs";-import dayjsLocalizer from "./dayjs-localizer";--// The DateLocalizer typings omit the week unit react-big-calendar passes at-// runtime, so widen to the shape under test.-const createLocalizer = (weekStart?: number) =>- dayjsLocalizer(dayjs, { weekStart }) as unknown as {- startOfWeek: () => number;- startOf: (date: Date, unit: string) => Date;- endOf: (date: Date, unit: string) => Date;- eq: (a: Date, b: Date, unit: string) => boolean;- };--// 2026-07-14 is a Tuesday-const tuesday = new Date(2026, 6, 14, 12, 0, 0);--describe("dayjsLocalizer weekStart", () => {- it("defaults to the dayjs locale week start when no weekStart is given", () => {- const localizer = createLocalizer();- expect(localizer.startOfWeek()).toBe(0);- expect(localizer.startOf(tuesday, "week")).toEqual(- new Date(2026, 6, 12, 0, 0, 0),- );- });-- it("starts the week on Monday when weekStart is 1", () => {- const localizer = createLocalizer(1);- expect(localizer.startOfWeek()).toBe(1);- expect(localizer.startOf(tuesday, "week")).toEqual(- new Date(2026, 6, 13, 0, 0, 0),- );- expect(localizer.endOf(tuesday, "week")).toEqual(- new Date(2026, 6, 19, 23, 59, 59, 999),- );- });-- it("starts the week on Saturday when weekStart is 6", () => {- const localizer = createLocalizer(6);- expect(localizer.startOf(tuesday, "week")).toEqual(- new Date(2026, 6, 11, 0, 0, 0),- );- expect(localizer.endOf(tuesday, "week")).toEqual(- new Date(2026, 6, 17, 23, 59, 59, 999),- );- });-- it("keeps a date already on the week start day in place", () => {- const localizer = createLocalizer(1);- const monday = new Date(2026, 6, 13, 8, 30, 0);- expect(localizer.startOf(monday, "week")).toEqual(- new Date(2026, 6, 13, 0, 0, 0),- );- });-- it("compares dates by the configured week boundary", () => {- const localizer = createLocalizer(1);- const sunday = new Date(2026, 6, 12);- const monday = new Date(2026, 6, 13);- // With Monday as week start, Sunday belongs to the previous week- expect(localizer.eq(sunday, monday, "week")).toBe(false);- expect(localizer.eq(monday, tuesday, "week")).toBe(true);- });-});diff --git a/apps/web/src/features/poll/components/forms/poll-options-form/dayjs-localizer.ts b/apps/web/src/features/poll/components/forms/poll-options-form/dayjs-localizer.tsdeleted file mode 100644index dca2728a0..000000000--- a/apps/web/src/features/poll/components/forms/poll-options-form/dayjs-localizer.ts+++ /dev/null@@ -1,381 +0,0 @@-// @ts-nocheck-import { DateLocalizer } from "react-big-calendar";--const weekRangeFormat = ({ start, end }, culture, local) =>- local.format(start, "MMMM DD", culture) +- " – " +- local.format(end, local.eq(start, end, "month") ? "DD" : "MMMM DD", culture);--const dateRangeFormat = ({ start, end }, culture, local) =>- // biome-ignore lint/style/useTemplate: Fix this later- local.format(start, "L", culture) + " – " + local.format(end, "L", culture);--const timeRangeFormat = ({ start, end }, culture, local) =>- // biome-ignore lint/style/useTemplate: Fix this later- local.format(start, "LT", culture) + " – " + local.format(end, "LT", culture);--const timeRangeStartFormat = ({ start }, culture, local) =>- // biome-ignore lint/style/useTemplate: Fix this later- local.format(start, "LT", culture) + " – ";--const timeRangeEndFormat = ({ end }, culture, local) =>- // biome-ignore lint/style/useTemplate: Fix this later- " – " + local.format(end, "LT", culture);--export const formats = {- dateFormat: "DD",- dayFormat: "DD ddd",- weekdayFormat: "ddd",-- selectRangeFormat: timeRangeFormat,- eventTimeRangeFormat: timeRangeFormat,- eventTimeRangeStartFormat: timeRangeStartFormat,- eventTimeRangeEndFormat: timeRangeEndFormat,-- timeGutterFormat: "LT",-- monthHeaderFormat: "MMMM YYYY",- dayHeaderFormat: "dddd MMM DD",- dayRangeHeaderFormat: weekRangeFormat,- agendaHeaderFormat: dateRangeFormat,-- agendaDateFormat: "ddd MMM DD",- agendaTimeFormat: "LT",- agendaTimeRangeFormat: timeRangeFormat,-};--function fixUnit(unit) {- let datePart = unit ? unit.toLowerCase() : unit;- if (datePart === "FullYear") {- datePart = "year";- } else if (!datePart) {- datePart = undefined;- }- return datePart;-}--export default function (dayjs, { weekStart } = {}) {- const locale = (m, c) => (c ? m.locale(c) : m);-- function firstOfWeek() {- if (weekStart !== undefined) {- return weekStart;- }- const data = dayjs.localeData();- return data ? data.firstDayOfWeek() : 0;- }-- // dayjs' own startOf("week") uses the global locale's week start, so week- // boundaries are computed manually from the configured weekStart.- function startOfWeek(date) {- const day = dayjs(date).startOf("day");- return day.subtract((day.day() - firstOfWeek() + 7) % 7, "day");- }-- /*** BEGIN localized date arithmetic methods with dayjs ***/- function defineComparators(a, b, unit) {- const datePart = fixUnit(unit);- if (datePart === "week") {- return [startOfWeek(a), startOfWeek(b), "day"];- }- const dtA = datePart ? dayjs(a).startOf(datePart) : dayjs(a);- const dtB = datePart ? dayjs(b).startOf(datePart) : dayjs(b);- return [dtA, dtB, datePart];- }-- // biome-ignore lint/style/useDefaultParameterLast: Fix this later- function startOf(date = null, unit) {- const datePart = fixUnit(unit);- if (datePart === "week") {- return startOfWeek(date).toDate();- }- if (datePart) {- return dayjs(date).startOf(datePart).toDate();- }- return dayjs(date).toDate();- }-- // biome-ignore lint/style/useDefaultParameterLast: Fix this later- function endOf(date = null, unit) {- const datePart = fixUnit(unit);- if (datePart === "week") {- return startOfWeek(date).add(6, "day").endOf("day").toDate();- }- if (datePart) {- return dayjs(date).endOf(datePart).toDate();- }- return dayjs(date).toDate();- }-- // dayjs comparison operations *always* convert both sides to dayjs objects- // prior to running the comparisons- function eq(a, b, unit) {- const [dtA, dtB, datePart] = defineComparators(a, b, unit);- return dtA.isSame(dtB, datePart);- }-- function neq(a, b, unit) {- return !eq(a, b, unit);- }-- function gt(a, b, unit) {- const [dtA, dtB, datePart] = defineComparators(a, b, unit);- return dtA.isAfter(dtB, datePart);- }-- function lt(a, b, unit) {- const [dtA, dtB, datePart] = defineComparators(a, b, unit);- return dtA.isBefore(dtB, datePart);- }-- function gte(a, b, unit) {- const [dtA, dtB, datePart] = defineComparators(a, b, unit);- return dtA.isSameOrBefore(dtB, datePart);- }-- function lte(a, b, unit) {- const [dtA, dtB, datePart] = defineComparators(a, b, unit);- return dtA.isSameOrBefore(dtB, datePart);- }-- function inRange(day, min, max, unit = "day") {- const datePart = fixUnit(unit);- const mDay = dayjs(day);- const mMin = dayjs(min);- const mMax = dayjs(max);- return mDay.isBetween(mMin, mMax, datePart, "[]");- }-- function min(dateA, dateB) {- const dtA = dayjs(dateA);- const dtB = dayjs(dateB);- const minDt = dayjs.min(dtA, dtB);- return minDt.toDate();- }-- function max(dateA, dateB) {- const dtA = dayjs(dateA);- const dtB = dayjs(dateB);- const maxDt = dayjs.max(dtA, dtB);- return maxDt.toDate();- }-- function merge(date, time) {- if (!date && !time) return null;-- const tm = dayjs(time).format("HH:mm:ss");- const dt = dayjs(date).startOf("day").format("MM/DD/YYYY");- // We do it this way to avoid issues when timezone switching- return dayjs(`${dt} ${tm}`, "MM/DD/YYYY HH:mm:ss").toDate();- }-- function add(date, adder, unit) {- const datePart = fixUnit(unit);- return dayjs(date).add(adder, datePart).toDate();- }-- function range(start, end, unit = "day") {- const datePart = fixUnit(unit);- // because the add method will put these in tz, we have to start that way- let current = dayjs(start).toDate();- const days = [];-- while (lte(current, end)) {- days.push(current);- current = add(current, 1, datePart);- }-- return days;- }-- function ceil(date, unit) {- const datePart = fixUnit(unit);- const floor = startOf(date, datePart);-- return eq(floor, date) ? floor : add(floor, 1, datePart);- }-- function diff(a, b, unit = "day") {- const datePart = fixUnit(unit);- // don't use 'defineComparators' here, as we don't want to mutate the values- const dtA = dayjs(a);- const dtB = dayjs(b);- return dtB.diff(dtA, datePart);- }-- function minutes(date) {- const dt = dayjs(date);- return dt.minutes();- }-- function firstVisibleDay(date) {- return startOfWeek(dayjs(date).startOf("month")).toDate();- }-- function lastVisibleDay(date) {- return endOf(dayjs(date).endOf("month").toDate(), "week");- }-- function visibleDays(date) {- let current = firstVisibleDay(date);- const last = lastVisibleDay(date);- const days = [];-- while (lte(current, last)) {- days.push(current);- current = add(current, 1, "d");- }-- return days;- }- /*** END localized date arithmetic methods with dayjs ***/-- /**- * Moved from TimeSlots.js, this method overrides the method of the same name- * in the localizer.js, using dayjs to construct the js Date- * @param {Date} dt - date to start with- * @param {Number} minutesFromMidnight- * @param {Number} offset- * @returns {Date}- */- function getSlotDate(dt, minutesFromMidnight, offset) {- return dayjs(dt)- .startOf("day")- .minute(minutesFromMidnight + offset)- .toDate();- }-- // dayjs will automatically handle DST differences in it's calculations- function getTotalMin(start, end) {- return diff(start, end, "minutes");- }-- function getMinutesFromMidnight(start) {- const dayStart = dayjs(start).startOf("day");- const day = dayjs(start);- return day.diff(dayStart, "minutes");- }-- // These two are used by DateSlotMetrics- function continuesPrior(start, first) {- const mStart = dayjs(start);- const mFirst = dayjs(first);- return mStart.isBefore(mFirst, "day");- }-- function continuesAfter(_start, end, last) {- const mEnd = dayjs(end);- const mLast = dayjs(last);- return mEnd.isSameOrAfter(mLast, "minutes");- }-- // These two are used by eventLevels- function sortEvents({- evtA: { start: aStart, end: aEnd, allDay: aAllDay },- evtB: { start: bStart, end: bEnd, allDay: bAllDay },- }) {- const startSort = +startOf(aStart, "day") - +startOf(bStart, "day");-- const durA = diff(aStart, ceil(aEnd, "day"), "day");-- const durB = diff(bStart, ceil(bEnd, "day"), "day");-- return (- startSort || // sort by start Day first- Math.max(durB, 1) - Math.max(durA, 1) || // events spanning multiple days go first- !!bAllDay - !!aAllDay || // then allDay single day events- +aStart - +bStart || // then sort by start time *don't need dayjs conversion here- +aEnd - +bEnd // then sort by end time *don't need dayjs conversion here either- );- }-- function inEventRange({- event: { start, end },- range: { start: rangeStart, end: rangeEnd },- }) {- const startOfDay = dayjs(start).startOf("day");- const eEnd = dayjs(end);- const rStart = dayjs(rangeStart);- const rEnd = dayjs(rangeEnd);-- const startsBeforeEnd = startOfDay.isSameOrBefore(rEnd, "day");- // when the event is zero duration we need to handle a bit differently- const sameMin = !startOfDay.isSame(eEnd, "minutes");- const endsAfterStart = sameMin- ? eEnd.isAfter(rStart, "minutes")- : eEnd.isSameOrAfter(rStart, "minutes");-- return startsBeforeEnd && endsAfterStart;- }-- // dayjs treats 'day' and 'date' equality very different- // dayjs(date1).isSame(date2, 'day') would test that they were both the same day of the week- // dayjs(date1).isSame(date2, 'date') would test that they were both the same date of the month of the year- function isSameDate(date1, date2) {- const dt = dayjs(date1);- const dt2 = dayjs(date2);- return dt.isSame(dt2, "date");- }-- /**- * This method, called once in the localizer constructor, is used by eventLevels- * 'eventSegments()' to assist in determining the 'span' of the event in the display,- * specifically when using a timezone that is greater than the browser native timezone.- * @returns number- */- function browserTZOffset() {- /**- * Date.prototype.getTimezoneOffset horrifically flips the positive/negative from- * what you see in it's string, so we have to jump through some hoops to get a value- * we can actually compare.- */- const dt = new Date();- const neg = /-/.test(dt.toString()) ? "-" : "";- const dtOffset = dt.getTimezoneOffset();- const comparator = Number(`${neg}${Math.abs(dtOffset)}`);- // dayjs correctly provides positive/negative offset, as expected- const mtOffset = dayjs().utcOffset();- return mtOffset > comparator ? 1 : 0;- }-- return new DateLocalizer({- formats,-- firstOfWeek,- firstVisibleDay,- lastVisibleDay,- visibleDays,-- format(value, format, culture) {- return locale(dayjs(value), culture).format(format);- },-- lt,- lte,- gt,- gte,- eq,- neq,- merge,- inRange,- startOf,- endOf,- range,- add,- diff,- ceil,- min,- max,- minutes,-- getSlotDate,- getTotalMin,- getMinutesFromMidnight,- continuesPrior,- continuesAfter,- sortEvents,- inEventRange,- isSameDate,- browserTZOffset,- });-}diff --git a/apps/web/src/features/poll/components/forms/poll-options-form/rbc-overrides.css b/apps/web/src/features/poll/components/forms/poll-options-form/rbc-overrides.cssdeleted file mode 100644index 13ce82d36..000000000--- a/apps/web/src/features/poll/components/forms/poll-options-form/rbc-overrides.css+++ /dev/null@@ -1,78 +0,0 @@-.rbc-time-view {- border: 0;- border-bottom: 1px solid var(--color-border-muted);- border-top: 1px solid var(--color-border-muted);-}--.rbc-today {- background-color: color-mix(in srgb, var(--color-muted) 50%, transparent);-}--.rbc-time-content > * + * > * {- border-color: var(--color-border);-}--.rbc-time-header.rbc-overflowing,-.rbc-time-header-content,-.rbc-header {- border-color: var(--color-border-muted);-}--.rbc-time-content {- border-top: 0;-}--.rbc-time-view .rbc-allday-cell {- display: none;-}--.rbc-current-time-indicator {- background-color: var(--color-rose-400);-}--.rbc-header + .rbc-header {- border-left: 0;-}--.rbc-time-slot {- padding-left: 0.5rem;- padding-top: 0.25rem;-}--.rbc-timeslot-group {- border-color: var(--color-border-muted);-}--.rbc-day-slot .rbc-time-slot {- border-style: dashed;- border-color: var(--color-border-muted);-}--.rbc-day-slot .rbc-events-container {- margin-right: 0.5rem;-}--.rbc-slot-selection {- background-color: color-mix(- in srgb,- var(--color-border-muted) 50%,- transparent- );- line-height: 1.25;- color: var(--color-gray-600);-}--.rbc-header.rbc-today {- color: var(--color-rose-500);- background-color: transparent;-}--.rbc-button-link {- pointer-events: none;- margin: 0.25rem;- width: 100%;-}--.rbc-time-header-gutter {- border-bottom: 1px solid var(--color-border-muted);-}diff --git a/apps/web/src/features/poll/components/forms/poll-options-form/week-calendar-utils.test.ts b/apps/web/src/features/poll/components/forms/poll-options-form/week-calendar-utils.test.tsnew file mode 100644index 000000000..49a419928--- /dev/null+++ b/apps/web/src/features/poll/components/forms/poll-options-form/week-calendar-utils.test.ts@@ -0,0 +1,104 @@+import { describe, expect, it } from "vitest";+import type { DateTimeOption } from "./types";+import {+ DURATION_CAP_MINUTES,+ durationMinutes,+ eventId,+ isDuplicate,+ optionsToEvents,+ slotToTimeOption,+} from "./week-calendar-utils";++const d = (s: string) => new Date(s);++describe("eventId", () => {+ it("is stable and distinct per option identity", () => {+ const slot: DateTimeOption = {+ type: "timeSlot",+ start: "2026-07-21T14:00:00",+ end: "2026-07-21T15:00:00",+ };+ expect(eventId(slot)).toBe(eventId({ ...slot }));+ expect(eventId(slot)).not.toBe(+ eventId({ type: "date", date: "2026-07-21" }),+ );+ });+});++describe("optionsToEvents", () => {+ it("maps a timeSlot to a timed event", () => {+ const events = optionsToEvents([+ {+ type: "timeSlot",+ start: "2026-07-21T14:00:00",+ end: "2026-07-21T15:00:00",+ },+ ]);+ expect(events).toHaveLength(1);+ expect(events[0].allDay).toBeFalsy();+ expect(events[0].start).toEqual(d("2026-07-21T14:00:00"));+ expect(events[0].end).toEqual(d("2026-07-21T15:00:00"));+ });++ it("maps a date option to a local, next-day-exclusive all-day event", () => {+ const events = optionsToEvents([{ type: "date", date: "2026-07-21" }]);+ expect(events[0].allDay).toBe(true);+ // Local midnight, not UTC (new Date("2026-07-21") would be UTC midnight).+ expect(events[0].start).toEqual(d("2026-07-21T00:00:00"));+ // Exclusive end at the next local day boundary, never zero-length.+ expect(events[0].end).toEqual(d("2026-07-22T00:00:00"));+ });+});++describe("slotToTimeOption", () => {+ it("round-trips through naive-local strings", () => {+ const opt = slotToTimeOption(+ d("2026-07-21T14:00:00"),+ d("2026-07-21T15:30:00"),+ );+ expect(opt).toEqual({+ type: "timeSlot",+ start: "2026-07-21T14:00:00",+ end: "2026-07-21T15:30:00",+ });+ });+});++describe("isDuplicate", () => {+ const existing: DateTimeOption[] = [+ {+ type: "timeSlot",+ start: "2026-07-21T14:00:00",+ end: "2026-07-21T15:00:00",+ },+ ];+ it("detects an identical start+end", () => {+ expect(+ isDuplicate(existing, {+ type: "timeSlot",+ start: "2026-07-21T14:00:00",+ end: "2026-07-21T15:00:00",+ }),+ ).toBe(true);+ });+ it("allows a different end", () => {+ expect(+ isDuplicate(existing, {+ type: "timeSlot",+ start: "2026-07-21T14:00:00",+ end: "2026-07-21T16:00:00",+ }),+ ).toBe(false);+ });+});++describe("durationMinutes / cap", () => {+ it("computes minute difference", () => {+ expect(+ durationMinutes(d("2026-07-21T14:00:00"), d("2026-07-21T15:30:00")),+ ).toBe(90);+ });+ it("cap is 24h", () => {+ expect(DURATION_CAP_MINUTES).toBe(1440);+ });+});diff --git a/apps/web/src/features/poll/components/forms/poll-options-form/week-calendar-utils.ts b/apps/web/src/features/poll/components/forms/poll-options-form/week-calendar-utils.tsnew file mode 100644index 000000000..01b29611a--- /dev/null+++ b/apps/web/src/features/poll/components/forms/poll-options-form/week-calendar-utils.ts@@ -0,0 +1,60 @@+import type { CalendarEvent } from "@rallly/ui/event-calendar";+import { dayjs } from "@/lib/dayjs";+import type { DateTimeOption, TimeOption } from "./types";+import { formatDateWithoutTz } from "./utils";++export const DURATION_CAP_MINUTES = 60 * 24;++export function eventId(option: DateTimeOption): string {+ return option.type === "date"+ ? `date:${option.date}`+ : `slot:${option.start}_${option.end}`;+}++export function optionsToEvents(options: DateTimeOption[]): CalendarEvent[] {+ return options.map((option) => {+ if (option.type === "date") {+ // Parse the date-only value as LOCAL midnight (new Date("YYYY-MM-DD")+ // would parse as UTC), and give the all-day event an exclusive end at the+ // next local day boundary rather than a zero-length span.+ const start = dayjs(option.date).startOf("day");+ return {+ id: eventId(option),+ title: "",+ start: start.toDate(),+ end: start.add(1, "day").toDate(),+ allDay: true,+ };+ }+ return {+ id: eventId(option),+ title: "",+ start: new Date(option.start),+ end: new Date(option.end),+ };+ });+}++export function slotToTimeOption(start: Date, end: Date): TimeOption {+ return {+ type: "timeSlot",+ start: formatDateWithoutTz(start),+ end: formatDateWithoutTz(end),+ };+}++export function isDuplicate(+ options: DateTimeOption[],+ candidate: TimeOption,+): boolean {+ return options.some(+ (option) =>+ option.type === "timeSlot" &&+ option.start === candidate.start &&+ option.end === candidate.end,+ );+}++export function durationMinutes(start: Date, end: Date): number {+ return dayjs(end).diff(start, "minutes");+}diff --git a/apps/web/src/features/poll/components/forms/poll-options-form/week-calendar.tsx b/apps/web/src/features/poll/components/forms/poll-options-form/week-calendar.tsxindex 129d303e7..c2fd2945c 100644--- a/apps/web/src/features/poll/components/forms/poll-options-form/week-calendar.tsx+++ b/apps/web/src/features/poll/components/forms/poll-options-form/week-calendar.tsx@@ -1,31 +1,63 @@-import "react-big-calendar/lib/css/react-big-calendar.css";-import "./rbc-overrides.css";+"use client";-import { XIcon } from "lucide-react";+import type {+ CalendarView,+ EventCalendarApi,+ EventCalendarOccurrence,+ EventCalendarProposedUpdate,+ EventCalendarSlotDraft,+ EventCalendarSlotInfo,+ EventCalendarUpdateResult,+} from "@rallly/ui/event-calendar";+import {+ EventCalendar,+ EventCalendarContent,+ EventCalendarDayView,+ EventCalendarWeekView,+ useEventCalendarNavigation,+} from "@rallly/ui/event-calendar";import React from "react";-import type { CalendarProps } from "react-big-calendar";-import { Calendar } from "react-big-calendar";import { createBreakpoint } from "react-use";import { useDateTime, useDateTimeConfig } from "@/lib/datetime/client";-import {- formatDateParts,- formatDateTime,- formatDateTimeRange,-} from "@/lib/datetime/format";-import { dayjs } from "@/lib/dayjs";+import { getBrowserTimeZone } from "@/lib/utils/date-time-utils";import DateNavigationToolbar from "./date-navigation-toolbar";-import dayjsLocalizer from "./dayjs-localizer";-import type { DateTimeOption, DateTimePickerProps } from "./types";-import { formatDateWithoutTz } from "./utils";+import type { DateTimePickerProps } from "./types";+import {+ DURATION_CAP_MINUTES,+ durationMinutes,+ isDuplicate,+ optionsToEvents,+ slotToTimeOption,+} from "./week-calendar-utils";const useDevice = createBreakpoint({ desktop: 720, mobile: 360 });-/**- * Not sure what's wrong with the type definitions for react-big-calendar but it's not working properly.- * This is a temporary fix that overrides their types which ideally we wouldn't have to do.- */-const CalendarTempFix = Calendar as React.ComponentType<CalendarProps>;+// The week/day picker only creates timed slots; all-day (date) options are a+// month-view concept. Hide the all-day lane so it isn't a dead interactive+// surface (rbc hid it too, via CSS).+const WeekViewNoAllDay = () => <EventCalendarWeekView showAllDay={false} />;+const DayViewNoAllDay = () => <EventCalendarDayView showAllDay={false} />;+const VIEW_COMPONENTS = { week: WeekViewNoAllDay, day: DayViewNoAllDay };++// ReUI's grid needs a fixed IANA zone to lay out days/hours. The poll form+// stores naive wall-clock strings with no zone of their own, so this zone is+// used purely as a rendering frame — every option <-> event conversion still+// goes through the Task 4 helpers (formatDateWithoutTz), never a real zone+// conversion of stored values.+const RENDER_TIME_ZONE = getBrowserTimeZone();++function CalendarToolbar() {+ const { title, next, prev, today } = useEventCalendarNavigation();+ return (+ <DateNavigationToolbar+ label={title}+ onPrevious={prev}+ onNext={next}+ onToday={today}+ />+ );+}const WeekCalendar: React.FunctionComponent<DateTimePickerProps> = ({options,@@ -35,193 +67,192 @@ const WeekCalendar: React.FunctionComponent<DateTimePickerProps> = ({duration = 60,onChangeDuration,}) => {- const { locale, timeFormat, weekStart } = useDateTimeConfig();- const { formatDuration } = useDateTime();+ const { weekStart } = useDateTimeConfig();+ const { formatDateTime, formatDateTimeRange } = useDateTime();++ const apiRef = React.useRef<EventCalendarApi | null>(null);+ const hasScrolledRef = React.useRef(false);- const localizer = React.useMemo(- () => dayjsLocalizer(dayjs, { weekStart }),- [weekStart],+ const events = React.useMemo(() => optionsToEvents(options), [options]);++ const defaultView = useDevice() === "mobile" ? "day" : "week";++ // The form works in naive local times; format in the render-frame zone.+ const formatTime = React.useCallback(+ (time: Date) =>+ formatDateTime(time, "time", { timeZone: RENDER_TIME_ZONE }),+ [formatDateTime],+ );++ const i18n = React.useMemo(+ () => ({+ functions: {+ formatTitle: (+ _view: CalendarView,+ ctx: { activeRange: { start: Date; end: Date } },+ ) =>+ formatDateTimeRange(+ ctx.activeRange.start,+ ctx.activeRange.end,+ "date",+ {+ timeZone: RENDER_TIME_ZONE,+ },+ ),+ formatEventTime: (start: Date, _end: Date, allDay: boolean) =>+ allDay ? "" : formatTime(start),+ formatDayRange: (range: { start: Date; end: Date }) =>+ formatDateTimeRange(range.start, range.end, "monthDay", {+ timeZone: RENDER_TIME_ZONE,+ }),+ },+ }),+ [formatDateTimeRange, formatTime],);- // The form works in naive local times; format in the system zone.- const formatTime = (time: Date) =>- formatDateTime(time, { preset: "time", locale, timeFormat });+ React.useEffect(() => {+ if (hasScrolledRef.current) return;+ const firstSlot = options.find((option) => option.type === "timeSlot");+ if (firstSlot) {+ hasScrolledRef.current = true;+ apiRef.current?.scrollToTime(new Date(firstSlot.start));+ }+ }, [options]);- const scrollToTime =- options.length > 0- ? options[0].type === "timeSlot"- ? new Date(options[0].start)- : undefined- : undefined;+ const handleSelectSlot = (slot: EventCalendarSlotDraft) => {+ // The all-day lane is a timed picker's dead zone: it would commit+ // midnight-to-midnight garbage slots. rbc hid this row entirely.+ if (slot.allDay) {+ return;+ }+ const candidate = slotToTimeOption(slot.start, slot.end);+ const diff = durationMinutes(slot.start, slot.end);+ if (diff < DURATION_CAP_MINUTES) {+ onChangeDuration(diff);+ }+ if (!isDuplicate(options, candidate)) {+ onChange([...options, candidate]);+ }+ };- const defaultView = useDevice() === "mobile" ? "day" : "week";+ const handleSlotClick = (slot: EventCalendarSlotInfo) => {+ if (slot.allDay) {+ return;+ }+ const start = slot.date;+ const end = new Date(start.getTime() + (duration || 60) * 60 * 1000);+ const candidate = slotToTimeOption(start, end);+ if (!isDuplicate(options, candidate)) {+ onChange([...options, candidate]);+ }+ };++ const handleEventClick = (occurrence: EventCalendarOccurrence) => {+ const clicked = slotToTimeOption(occurrence.start, occurrence.end);+ onChange(+ options.filter(+ (option) =>+ !(+ option.type === "timeSlot" &&+ option.start === clicked.start &&+ option.end === clicked.end+ ),+ ),+ );+ };++ const handleEventUpdate = (+ update: EventCalendarProposedUpdate,+ ): EventCalendarUpdateResult => {+ if (!update.occurrence) {+ return false;+ }+ const oldOption = slotToTimeOption(+ update.occurrence.start,+ update.occurrence.end,+ );+ const newOption = slotToTimeOption(update.start, update.end);++ const duplicatesAnother = options.some(+ (option) =>+ option.type === "timeSlot" &&+ option.start === newOption.start &&+ option.end === newOption.end &&+ !(option.start === oldOption.start && option.end === oldOption.end),+ );+ if (duplicatesAnother) {+ return false;+ }++ if (update.source.startsWith("resize")) {+ const diff = durationMinutes(update.start, update.end);+ if (diff < DURATION_CAP_MINUTES) {+ onChangeDuration(diff);+ }+ }++ onChange(+ options.map((option) =>+ option.type === "timeSlot" &&+ option.start === oldOption.start &&+ option.end === oldOption.end+ ? newOption+ : option,+ ),+ );++ return true;+ };return (- <div className="relative flex h-[600px]">- <CalendarTempFix+ <div key={defaultView} className="relative h-150">+ <EventCalendarclassName="absolute inset-0"- events={options.map((option) => {- if (option.type === "date") {- return { start: new Date(option.date) };- } else {- return {- start: new Date(option.start),- end: new Date(option.end),- };- }- })}- culture="default"- onNavigate={onNavigate}+ apiRef={apiRef}+ events={events}date={date}+ onDateChange={onNavigate}defaultView={defaultView}views={["week", "day"]}- selectable={true}- localizer={localizer}- onSelectEvent={(event) => {- onChange(- options.filter(- (option) =>- !(- option.type === "timeSlot" &&- event.start &&- option.start === formatDateWithoutTz(event.start) &&- event.end &&- option.end === formatDateWithoutTz(event.end)- ),- ),- );- }}- components={{- toolbar: function Toolbar(props) {- return (- <DateNavigationToolbar- year={props.date.getFullYear()}- label={props.label}- onPrevious={() => {- props.onNavigate("PREV");- }}- onToday={() => {- props.onNavigate("TODAY");- }}- onNext={() => {- props.onNavigate("NEXT");- }}- />- );- },- eventWrapper: function EventWraper(props) {- const start = dayjs(props.event.start);- const end = dayjs(props.event.end);- return (- // biome-ignore lint/a11y/noStaticElementInteractions: fix later- <div- // onClick prop doesn't work properly. Seems like some other element is cancelling the event before it reaches this element- onMouseUp={props.onClick}- className="group absolute ml-1 flex max-h-full flex-col justify-between overflow-hidden rounded-lg border border-popover-border bg-popover p-1 text-foreground text-xs shadow-xs backdrop-blur-sm hover:cursor-pointer"- style={{- top: `calc(${props.style?.top}% + 4px)`,- height: `calc(${props.style?.height}% - 8px)`,- left: `${props.style?.xOffset}%`,- width: `calc(${props.style?.width}%)`,- }}- >- <div className="absolute top-1.5 right-1.5 flex justify-end opacity-0 group-hover:opacity-100">- <XIcon className="size-3" />- </div>+ timeZone={RENDER_TIME_ZONE}+ weekStartsOn={weekStart as 0 | 1 | 2 | 3 | 4 | 5 | 6}+ slotDuration={15}+ snapDuration={30}+ i18n={i18n}+ renderTimeGutterSlot={({ time, hour, minute }) =>+ // The engine's default gutter uses date-fns with its own format+ // string, ignoring our 12h/24h preference. Render the hour label with+ // our Intl formatter instead. Suppress the day-start label (hour 0),+ // matching the default's top-edge suppression.+ hour === 0 && minute === 0 ? null : formatTime(time)+ }+ onSelectSlot={handleSelectSlot}+ onSlotClick={handleSlotClick}+ onEventClick={handleEventClick}+ onEventUpdate={handleEventUpdate}+ renderEvent={({ occurrence }) => {+ const start = occurrence.start;+ const end = occurrence.end;+ return (+ // A poll option is a PROPOSED time, not a confirmed event: a dotted+ // outline over a soft accent tint reads as "tentative". Kept visually+ // distinct from ReUI's dashed drag/resize ghost (which is fainter and+ // dashed, not dotted). Color flows from --ec-event-color.+ <div>+ <div><div>- <div className="font-semibold">- {formatTime(start.toDate())}- </div>- <div className="opacity-50">- {formatDuration(end.diff(start, "minute"))}- </div>+ {formatDateTimeRange(start, end, "time", {+ timeZone: RENDER_TIME_ZONE,+ })}</div>- <div>- <div className="opacity-50">{formatTime(end.toDate())}</div>- </div>- </div>- );- },- week: {- // biome-ignore lint/suspicious/noExplicitAny: Fix this later- header: function Header({ date }: any) {- const parts = formatDateParts(date, { locale });- return (- <span className="w-full rounded-md text-center text-xs tracking-tight">- <span className="mr-1.5 font-normal">{parts.weekday}</span>- <span className="font-medium">{parts.day}</span>- </span>- );- },- },- timeSlotWrapper: function TimeSlotWrapper({- children,- }: {- children?: React.ReactNode;- }) {- return (- <div className="h-6 text-muted-foreground text-xs leading-none">- {children}</div>- );- },- }}- // Localizer strings that remain visible in the week/day views; the- // dayjs localizer only does date math for the grid.- formats={{- timeGutterFormat: (date: Date) => formatTime(date),- selectRangeFormat: ({ start, end }: { start: Date; end: Date }) =>- formatDateTimeRange(start, end, {- preset: "time",- locale,- timeFormat,- }),- dayRangeHeaderFormat: ({ start, end }: { start: Date; end: Date }) =>- formatDateTimeRange(start, end, { preset: "monthDay", locale }),- // The toolbar shows the year separately, so leave it out here.- dayHeaderFormat: (date: Date) =>- formatDateTime(date, { preset: "weekdayMonthDay", locale }),- }}- step={15}- onSelectSlot={({ start, end, action }) => {- // on select slot- const startDate = new Date(start);- const endDate = new Date(end);-- const newEvent: DateTimeOption = {- type: "timeSlot",- start: formatDateWithoutTz(startDate),- end: formatDateWithoutTz(endDate),- };-- if (action === "select") {- const diff = dayjs(endDate).diff(startDate, "minutes");- if (diff < 60 * 24) {- onChangeDuration(diff);- }- } else {- // Fall back to an hour when the duration is 0 (all-day mode) so a- // click never creates a zero-length time slot.- newEvent.end = formatDateWithoutTz(- dayjs(startDate)- .add(duration || 60, "minutes")- .toDate(),- );- }-- const alreadyExists = options.some(- (option) =>- option.type === "timeSlot" &&- option.start === newEvent.start &&- option.end === newEvent.end,+ </div>);-- if (!alreadyExists) {- onChange([...options, newEvent]);- }}}- scrollToTime={scrollToTime}- />+ >+ <CalendarToolbar />+ <EventCalendarContent components={VIEW_COMPONENTS} />+ </EventCalendar></div>);};diff --git a/apps/web/src/lib/datetime/client.tsx b/apps/web/src/lib/datetime/client.tsxindex cae5549f0..46c68b391 100644--- a/apps/web/src/lib/datetime/client.tsx+++ b/apps/web/src/lib/datetime/client.tsx@@ -5,6 +5,7 @@ import React from "react";import type { DateTimePreset } from "@/lib/datetime/format";import {formatDateTime as baseFormatDateTime,+ formatDateTimeRange as baseFormatDateTimeRange,formatDuration as baseFormatDuration,formatRelativeTime,} from "@/lib/datetime/format";@@ -96,6 +97,19 @@ export function useDateTime() {timeZone: opts?.timeZone ?? timeZone ?? "UTC",showTimeZone: opts?.showTimeZone,}),+ formatDateTimeRange: (+ start: DateInput,+ end: DateInput,+ preset?: DateTimePreset,+ opts?: { timeZone?: string; showTimeZone?: boolean },+ ) =>+ baseFormatDateTimeRange(start, end, {+ preset,+ locale,+ timeFormat,+ timeZone: opts?.timeZone ?? timeZone ?? "UTC",+ showTimeZone: opts?.showTimeZone,+ }),toRelativeTime: (value: DateInput) => formatRelativeTime(value, locale),formatDuration: (minutes: number) => baseFormatDuration(minutes, locale),weekdays: () => getWeekdayNames(locale),diff --git a/biome-plugins/no-raw-datetime-formatting.grit b/biome-plugins/no-raw-datetime-formatting.gritindex b8f0386d3..f53b38182 100644--- a/biome-plugins/no-raw-datetime-formatting.grit+++ b/biome-plugins/no-raw-datetime-formatting.grit@@ -5,6 +5,10 @@// (which format independently of the app to act as an oracle, matching the// tests exemption in the biome.json overrides), and files still pending// migration. Shrink it as RAL-1247 proceeds.+// packages/ui is exempt entirely: lib/datetime is an apps/web app-layer+// concept, and a shared UI package cannot import it (wrong layering+// direction). Shared primitives in packages/ui format dates only via a+// caller-passed `locale` prop, which is a legitimate, narrower contract.language jsor {@@ -19,7 +23,8 @@ or {r".*/src/lib/utils/timezone-schema\.ts",r".*/src/components/time-zone-picker/timezone-utils\.ts",r".*/src/features/poll/components/manage-poll/use-csv-exporter\.ts",- r".*/tests/.*"+ r".*/tests/.*",+ r".*/packages/ui/.*"},register_diagnostic(span=$match, message="Do not format dates inline. Use the formatters in `@/lib/datetime` so locale, timezone, and hour-cycle preferences are applied consistently.")}diff --git a/biome.json b/biome.jsonindex dd767b5fc..64f4a003c 100644--- a/biome.json+++ b/biome.json@@ -75,6 +75,32 @@}}}+ },+ {+ "includes": ["**/event-calendar/**"],+ "linter": {+ "rules": {+ "style": {+ "noNonNullAssertion": "off"+ },+ "suspicious": {+ "noExplicitAny": "off",+ "noAssignInExpressions": "off",+ "noConfusingVoidType": "off",+ "useIterableCallbackReturn": "off",+ "noArrayIndexKey": "off"+ },+ "correctness": {+ "useExhaustiveDependencies": "off"+ },+ "a11y": {+ "useSemanticElements": "off",+ "useFocusableInteractive": "off",+ "useKeyWithClickEvents": "off",+ "noStaticElementInteractions": "off"+ }+ }+ }}],"formatter": {diff --git a/packages/ui/package.json b/packages/ui/package.jsonindex 6038555ca..574adde3c 100644--- a/packages/ui/package.json+++ b/packages/ui/package.json@@ -14,11 +14,13 @@"exports": {".": "./src/index.ts","./*": "./src/*.tsx",+ "./event-calendar": "./src/event-calendar/event-calendar.tsx","./hooks/*": "./src/hooks/*.ts","./style.css": "./src/style.css"},"dependencies": {"@base-ui/react": "^1.2.0",+ "@date-fns/tz": "^1.5.0","@rallly/languages": "workspace:*","@rallly/tailwind-config": "workspace:*","@react-aria/color": "^3.1.5",@@ -32,6 +34,7 @@"class-variance-authority": "^0.7.1","clsx": "^1.2.1","cmdk": "^1.1.1",+ "date-fns": "^4.4.0","input-otp": "^1.4.2","lucide-react": "^0.479.0","mdast-util-gfm-autolink-literal": "^2.0.1",@@ -39,6 +42,7 @@"next-themes": "^0.4.6","react": "19.2.6","react-aria-components": "^1.16.0",+ "react-day-picker": "^10.0.1","react-dom": "19.2.6","react-hook-form": "^7.68.0","react-markdown": "^10.1.0",@@ -50,6 +54,7 @@"devDependencies": {"@rallly/tsconfig": "workspace:*","@testing-library/react": "^16.3.0",+ "@types/node": "^24.1.0","@types/react": "19.2.13","@types/react-dom": "19.2.3","@vitejs/plugin-react": "^5.0.0",diff --git a/packages/ui/src/calendar.tsx b/packages/ui/src/calendar.tsxnew file mode 100644index 000000000..57d351764--- /dev/null+++ b/packages/ui/src/calendar.tsx@@ -0,0 +1,243 @@+"use client";++import * as React from "react";+import type { DayButton, Locale } from "react-day-picker";+import { DayPicker, getDefaultClassNames } from "react-day-picker";++import { Button } from "./button";+import { buttonVariants } from "./button-variants";+import { IconPlaceholder } from "./event-calendar/icon-placeholder";+import { cn } from "./lib/utils";++function Calendar({+ className,+ classNames,+ showOutsideDays = true,+ captionLayout = "label",+ buttonVariant = "ghost",+ locale,+ formatters,+ components,+ ...props+}: React.ComponentProps<typeof DayPicker> & {+ buttonVariant?: React.ComponentProps<typeof Button>["variant"];+}) {+ const defaultClassNames = getDefaultClassNames();++ return (+ <DayPicker+ showOutsideDays={showOutsideDays}+ className={cn(+ "group/calendar bg-background in-data-[slot=card-content]:bg-transparent in-data-[slot=popover-content]:bg-transparent p-3 [--cell-radius:var(--radius-md)] [--cell-size:--spacing(8)]",+ String.raw`rtl:**:[.rdp-button\_next>svg]:rotate-180`,+ String.raw`rtl:**:[.rdp-button\_previous>svg]:rotate-180`,+ className,+ )}+ captionLayout={captionLayout}+ locale={locale}+ formatters={{+ formatMonthDropdown: (date) =>+ date.toLocaleString(locale?.code, { month: "short" }),+ ...formatters,+ }}+ classNames={{+ root: cn("w-fit", defaultClassNames.root),+ months: cn(+ "relative flex flex-col gap-4 md:flex-row",+ defaultClassNames.months,+ ),+ month: cn("flex w-full flex-col gap-4", defaultClassNames.month),+ nav: cn(+ "absolute inset-x-0 top-0 flex w-full items-center justify-between gap-1",+ defaultClassNames.nav,+ ),+ button_previous: cn(+ buttonVariants({ variant: buttonVariant }),+ "size-(--cell-size) select-none p-0 aria-disabled:opacity-50",+ defaultClassNames.button_previous,+ ),+ button_next: cn(+ buttonVariants({ variant: buttonVariant }),+ "size-(--cell-size) select-none p-0 aria-disabled:opacity-50",+ defaultClassNames.button_next,+ ),+ month_caption: cn(+ "flex h-(--cell-size) w-full items-center justify-center px-(--cell-size)",+ defaultClassNames.month_caption,+ ),+ dropdowns: cn(+ "flex h-(--cell-size) w-full items-center justify-center gap-1.5 font-medium text-sm",+ defaultClassNames.dropdowns,+ ),+ dropdown_root: cn(+ "cn-calendar-dropdown-root relative rounded-(--cell-radius)",+ defaultClassNames.dropdown_root,+ ),+ dropdown: cn(+ "absolute inset-0 bg-popover opacity-0",+ defaultClassNames.dropdown,+ ),+ caption_label: cn(+ "select-none font-medium",+ captionLayout === "label"+ ? "cn-calendar-caption text-sm"+ : "cn-calendar-caption-label flex items-center gap-1 rounded-(--cell-radius) text-sm [&>svg]:size-3.5 [&>svg]:text-muted-foreground",+ defaultClassNames.caption_label,+ ),+ month_grid: cn("w-full border-collapse", defaultClassNames.month_grid),+ weekdays: cn("flex", defaultClassNames.weekdays),+ weekday: cn(+ "flex-1 select-none rounded-(--cell-radius) font-normal text-[0.8rem] text-muted-foreground",+ defaultClassNames.weekday,+ ),+ week: cn("mt-2 flex w-full", defaultClassNames.week),+ week_number_header: cn(+ "w-(--cell-size) select-none",+ defaultClassNames.week_number_header,+ ),+ week_number: cn(+ "select-none text-[0.8rem] text-muted-foreground",+ defaultClassNames.week_number,+ ),+ day: cn(+ "group/day relative aspect-square h-full w-full select-none rounded-(--cell-radius) p-0 text-center [&:last-child[data-selected=true]_button]:rounded-r-(--cell-radius)",+ props.showWeekNumber+ ? "[&:nth-child(2)[data-selected=true]_button]:rounded-l-(--cell-radius)"+ : "[&:first-child[data-selected=true]_button]:rounded-l-(--cell-radius)",+ defaultClassNames.day,+ ),+ range_start: cn(+ "relative isolate z-0 rounded-l-(--cell-radius) bg-muted after:absolute after:inset-y-0 after:right-0 after:w-4 after:bg-muted",+ defaultClassNames.range_start,+ ),+ range_middle: cn("rounded-none", defaultClassNames.range_middle),+ range_end: cn(+ "relative isolate z-0 rounded-r-(--cell-radius) bg-muted after:absolute after:inset-y-0 after:left-0 after:w-4 after:bg-muted",+ defaultClassNames.range_end,+ ),+ today: cn(+ "rounded-(--cell-radius) bg-muted text-foreground data-[selected=true]:rounded-none",+ defaultClassNames.today,+ ),+ outside: cn(+ "text-muted-foreground aria-selected:text-muted-foreground",+ defaultClassNames.outside,+ ),+ disabled: cn(+ "text-muted-foreground opacity-50",+ defaultClassNames.disabled,+ ),+ hidden: cn("invisible", defaultClassNames.hidden),+ ...classNames,+ }}+ components={{+ Root: ({ className, rootRef, ...props }) => {+ return (+ <div+ data-slot="calendar"+ ref={rootRef}+ className={cn(className)}+ {...props}+ />+ );+ },+ Chevron: ({ className, orientation, ...props }) => {+ if (orientation === "left") {+ return (+ <IconPlaceholder+ lucide="ChevronLeftIcon"+ tabler="IconChevronLeft"+ hugeicons="ArrowLeftIcon"+ phosphor="CaretLeftIcon"+ remixicon="RiArrowLeftSLine"+ className={cn("cn-rtl-flip size-4", className)}+ {...props}+ />+ );+ }++ if (orientation === "right") {+ return (+ <IconPlaceholder+ lucide="ChevronRightIcon"+ tabler="IconChevronRight"+ hugeicons="ArrowRightIcon"+ phosphor="CaretRightIcon"+ remixicon="RiArrowRightSLine"+ className={cn("cn-rtl-flip size-4", className)}+ {...props}+ />+ );+ }++ return (+ <IconPlaceholder+ lucide="ChevronDownIcon"+ tabler="IconChevronDown"+ hugeicons="ArrowDownIcon"+ phosphor="CaretDownIcon"+ remixicon="RiArrowDownSLine"+ className={cn("size-4", className)}+ {...props}+ />+ );+ },+ DayButton: ({ ...props }) => (+ <CalendarDayButton locale={locale} {...props} />+ ),+ WeekNumber: ({ children, ...props }) => {+ return (+ <td {...props}>+ <div className="flex size-(--cell-size) items-center justify-center text-center">+ {children}+ </div>+ </td>+ );+ },+ ...components,+ }}+ {...props}+ />+ );+}++function CalendarDayButton({+ className,+ day,+ modifiers,+ locale,+ ...props+}: React.ComponentProps<typeof DayButton> & { locale?: Partial<Locale> }) {+ const defaultClassNames = getDefaultClassNames();++ const ref = React.useRef<HTMLButtonElement>(null);+ React.useEffect(() => {+ if (modifiers.focused) ref.current?.focus();+ }, [modifiers.focused]);++ return (+ <Button+ variant="ghost"+ size="icon"+ aria-label={day.date.toDateString()}+ data-day={day.date.toLocaleDateString(locale?.code)}+ data-selected-single={+ modifiers.selected &&+ !modifiers.range_start &&+ !modifiers.range_end &&+ !modifiers.range_middle+ }+ data-range-start={modifiers.range_start}+ data-range-end={modifiers.range_end}+ data-range-middle={modifiers.range_middle}+ className={cn(+ "relative isolate z-10 flex aspect-square size-auto w-full min-w-(--cell-size) flex-col gap-1 border-0 font-normal leading-none data-[range-end=true]:rounded-(--cell-radius) data-[range-middle=true]:rounded-none data-[range-start=true]:rounded-(--cell-radius) data-[range-end=true]:rounded-r-(--cell-radius) data-[range-start=true]:rounded-l-(--cell-radius) data-[range-end=true]:bg-primary data-[range-middle=true]:bg-muted data-[range-start=true]:bg-primary data-[selected-single=true]:bg-primary data-[range-end=true]:text-primary-foreground data-[range-middle=true]:text-foreground data-[range-start=true]:text-primary-foreground data-[selected-single=true]:text-primary-foreground group-data-[focused=true]/day:relative group-data-[focused=true]/day:z-10 group-data-[focused=true]/day:border-ring group-data-[focused=true]/day:ring-[3px] group-data-[focused=true]/day:ring-ring/50 dark:hover:text-foreground [&>span]:text-xs [&>span]:opacity-70",+ defaultClassNames.day,+ className,+ )}+ {...props}+ />+ );+}++export { Calendar, CalendarDayButton };diff --git a/packages/ui/src/dropdown-menu.tsx b/packages/ui/src/dropdown-menu.tsxindex ad0638133..70fae8ae9 100644--- a/packages/ui/src/dropdown-menu.tsx+++ b/packages/ui/src/dropdown-menu.tsx@@ -81,6 +81,10 @@ function DropdownMenuItem({);}+function DropdownMenuGroup({ ...props }: MenuPrimitive.Group.Props) {+ return <MenuPrimitive.Group data-slot="dropdown-menu-group" {...props} />;+}+function DropdownMenuRadioGroup({ ...props }: MenuPrimitive.RadioGroup.Props) {return (<MenuPrimitive.RadioGroup@@ -197,6 +201,7 @@ function DropdownMenuSubContent({export {DropdownMenu,DropdownMenuContent,+ DropdownMenuGroup,DropdownMenuItem,DropdownMenuLabel,DropdownMenuRadioGroup,diff --git a/packages/ui/src/event-calendar/event-calendar-agenda-view.tsx b/packages/ui/src/event-calendar/event-calendar-agenda-view.tsxnew file mode 100644index 000000000..942135d70--- /dev/null+++ b/packages/ui/src/event-calendar/event-calendar-agenda-view.tsx@@ -0,0 +1,215 @@+// Title: Event Calendar Agenda View+// Description: Chronological agenda grouped by day - a day header row plus a clean time / dot / title table.++"use client";++import { mergeProps } from "@base-ui/react/merge-props";+import { useRender } from "@base-ui/react/use-render";+import { addDays, format } from "date-fns";+import { useMemo } from "react";+import { cn } from "../lib/utils";+import { ScrollArea } from "../scroll-area";+import {+ EventCalendarViewContext,+ useEventCalendar,+ useEventCalendarSelector,+ useEventCalendarSettings,+ useEventCalendarViewConfig,+} from "./event-calendar";+import { EventCalendarEvent } from "./event-calendar-event";+import {+ getDayKey,+ getRangeKey,+ toZoned,+ zonedStartOfDay,+} from "./event-calendar-lib";+import type {+ EventCalendarDateRange,+ EventCalendarSegment,+} from "./event-calendar-types";+import { IconPlaceholder } from "./icon-placeholder";+import { IconStack } from "./icon-stack";++// 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>+ <IconPlaceholder+ lucide="CalendarIcon"+ tabler="IconCalendarEvent"+ hugeicons="Calendar04Icon"+ phosphor="CalendarBlankIcon"+ remixicon="RiCalendarLine"+ className="size-5"+ aria-hidden="true"+ />+ </IconStack>+ <span className="text-muted-foreground text-sm">+ {settings.i18n.labels.noEvents}+ </span>+ </>+ )}+ </div>+ ) : (+ <div className="flex flex-col">+ {groups.map(({ day, bucket }) => {+ const items = [...(bucket?.allDay ?? []), ...(bucket?.timed ?? [])];+ const zoned = toZoned(day, settings.timeZone);+ return (+ <div+ key={day.getTime()}+ data-slot="event-calendar-agenda-day"+ data-today={isToday(day) || undefined}+ >+ {/* Group header: weekday (leading) + full date (trailing) */}+ <div+ data-slot="event-calendar-agenda-day-header"+ className={cn(+ "sticky top-0 z-10 flex items-baseline justify-between gap-4 border-b bg-muted/60 px-4 py-2",+ viewConfig.classNames?.agendaDayHeader,+ )}+ >+ <span+ className={cn(+ "font-semibold text-foreground",+ isToday(day) && "text-primary",+ )}+ >+ {format(zoned, "EEEE", { locale: settings.locale })}+ </span>+ <span className="font-medium text-muted-foreground tabular-nums">+ {format(zoned, "MMMM d, yyyy", { locale: settings.locale })}+ </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",+ 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+ "gap-3 rounded-none border-b px-4 py-2.5 transition-colors hover:bg-accent/40",+ viewConfig.classNames?.agendaItem,+ )}+ />+ );+}++export { EventCalendarAgendaView };+export type { EventCalendarAgendaViewProps };diff --git a/packages/ui/src/event-calendar/event-calendar-content.tsx b/packages/ui/src/event-calendar/event-calendar-content.tsxnew file mode 100644index 000000000..370742766--- /dev/null+++ b/packages/ui/src/event-calendar/event-calendar-content.tsx@@ -0,0 +1,80 @@+// Title: Event Calendar Content+// Description: Active-view switchboard rendering month, week, day, N-days, or agenda; swappable per view via the components prop.++"use client";++import { mergeProps } from "@base-ui/react/merge-props";+import { useRender } from "@base-ui/react/use-render";+import type { ComponentType, ReactNode } from "react";+import { cn } from "../lib/utils";+import {+ useEventCalendarSelector,+ useEventCalendarViewConfig,+} from "./event-calendar";+import { EventCalendarAgendaView } from "./event-calendar-agenda-view";+import { EventCalendarMonthView } from "./event-calendar-month-view";+import { EventCalendarResourceView } from "./event-calendar-resource-view";+import {+ EventCalendarDaysView,+ EventCalendarDayView,+ EventCalendarWeekView,+} from "./event-calendar-time-grid";+import type { CalendarView } from "./event-calendar-types";++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,+ };+ const ActiveView = resolved[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 };diff --git a/packages/ui/src/event-calendar/event-calendar-dnd.tsx b/packages/ui/src/event-calendar/event-calendar-dnd.tsxnew file mode 100644index 000000000..a11006ba4--- /dev/null+++ b/packages/ui/src/event-calendar/event-calendar-dnd.tsx@@ -0,0 +1,887 @@+// Title: Event Calendar Dnd+// Description: Custom pointer-event interaction engine - move, resize, and drag-create across month, week, day, and N-day views with live validation.++"use client";++import { addDays, addMinutes, differenceInCalendarDays } from "date-fns";+import { useCallback, useMemo } from "react";+import type { EventCalendarInstance } from "./event-calendar";+import { useEventCalendar, useEventCalendarViewConfig } from "./event-calendar";+import { snapMinutes, toZoned, zonedStartOfDay } from "./event-calendar-lib";+import type {+ EventCalendarProposedUpdate,+ EventCalendarSegment,+} from "./event-calendar-types";++/**+ * 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;+}++/**+ * 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";+ let activated = false;+ const onMove = (e: PointerEvent) => {+ if (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");+ instance.settings.onDragBlocked?.(segment.occurrence, { gesture, reason });+ };+ const cleanup = () => {+ window.removeEventListener("pointermove", onMove);+ window.removeEventListener("pointerup", cleanup);+ window.removeEventListener("pointercancel", 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();+ }+ };+ window.addEventListener("pointermove", onMove);+ window.addEventListener("pointerup", cleanup);+ window.addEventListener("pointercancel", cleanup);+}++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;++ let active = kind.startsWith("resize"); // resize activates immediately+ 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 isTouch = startEvent.pointerType === "touch";++ 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;++ 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;+ surface = collectSurface(origin, internals.getRootEl());+ if (kind === "move" && occurrence && surface.columns.length > 0 && !isBar) {+ const col = findColumn(surface, startX);+ if (col) {+ const startMin =+ (occurrence.start.getTime() -+ zonedStartOfDay(occurrence.start, timeZone).getTime()) /+ 60000;+ grabOffsetMin = pointerMinutes(surface, col, startY) - startMin;+ }+ }+ 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);+ const delta = differenceInCalendarDays(targetDay, originDay);+ 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);+ const durationMin = Math.round(durationMs / 60000);+ const clamped = Math.min(+ Math.max(newStartMin, col.boundsStartMin),+ col.boundsEndMin - durationMin,+ );+ const start = addMinutes(dayStart, clamped);+ 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;+ if (e.clientY < rect.top + edge) {+ delta = -step * ((rect.top + edge - e.clientY) / edge);+ } else if (e.clientY > rect.bottom - edge) {+ delta = step * ((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);+ }+ };++ const cleanup = () => {+ window.removeEventListener("pointermove", onPointerMove);+ window.removeEventListener("pointerup", onPointerUp);+ window.removeEventListener("pointercancel", onCancel);+ 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();+ }+ };++ const onPointerMove = (e: PointerEvent) => {+ 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) => {+ 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.+ void e;+ 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"),+ });+ };++ const onCancel = () => cancel();++ window.addEventListener("pointermove", onPointerMove);+ window.addEventListener("pointerup", onPointerUp);+ window.addEventListener("pointercancel", onCancel);+ window.addEventListener("keydown", onKeyDown, true);++ // 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],+ );++ 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,+ markChipPress,+ useEventCalendarGestures,+ wasRecentChipPress,+ wasRecentDrag,+};diff --git a/packages/ui/src/event-calendar/event-calendar-event.tsx b/packages/ui/src/event-calendar/event-calendar-event.tsxnew file mode 100644index 000000000..2cb540abf--- /dev/null+++ b/packages/ui/src/event-calendar/event-calendar-event.tsx@@ -0,0 +1,564 @@+// Title: Event Calendar Event+// Description: The reusable event chip/bar/block - selection, clicks, drag + resize wiring, and the consumer render slot.++"use client";++import { mergeProps } from "@base-ui/react/merge-props";+import { useRender } from "@base-ui/react/use-render";+import { addDays, format } from "date-fns";+import type { CSSProperties, ReactNode } from "react";+import { createContext, useContext, useMemo } from "react";+import { cn } from "../lib/utils";+import {+ Tooltip,+ TooltipContent,+ TooltipProvider,+ TooltipTrigger,+} from "../tooltip";+import {+ useEventCalendar,+ useEventCalendarSelector,+ useEventCalendarViewConfig,+ useEventCalendarViewContext,+} from "./event-calendar";+import {+ markChipPress,+ useEventCalendarGestures,+ wasRecentDrag,+} from "./event-calendar-dnd";+import {+ spansMultipleDays,+ toZoned,+ zonedStartOfDay,+} from "./event-calendar-lib";+import type {+ EventCalendarOccurrence,+ EventCalendarSegment,+} from "./event-calendar-types";+import { IconPlaceholder } from "./icon-placeholder";++/**+ * Effective Tailwind palette presets for event colors; every entry works on+ * light and dark surfaces through the chip's alpha background + accent border.+ */+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)" },+];++/**+ * Standardized drag-ghost surface treatment, shared verbatim by every view+ * (month, week/day/N-days, resource). One visual language for interactions:+ * - move: the event is CARRIED FREELY - a cursor-attached full clone (built+ * by the dnd engine, data-slot=event-calendar-drag-carry) travels with the+ * pointer; the in-grid ghost is only this faint dashed placeholder marking+ * the snapped drop slot. The source stays dimmed in place.+ * - resize: the event is STRETCHED - the chip itself at the proposed extent+ * with a dashed boundary instead of solid (slight indicator, no elevation).+ * - invalid: destructive tint on the placeholder / dashed clone; the engine+ * adds the not-allowed cursor, a destructive ring on the carry clone, and+ * a cursor-following validation hint.+ */+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: squeezed cascade columns+ * hard-clip titles into a mash of adjacent glyphs; a right-edge mask fade+ * reads cleaner than an ellipsis at those tiny widths. The mask applies ONLY+ * below a 10rem container width - mask-image forces text off subpixel+ * antialiasing onto a grayscale raster layer, so masking every wide chip+ * makes the whole grid read bolder/blurry and shimmer while the window+ * resizes. Wide chips keep a plain ellipsis. Consumer renderEvent content+ * can import and reuse it.+ */+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)]";++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: renders the chip exactly as-is but inert - no gestures,+ * resize handles, selection/drag state, focus, or pointer events. Used for+ * the full-fidelity ghost that tracks the proposed slot during a move.+ */+ preview?: boolean;+}++/**+ * The one interactive event element used by every view. The wrapper owns+ * positioning hooks, a11y, selection, drag/resize listeners, and data+ * attributes; content comes from children, the root renderEvent override,+ * or 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);+ 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;+ // squeezed cascade columns there fade-truncate instead of hard-clipping+ // into neighbors+ const stackedBlock =+ timedBlock &&+ (segment.endMin ?? 0) - (segment.startMin ?? 0) >=+ viewConfig.compactEventMinutes;++ const defaultContent = (+ <>+ {/* leading color dot for single-row chips (month cells, all-day bars);+ time-grid blocks read their color from the tinted surface instead -+ in the 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 just the dot-to-title gap (the chip keeps gap-1.5+ // between the title and the trailing time)+ className="-me-0.5 size-1.5 shrink-0 rounded-full bg-(--ec-event-color)"+ />+ )}+ {occurrence.isRecurring && (+ <IconPlaceholder+ lucide="RepeatIcon"+ tabler="IconRepeat"+ hugeicons="RepeatIcon"+ phosphor="RepeatIcon"+ remixicon="RiRepeatLine"+ 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; grid views show the full range */}+ {!occurrence.allDay &&+ segment.isStart &&+ (view === "month" ? (+ <span className="shrink-0 text-muted-foreground">+ {format(+ toZoned(occurrence.start, settings.timeZone),+ settings.i18n.formats.eventTime,+ { locale: settings.locale },+ )}+ </span>+ ) : (+ <span+ className={cn(+ "@[8rem]:inline hidden text-muted-foreground",+ stackedBlock ? EVENT_CALENDAR_FADE_TRUNCATE : "truncate",+ )}+ >+ {settings.i18n.functions.formatEventTime(+ toZoned(occurrence.start, settings.timeZone),+ toZoned(occurrence.end, settings.timeZone),+ occurrence.allDay,+ )}+ </span>+ ))}+ </>+ );++ // Agenda time text is per-day for multi-day events: the first day reads+ // "From 9:00 AM", middle days "All day", the last day "Until 5:00 PM".+ // Boundaries derive from the occurrence vs segment.day (never the packing+ // flags - lane merging rewrites those on shared segment objects).+ 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,+ );+ })();++ // Agenda default row: time column, color-dot badge, plain title+ const agendaDefaultContent = (+ <>+ <span className="w-40 shrink-0 truncate text-muted-foreground 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 && (+ <IconPlaceholder+ lucide="RepeatIcon"+ tabler="IconRepeat"+ hugeicons="RepeatIcon"+ phosphor="RepeatIcon"+ remixicon="RiRepeatLine"+ className="size-2.5 shrink-0 text-muted-foreground"+ aria-hidden="true"+ />+ )}+ </>+ );++ // Custom chip content is memoized so a drag - which re-renders the lane on+ // every pointer move - never re-invokes the consumer's renderEvent per frame.+ // The element stays referentially stable across those re-renders, so React+ // skips the custom subtree and it doesn't flicker; on drop only the moved+ // chip's inputs change and recompute. Deps are exactly renderProps' inputs+ // plus the render fns (all stable during an internal drag).+ 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,+ );+ // native hover tooltip text; a consumer formatter returning undefined+ // drops the title attribute entirely (e.g. when it renders its own tooltip)+ const label = settings.i18n.functions.formatEventLabel+ ? settings.i18n.functions.formatEventLabel(event.title, timeLabel)+ : `${event.title}, ${timeLabel}`;++ // Optional styled tooltip on hover / keyboard focus (viewConfig.eventTooltip,+ // default off). When on, the native title is dropped so the two never stack;+ // a preview clone never gets one. Content defaults to the label and can be+ // overridden with renderEventTooltip - a falsy result (null/undefined, or+ // the `false`/"" that `cond && <node>` yields) falls back to the label, and+ // an empty label (i18n opt-out) leaves no content so the tooltip is skipped.+ 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): a tiny bar inside each resize+ // handle signals the direction. Shown on every resizable chip - compact+ // sub-compactEventMinutes timed blocks included - because the chip+ // min-height (1.5rem) leaves room at the very top/bottom edges without+ // colliding with the vertically-centered title.+ const grip = (+ <span+ aria-hidden+ data-slot="event-calendar-resize-grip"+ className={cn(+ "rounded-full bg-foreground/40",+ 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,+ // native hover reveal for squeezed/faded chips: full title + time (dropped+ // when the styled eventTooltip is on so the two never stack)+ 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}`+ : ""+ }`,+ "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 if this press does not turn+ // into a drag (e.g. a locked chip) - see markChipPress+ 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+ // (e.g. click = open dialog only, no selected tint)+ 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 relative flex w-full min-w-0 cursor-pointer touch-none select-none items-center overflow-hidden text-start text-foreground",+ "outline-none focus-visible:ring-2 focus-visible:ring-ring/50",+ 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 px-1.5 py-1 leading-normal",+ // soft tint + hairline inset ring: color reads from the surface+ // itself (no accent border), stays legible in light and dark+ "bg-(--ec-event-color)/15 hover:bg-(--ec-event-color)/25",+ // a flat tint reads darker over a dark surface, so lift it a little+ // in dark mode to keep a lighter, softer chip tone+ "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:inset-ring-(--ec-event-color)/40 data-selected:bg-(--ec-event-color)/30",+ 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 delay={tooltipOpts?.delay ?? 600}>+ <Tooltip>+ <TooltipTrigger render={chip} />+ <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,+ EventCalendarEvent,+ useEventCalendarEventChip,+};+export type { EventCalendarChipContextValue, EventCalendarEventProps };diff --git a/packages/ui/src/event-calendar/event-calendar-i18n.tsx b/packages/ui/src/event-calendar/event-calendar-i18n.tsxnew file mode 100644index 000000000..04f20ca55--- /dev/null+++ b/packages/ui/src/event-calendar/event-calendar-i18n.tsx@@ -0,0 +1,263 @@+// Title: Event Calendar I18n+// Description: Default UI texts, date-format strings, and formatter functions for the event calendar, fully overridable per key.++import type { Locale } from "date-fns";+import { format, isSameMonth, isSameYear } from "date-fns";+import type {+ CalendarView,+ EventCalendarDateRange,+} from "./event-calendar-types";++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) => string;+ formatDayRange: (range: EventCalendarDateRange) => 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} 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+ const rangeEnd = new Date(activeRange.end.getTime() - 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) => {+ if (allDay) return cfg.labels.allDay;+ const fmt = cfg.formats.eventTime;+ // Multi-day timed events carry the date on both sides+ if (end.getTime() - start.getTime() > 24 * 60 * 60 * 1000) {+ return `${format(start, `MMM d, ${fmt}`)} - ${format(end, `MMM d, ${fmt}`)}`;+ }+ return `${format(start, fmt)} - ${format(end, fmt)}`;+ },+ formatDayRange: (range) => {+ const rangeEnd = new Date(range.end.getTime() - 1);+ return `${format(range.start, "MMM d")} - ${format(rangeEnd, "MMM d")}`;+ },+ };+}++const DEFAULT_EVENT_CALENDAR_I18N: EventCalendarI18nConfig = {+ labels: DEFAULT_LABELS,+ viewNames: DEFAULT_VIEW_NAMES,+ formats: DEFAULT_FORMATS,+ functions: makeDefaultFunctions({+ labels: DEFAULT_LABELS,+ formats: DEFAULT_FORMATS,+ }),+};++/**+ * 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?: Partial<EventCalendarI18nConfig>,+): 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 };diff --git a/packages/ui/src/event-calendar/event-calendar-lib.tsx b/packages/ui/src/event-calendar/event-calendar-lib.tsxnew file mode 100644index 000000000..33608da51--- /dev/null+++ b/packages/ui/src/event-calendar/event-calendar-lib.tsx@@ -0,0 +1,632 @@+// Title: Event Calendar Lib+// Description: Pure, React-free calendar math: view ranges, zoned day keys, multi-day segmentation, overlap packing, lane packing, and the event index.++import { TZDate } from "@date-fns/tz";+import {+ addDays,+ addMonths,+ addWeeks,+ differenceInCalendarDays,+ differenceInMinutes,+ format,+ startOfDay,+ startOfMonth,+ startOfWeek,+} from "date-fns";+import { expandRecurrence } from "./event-calendar-recurrence";+import type {+ CalendarEvent,+ CalendarView,+ EventCalendarDateRange,+ EventCalendarOccurrence,+ EventCalendarOffDaysConfig,+ EventCalendarResource,+ EventCalendarSegment,+} from "./event-calendar-types";++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 };+}++/** 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") return addMonths(zoned, direction);+ 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 compares date-only+ * in the display zone.+ */+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): boolean {+ return occurrence.allDay || spansMultipleDays(occurrence);+}++function spansMultipleDays(occ: { start: Date; end: Date }): boolean {+ // An event ending exactly at the next midnight is still single-day+ // (exclusive end), so compare against a strictly-later instant.+ return occ.end.getTime() - occ.start.getTime() > 24 * 60 * 60 * 1000;+}++/**+ * 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 = Number.NEGATIVE_INFINITY;+ for (const item of items) {+ if (item.startMin >= clusterEnd) {+ current = [];+ clusters.push(current);+ clusterEnd = Number.NEGATIVE_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 custom = opts.getOccurrences?.(event, visibleRange, { timeZone });+ if (custom) {+ custom.forEach((occ, i) => {+ 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 replaced = overrideTimes.get(event.id);+ 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);+ 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. */+function resolveOffDay(+ day: Date,+ timeZone: string,+ config: boolean | EventCalendarOffDaysConfig | undefined,+): boolean {+ if (!config) return false;+ const resolved: EventCalendarOffDaysConfig = config === true ? {} : config;+ const weekendDays = resolved.weekendDays ?? 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,+};diff --git a/packages/ui/src/event-calendar/event-calendar-month-view.tsx b/packages/ui/src/event-calendar/event-calendar-month-view.tsxnew file mode 100644index 000000000..cee163daf--- /dev/null+++ b/packages/ui/src/event-calendar/event-calendar-month-view.tsx@@ -0,0 +1,1153 @@+// Title: Event Calendar Month View+// Description: ARIA-grid month view with week rows, day cells, event chips, and overflow counts.++"use client";++import { mergeProps } from "@base-ui/react/merge-props";+import { useRender } from "@base-ui/react/use-render";+import { addDays, format, getWeek } from "date-fns";+import type { CSSProperties, Ref } from "react";+import {+ useCallback,+ useEffect,+ useLayoutEffect,+ useMemo,+ useRef,+ useState,+} from "react";+import { cn } from "../lib/utils";+import { Popover, PopoverContent, PopoverTrigger } from "../popover";+import { ScrollArea } from "../scroll-area";+import {+ EventCalendarViewContext,+ useEventCalendar,+ useEventCalendarDay,+ useEventCalendarSelector,+ useEventCalendarSettings,+ useEventCalendarViewConfig,+ useEventCalendarViewSettings,+ useEventCalendarWeek,+} from "./event-calendar";+import {+ useEventCalendarGestures,+ wasRecentChipPress,+ wasRecentDrag,+} from "./event-calendar-dnd";+import {+ EVENT_CALENDAR_GHOST,+ EventCalendarEvent,+} from "./event-calendar-event";+import {+ getDayKey,+ getRangeKey,+ resolveOffDay,+ toZoned,+ zonedStartOfDay,+} from "./event-calendar-lib";+import type {+ EventCalendarDateRange,+ EventCalendarDragState,+ EventCalendarSegment,+} from "./event-calendar-types";+import { IconPlaceholder } from "./icon-placeholder";++// 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;++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 - (Number.parseFloat(cs.paddingTop) || 0);+ const gap = Number.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(+ "truncate px-2 py-1.5 font-medium text-muted-foreground",+ 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="@max-[36rem]:inline hidden">+ {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(+ "border-e px-2 pt-1 text-muted-foreground tabular-nums",+ viewConfig.classNames?.weekNumber,+ )}+ >+ {settings.i18n.labels.week(+ getWeek(toZoned(week[0], settings.timeZone), {+ 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(+ "inset-ring-0 h-full",+ !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>;+}) {+ // biome-ignore lint/correctness/noUnusedVariables: throws outside <EventCalendar>; kept as a guard+ 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,+ );+ 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+ const isInteracting = useEventCalendarSelector<unknown, boolean>(+ (state) => state.drag !== null || state.slotDraft !== null,+ );+ 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),+ },+ );+ // 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);+ }++ // 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}+ // 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(+ "flex size-5 cursor-pointer items-center justify-center rounded-sm bg-primary text-primary-foreground opacity-0 transition-opacity focus-visible:opacity-100 group-hover/ec-cell:opacity-100",+ viewConfig.classNames?.dayAddButton,+ )}+ onClick={(e) => {+ e.stopPropagation();+ settings.onSlotClick?.(+ { date: day, allDay: true, view: "month" },+ e,+ );+ }}+ >+ <IconPlaceholder+ lucide="PlusIcon"+ tabler="IconPlus"+ hugeicons="PlusSignIcon"+ phosphor="PlusIcon"+ remixicon="RiAddLine"+ 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 font-light text-primary-foreground",+ 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+ 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(+ "relative border-b-2 border-b-primary/40 bg-primary/3",+ 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 && "bg-primary/5",+ 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 border-primary/40 border-y border-dashed",+ inDraft.isStart && "border-s",+ inDraft.isEnd && "border-e",+ viewConfig.classNames?.slotDraft,+ )}+ />+ )}+ {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);++ // 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(+ "cursor-pointer truncate rounded-sm px-1.5 text-start text-muted-foreground hover:text-foreground",+ // 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+ ? "border-(--ec-event-color)/50 bg-(--ec-event-color)/8 text-foreground"+ : "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}+ // 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} />+ )}+ </PopoverContent>+ </Popover>+ );+}++/** Built-in "+N more" popover body: day header + the day's chips. */+function EventCalendarMoreDefaultContent({+ day,+ segments,+}: {+ day: Date;+ segments: EventCalendarSegment[];+}) {+ const settings = useEventCalendarSettings();+ const viewConfig = useEventCalendarViewConfig();+ return (+ <>+ <div+ className={cn(+ "px-1 py-1 font-medium text-muted-foreground text-xs",+ 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 };diff --git a/packages/ui/src/event-calendar/event-calendar-nav.tsx b/packages/ui/src/event-calendar/event-calendar-nav.tsxnew file mode 100644index 000000000..27271825a--- /dev/null+++ b/packages/ui/src/event-calendar/event-calendar-nav.tsx@@ -0,0 +1,641 @@+// Title: Event Calendar Nav+// Description: Composable navigation - Today, prev/next, period title, view switcher dropdown, and a free toolbar slot.++"use client";++import { mergeProps } from "@base-ui/react/merge-props";+import { useRender } from "@base-ui/react/use-render";+import { addDays, format } from "date-fns";+import type { ReactNode } from "react";+import { useState } from "react";+import type { ButtonProps } from "../button";+import { Button } from "../button";+import { Calendar } from "../calendar";+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuGroup,+ DropdownMenuItem,+ DropdownMenuLabel,+ DropdownMenuTrigger,+} from "../dropdown-menu";++import { cn } from "../lib/utils";+import { Popover, PopoverContent, PopoverTrigger } from "../popover";+import {+ Tooltip,+ TooltipContent,+ TooltipProvider,+ TooltipTrigger,+} from "../tooltip";+import {+ useEventCalendarNavigation,+ useEventCalendarSettings,+ useEventCalendarView,+ useEventCalendarViewConfig,+} from "./event-calendar";+import { toZoned } from "./event-calendar-lib";+import type { CalendarView } from "./event-calendar-types";+import { IconPlaceholder } from "./icon-placeholder";++/** Configured nav button variant/size (viewConfig.navButtonVariant/Size)+ * plus the shared classNames.navButton hook, merged on every nav button. */+function useNavButtonProps(): {+ variant: NonNullable<ButtonProps["variant"]>;+ size: "sm" | "default";+ iconSize: "icon-sm" | "icon";+ className: string | undefined;+} {+ const viewConfig = useEventCalendarViewConfig();+ return {+ variant: viewConfig.navButtonVariant,+ size: viewConfig.navButtonSize,+ iconSize: viewConfig.navButtonSize === "sm" ? "icon-sm" : "icon",+ className: viewConfig.classNames?.navButton,+ };+}++/** Resolved nav tooltip policy (viewConfig.navTooltips + classNames.navTooltip). */+function useNavTooltipConfig(): {+ disabled: boolean;+ side: "top" | "bottom" | "left" | "right";+ delay: number;+ closeDelay: number;+ timeout: number;+ className: string | undefined;+} {+ const viewConfig = useEventCalendarViewConfig();+ const config =+ viewConfig.navTooltips === false ? undefined : viewConfig.navTooltips;+ return {+ disabled: viewConfig.navTooltips === false,+ // the nav sits at the top of the calendar, so tooltips open upward by+ // default (away from the grid); collision flipping still drops them below+ // when there is no room above+ side: config?.side ?? "top",+ delay: config?.delay ?? 600,+ closeDelay: config?.closeDelay ?? 0,+ timeout: config?.timeout ?? 300,+ className: viewConfig.classNames?.navTooltip,+ };+}++type NavButtonProps = Omit<useRender.ComponentProps<"button">, "children"> & {+ children?: ReactNode;+ /**+ * Tooltip policy (the part that usually goes wrong on clickable elements):+ * tooltips appear ONLY on hover or keyboard focus-visible - a pointer click+ * never re-triggers them. Buttons that open overlays (the view switcher)+ * use a hover-only tooltip that is force-closed while the overlay is up and+ * ignores focus, so nothing flashes when focus returns after selection.+ * Icon-only buttons default to their accessible label; Today defaults to+ * the actual current date (info the label doesn't carry). Pass null to+ * disable one, or any node to override; viewConfig.navTooltips=false turns+ * them all off (its object form tunes side/delay/closeDelay/timeout).+ */+ tooltip?: ReactNode | null;+};++/** Hover/focus-visible tooltip wrapper; renders the bare button when disabled+ * (per-button content=null or viewConfig.navTooltips=false). */+function NavTooltip({+ content,+ children,+}: {+ content: ReactNode | null;+ children: React.ReactElement;+}) {+ const tooltips = useNavTooltipConfig();+ if (tooltips.disabled || content === null || content === undefined)+ return children;+ return (+ <Tooltip>+ <TooltipTrigger render={children} />+ <TooltipContent side={tooltips.side} className={tooltips.className}>+ {content}+ </TooltipContent>+ </Tooltip>+ );+}++function EventCalendarNavToday({+ className,+ render,+ children,+ tooltip,+ ...props+}: NavButtonProps) {+ const { today, isToday } = useEventCalendarNavigation();+ const settings = useEventCalendarSettings();+ const nav = useNavButtonProps();+ // display-zone "today", like every other today derivation in the calendar+ // (a system-zone new Date() can name a different day than Today opens)+ const defaultTooltip = format(+ toZoned(new Date(), settings.timeZone),+ settings.i18n.formats.dayTitle,+ { locale: settings.locale },+ );+ return (+ <NavTooltip content={tooltip === undefined ? defaultTooltip : tooltip}>+ <Button+ variant={nav.variant}+ size={nav.size}+ data-slot="event-calendar-nav-today"+ data-active={isToday || undefined}+ className={cn(nav.className, className)}+ onClick={today}+ render={render}+ {...props}+ >+ {children ?? settings.i18n.labels.today}+ </Button>+ </NavTooltip>+ );+}++function EventCalendarNavPrev({+ className,+ render,+ children,+ tooltip,+ ...props+}: NavButtonProps) {+ const { prev } = useEventCalendarNavigation();+ const settings = useEventCalendarSettings();+ const nav = useNavButtonProps();+ return (+ <NavTooltip+ content={tooltip === undefined ? settings.i18n.labels.previous : tooltip}+ >+ <Button+ variant={nav.variant}+ size={nav.iconSize}+ data-slot="event-calendar-nav-prev"+ aria-label={settings.i18n.labels.previous}+ className={cn(nav.className, className)}+ onClick={prev}+ render={render}+ {...props}+ >+ {children ?? (+ <IconPlaceholder+ lucide="ChevronLeftIcon"+ tabler="IconChevronLeft"+ hugeicons="ArrowLeft01Icon"+ phosphor="CaretLeftIcon"+ remixicon="RiArrowLeftSLine"+ className="size-4"+ aria-hidden="true"+ />+ )}+ </Button>+ </NavTooltip>+ );+}++function EventCalendarNavNext({+ className,+ render,+ children,+ tooltip,+ ...props+}: NavButtonProps) {+ const { next } = useEventCalendarNavigation();+ const settings = useEventCalendarSettings();+ const nav = useNavButtonProps();+ return (+ <NavTooltip+ content={tooltip === undefined ? settings.i18n.labels.next : tooltip}+ >+ <Button+ variant={nav.variant}+ size={nav.iconSize}+ data-slot="event-calendar-nav-next"+ aria-label={settings.i18n.labels.next}+ className={cn(nav.className, className)}+ onClick={next}+ render={render}+ {...props}+ >+ {children ?? (+ <IconPlaceholder+ lucide="ChevronRightIcon"+ tabler="IconChevronRight"+ hugeicons="ArrowRight01Icon"+ phosphor="CaretRightIcon"+ remixicon="RiArrowRightSLine"+ className="size-4"+ aria-hidden="true"+ />+ )}+ </Button>+ </NavTooltip>+ );+}++interface EventCalendarTitleProps extends useRender.ComponentProps<"div"> {+ format?: (ctx: { title: string }) => ReactNode;+}++function EventCalendarTitle({+ className,+ render,+ format: formatTitle,+ ...props+}: EventCalendarTitleProps) {+ const { title } = useEventCalendarNavigation();+ const viewConfig = useEventCalendarViewConfig();+ const defaultProps = {+ "data-slot": "event-calendar-title",+ "aria-live": "polite" as const,+ className: cn(+ "min-w-0 truncate font-semibold text-sm",+ viewConfig.classNames?.title,+ className,+ ),+ children: formatTitle?.({ title }) ?? title,+ };+ return useRender({+ defaultTagName: "div",+ render,+ props: mergeProps<"div">(defaultProps, props),+ });+}++interface EventCalendarViewSwitcherProps+ extends Omit<useRender.ComponentProps<"button">, "children"> {+ children?: ReactNode;+ /** Hover/focus-visible hint; defaults to the "Select view" label. Pass+ * null to disable (overlay-opener policy). */+ tooltip?: ReactNode | null;+}++function EventCalendarViewSwitcher({+ className,+ render,+ children,+ tooltip,+ ...props+}: EventCalendarViewSwitcherProps) {+ const { view, dayCount, availableViews, setView } = useEventCalendarView();+ const settings = useEventCalendarSettings();+ const viewConfig = useEventCalendarViewConfig();+ const nav = useNavButtonProps();+ const tooltips = useNavTooltipConfig();+ const labels = settings.i18n.labels;+ // Controlled open: selecting a view swaps the whole content subtree in the+ // same click, so closing must not depend on the menu's internal handler.+ const [open, setOpen] = useState(false);+ // Hover-only tooltip: when the menu closes, Base UI focuses the trigger+ // again and a focus-opened tooltip would flash - ignore focus opens.+ const [tipOpen, setTipOpen] = useState(false);++ const selectView = (v: CalendarView, opts?: { dayCount?: number }) => {+ setOpen(false);+ setView(v, opts);+ };++ const viewLabel = (v: CalendarView) =>+ v === "days"+ ? settings.i18n.viewNames.days(dayCount)+ : settings.i18n.viewNames[v];++ return (+ <DropdownMenu+ open={open}+ onOpenChange={(next: boolean) => {+ setOpen(next);+ if (next) setTipOpen(false);+ }}+ >+ {/* Tooltip on an overlay-opener: hover-only (focus opens ignored) and+ force-closed while the menu is up, so it never lingers or flashes+ when focus returns on close. Inherits the nav TooltipProvider's+ delay/closeDelay/timeout. */}+ <Tooltip+ open={tipOpen && !open}+ onOpenChange={(next: boolean, details: { reason?: string }) => {+ // opens are hover-only; the trigger-focus open that follows a+ // menu close is ignored, closes always land+ if (next && details?.reason !== "trigger-hover") return;+ setTipOpen(next);+ }}+ >+ <DropdownMenuTrigger+ render={+ <TooltipTrigger+ render={+ <Button+ variant={nav.variant}+ size={nav.size}+ data-slot="event-calendar-view-switcher"+ aria-label={labels.selectView}+ className={cn("gap-1", nav.className, className)}+ />+ }+ />+ }+ {...props}+ >+ {children ?? (+ <>+ {viewLabel(view)}+ <IconPlaceholder+ lucide="ChevronDownIcon"+ tabler="IconChevronDown"+ hugeicons="ArrowDown01Icon"+ phosphor="CaretDownIcon"+ remixicon="RiArrowDownSLine"+ className="size-4 opacity-60"+ aria-hidden="true"+ />+ </>+ )}+ </DropdownMenuTrigger>+ {tipOpen && !open && tooltip !== null && !tooltips.disabled && (+ <TooltipContent side={tooltips.side} className={tooltips.className}>+ {tooltip ?? labels.selectView}+ </TooltipContent>+ )}+ </Tooltip>+ <DropdownMenuContent+ align="start"+ className={cn("min-w-44", viewConfig.classNames?.viewSwitcherContent)}+ >+ {/* Base UI contract: GroupLabel must live inside Menu.Group */}+ <DropdownMenuGroup>+ <DropdownMenuLabel+ className={cn(+ "font-normal text-muted-foreground",+ viewConfig.classNames?.viewSwitcherLabel,+ )}+ >+ {settings.i18n.labels.selectView}+ </DropdownMenuLabel>+ {availableViews.map((v) =>+ v === "days" ? (+ viewConfig.dayCountPresets.map((count) => (+ <DropdownMenuItem+ key={`days-${count}`}+ data-active={+ (view === "days" && dayCount === count) || undefined+ }+ onClick={() => selectView("days", { dayCount: count })}+ >+ {settings.i18n.viewNames.days(count)}+ {/* hint derived from the preset itself, not i18n's default */}+ {viewConfig.enableShortcuts && (+ <EventCalendarViewShortcut>+ {count}+ </EventCalendarViewShortcut>+ )}+ </DropdownMenuItem>+ ))+ ) : (+ <DropdownMenuItem+ key={v}+ data-active={view === v || undefined}+ onClick={() => selectView(v)}+ >+ {viewLabel(v)}+ {viewConfig.enableShortcuts && (+ <EventCalendarViewShortcut>+ {labels.viewShortcuts[v]}+ </EventCalendarViewShortcut>+ )}+ </DropdownMenuItem>+ ),+ )}+ </DropdownMenuGroup>+ </DropdownMenuContent>+ </DropdownMenu>+ );+}++/** Outline key badge; theme-token only, so it adapts to every style. */+function EventCalendarViewShortcut({ children }: { children: ReactNode }) {+ const viewConfig = useEventCalendarViewConfig();+ return (+ <kbd+ data-slot="event-calendar-view-shortcut"+ className={cn(+ "ms-auto inline-flex size-5 shrink-0 items-center justify-center rounded-sm border font-sans text-muted-foreground text-xs",+ viewConfig.classNames?.viewShortcut,+ )}+ >+ {children}+ </kbd>+ );+}++interface EventCalendarDatePickerProps+ extends Omit<useRender.ComponentProps<"button">, "children"> {+ children?: ReactNode;+ /** "auto" (default) resolves per view: range for week/N-days/agenda. */+ mode?: "auto" | "single" | "range";+ /** Hover/focus-visible hint; defaults to null - no tooltip, because the+ * button opens an overlay (see the NavButtonProps tooltip policy). */+ tooltip?: ReactNode | null;+}++/** Views whose period reads better as a highlighted range. */+const RANGE_VIEWS: CalendarView[] = ["week", "days", "agenda"];++/**+ * Optional go-to-date picker (shadcn Calendar in a popover), view-aware:+ * week/N-days/agenda highlight the whole active range (any click re-anchors+ * the period), other views select a single date. Not part of the default+ * nav - compose it yourself (or any external picker driving+ * useEventCalendarNavigation().goTo). No tooltip by default: it opens an+ * overlay (see the NavButtonProps tooltip policy); pass `tooltip` to opt in.+ */+function EventCalendarDatePicker({+ className,+ render,+ children,+ tooltip = null,+ mode,+ ...props+}: EventCalendarDatePickerProps) {+ const { date, goTo, activeRange } = useEventCalendarNavigation();+ const { view } = useEventCalendarView();+ const settings = useEventCalendarSettings();+ const viewConfig = useEventCalendarViewConfig();+ const nav = useNavButtonProps();+ const [open, setOpen] = useState(false);+ const zoned = toZoned(date, settings.timeZone);++ const configured = mode ?? "auto";+ const resolved =+ configured === "auto"+ ? RANGE_VIEWS.includes(view)+ ? "range"+ : "single"+ : configured;++ const pick = (next: Date | undefined) => {+ if (!next) return;+ goTo(next);+ setOpen(false);+ };++ return (+ <Popover open={open} onOpenChange={setOpen}>+ <NavTooltip content={tooltip}>+ <PopoverTrigger+ render={+ <Button+ variant={nav.variant}+ size={nav.iconSize}+ data-slot="event-calendar-date-picker"+ data-mode={resolved}+ aria-label={settings.i18n.labels.goToDate}+ className={cn(nav.className, className)}+ render={render}+ />+ }+ {...props}+ >+ {children ?? (+ <IconPlaceholder+ lucide="CalendarIcon"+ tabler="IconCalendarEvent"+ hugeicons="Calendar04Icon"+ phosphor="CalendarBlankIcon"+ remixicon="RiCalendarLine"+ className="size-4"+ aria-hidden="true"+ />+ )}+ </PopoverTrigger>+ </NavTooltip>+ <PopoverContent+ align="start"+ className={cn("w-auto p-0!", viewConfig.classNames?.datePickerContent)}+ >+ {resolved === "range" ? (+ <Calendar+ mode="range"+ selected={{+ from: toZoned(activeRange.start, settings.timeZone),+ to: toZoned(addDays(activeRange.end, -1), settings.timeZone),+ }}+ defaultMonth={zoned}+ onDayClick={pick}+ locale={settings.locale}+ weekStartsOn={settings.weekStartsOn}+ />+ ) : (+ <Calendar+ mode="single"+ selected={zoned}+ defaultMonth={zoned}+ onSelect={pick}+ locale={settings.locale}+ weekStartsOn={settings.weekStartsOn}+ />+ )}+ </PopoverContent>+ </Popover>+ );+}++type EventCalendarToolbarProps = useRender.ComponentProps<"div">;++/** Free slot for consumer toolbar buttons; pure layout shell. */+function EventCalendarToolbar({+ className,+ render,+ ...props+}: EventCalendarToolbarProps) {+ const viewConfig = useEventCalendarViewConfig();+ const defaultProps = {+ "data-slot": "event-calendar-toolbar",+ className: cn(+ "flex items-center gap-2",+ viewConfig.classNames?.toolbar,+ className,+ ),+ children: props.children,+ };+ return useRender({+ defaultTagName: "div",+ render,+ props: mergeProps<"div">(defaultProps, props),+ });+}++interface EventCalendarNavProps extends useRender.ComponentProps<"div"> {+ /**+ * Render the view switcher in the composed layout. Turn off when the+ * calendar ships with a fixed view (e.g. a month-only embed) and users+ * should not be able to change it.+ * @default true+ */+ showViewSwitcher?: boolean;+}++/**+ * Default composed nav: Today, prev/next, title, spacer, view switcher.+ * Pass children to use it as a pure layout shell instead.+ */+function EventCalendarNav({+ className,+ render,+ children,+ showViewSwitcher = true,+ ...props+}: EventCalendarNavProps) {+ const viewConfig = useEventCalendarViewConfig();+ const tooltips = useNavTooltipConfig();+ const defaultProps = {+ "data-slot": "event-calendar-nav",+ className: cn(+ "flex min-w-0 flex-wrap items-center gap-1 px-2 py-2",+ viewConfig.stickyNav && "sticky top-0 z-30 bg-background",+ viewConfig.classNames?.nav,+ className,+ ),+ children: children ?? (+ // Shared provider: first tooltip waits, moving between buttons is instant+ <TooltipProvider+ delay={tooltips.delay}+ closeDelay={tooltips.closeDelay}+ timeout={tooltips.timeout}+ >+ <EventCalendarNavToday />+ {showViewSwitcher && <EventCalendarViewSwitcher />}+ <div className="flex items-center">+ <EventCalendarNavPrev />+ <EventCalendarNavNext />+ </div>+ {/* ms-3 sets the title apart from the tight control cluster so the+ period reads as its own group, not another button */}+ <EventCalendarTitle className="ms-3" />+ <div className="grow" />+ </TooltipProvider>+ ),+ };+ return useRender({+ defaultTagName: "div",+ render,+ props: mergeProps<"div">(defaultProps, props),+ });+}++export {+ EventCalendarDatePicker,+ EventCalendarNav,+ EventCalendarNavNext,+ EventCalendarNavPrev,+ EventCalendarNavToday,+ EventCalendarTitle,+ EventCalendarToolbar,+ EventCalendarViewSwitcher,+};+export type {+ EventCalendarNavProps,+ EventCalendarTitleProps,+ EventCalendarToolbarProps,+ EventCalendarViewSwitcherProps,+};diff --git a/packages/ui/src/event-calendar/event-calendar-recurrence.tsx b/packages/ui/src/event-calendar/event-calendar-recurrence.tsxnew file mode 100644index 000000000..5c346e7ee--- /dev/null+++ b/packages/ui/src/event-calendar/event-calendar-recurrence.tsx@@ -0,0 +1,490 @@+// Title: Event Calendar Recurrence+// Description: RFC 5545 subset recurrence expansion for the event calendar - structured rules or raw RRULE strings, with a hard occurrence cap.++import { TZDate } from "@date-fns/tz";+import { addDays, addMonths, addWeeks, addYears } from "date-fns";+import type {+ CalendarEvent,+ EventCalendarDateRange,+ EventCalendarOccurrence,+ EventCalendarRecurrenceRule,+ EventCalendarWeekday,+} from "./event-calendar-types";++/** 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, Number.parseInt(value, 10) || 1);+ break;+ case "COUNT":+ rule.count = Math.max(1, Number.parseInt(value, 10) || 1);+ break;+ case "UNTIL":+ rule.until = parseRRuleDate(value, timeZone);+ break;+ case "BYDAY":+ rule.byWeekday = value.split(",").map((token) => {+ const match = /^(-?\d+)?(SU|MO|TU|WE|TH|FR|SA)$/.exec(token.trim());+ if (!match) throw new EventCalendarRecurrenceError(`BYDAY=${token}`);+ const day = match[2] as EventCalendarWeekday;+ return match[1]+ ? { day, ordinal: Number.parseInt(match[1], 10) }+ : day;+ });+ break;+ case "BYMONTHDAY":+ rule.byMonthDay = value.split(",").map((v) => Number.parseInt(v, 10));+ break;+ case "BYMONTH":+ rule.byMonth = value.split(",").map((v) => Number.parseInt(v, 10));+ break;+ case "WKST": {+ if (!WEEKDAYS.includes(value as EventCalendarWeekday)) {+ throw new EventCalendarRecurrenceError(`WKST=${value}`);+ }+ rule.weekStart = value as EventCalendarWeekday;+ 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)+ const match = /^(\d{4})(\d{2})(\d{2})(?:T(\d{2})(\d{2})(\d{2})(Z)?)?$/.exec(+ value,+ );+ 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+ * wall-time duration is preserved across DST transitions.+ *+ * 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) {+ if (event.start < range.end && event.end > 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);+ // 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;++ const monthlyByDay =+ rule.freq === "monthly" && rule.byWeekday?.length ? rule.byWeekday : null;++ // 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));++ const daysInMonth = (year: number, month: number) =>+ new Date(year, month + 1, 0).getDate();++ /** 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 candidatesFor = (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[] = [];+ for (let d = 0; d < 7; d++) {+ if (!weeklyDays.includes(d)) continue;+ const candidate = addDays(base, d - base.getDay());+ // 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());+ };++ /** 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) - 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 (weeklyDays) {+ // week 0 only counts selected weekdays at/after DTSTART's weekday+ const firstWeek = weeklyDays.filter(+ (d) => d >= zonedStart.getDay(),+ ).length;+ index = firstWeek + (startPeriod - 1) * weeklyDays.length;+ } else if (hasMonthDayParts) {+ // per-period counts vary (skipped days, 4-vs-5 weekday months) - sum them+ for (let period = 0; period < startPeriod; period++) {+ index += candidatesFor(period).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 = new Date(start.getTime() + durationMs);+ 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 = new Date(start.getTime() + durationMs);+ 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,+ });+ }+ occurrences.sort((a, b) => a.start.getTime() - b.start.getTime());+ }++ return occurrences;+}++export {+ EventCalendarRecurrenceError,+ expandRecurrence,+ formatRRuleString,+ MAX_OCCURRENCES,+ parseRRuleString,+};diff --git a/packages/ui/src/event-calendar/event-calendar-resource-view.tsx b/packages/ui/src/event-calendar/event-calendar-resource-view.tsxnew file mode 100644index 000000000..018f33251--- /dev/null+++ b/packages/ui/src/event-calendar/event-calendar-resource-view.tsx@@ -0,0 +1,763 @@+// Title: Event Calendar Resource View+// Description: Resource-columns day grid for booking scenarios - one time axis, one column per resource, full drag, resize, and drag-create.++"use client";++import { mergeProps } from "@base-ui/react/merge-props";+import { useRender } from "@base-ui/react/use-render";+import { addDays, addMinutes } from "date-fns";+import type { CSSProperties } from "react";+import { useEffect, useMemo, useRef } from "react";+import { cn } from "../lib/utils";+import { ScrollArea } from "../scroll-area";+import {+ EventCalendarViewContext,+ useEventCalendar,+ useEventCalendarDay,+ useEventCalendarSelector,+ useEventCalendarSettings,+ useEventCalendarViewConfig,+ useEventCalendarViewSettings,+} from "./event-calendar";+import {+ useEventCalendarGestures,+ wasRecentChipPress,+ wasRecentDrag,+} from "./event-calendar-dnd";+import {+ EVENT_CALENDAR_GHOST,+ EventCalendarEvent,+} from "./event-calendar-event";+import {+ flattenResources,+ getDayKey,+ getDayTotalMinutes,+ packTimedSegments,+ resolveOffDay,+ snapMinutes,+ toZoned,+ zonedStartOfDay,+} from "./event-calendar-lib";+import {+ EventCalendarNowIndicator,+ EventCalendarTimeGutter,+ minuteBlockStyle,+} from "./event-calendar-time-grid";+import type {+ EventCalendarResource,+ EventCalendarSegment,+} from "./event-calendar-types";++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 &&+ "sticky top-(--ec-sticky-offset,0px) z-20 bg-background",+ 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)+ "w-(--ec-gutter-width,4.5rem) shrink-0 border-e ps-2 pe-2.5 pt-1.5 text-muted-foreground",+ 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,+ );+ 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("bg-primary/10", 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,+ );+ 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.+ const packed = useMemo(() => {+ const mine = segments.timed+ .filter((segment) => segment.occurrence.event.resourceId === resource.id)+ .map((segment) => ({ ...segment }) as EventCalendarSegment);+ packTimedSegments(mine);+ return mine;+ }, [segments.timed, resource.id]);++ 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()),+ },+ );++ 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.+ const colPct = 100 / columnCount;+ 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: `${column * colPct}%`,+ width: `${span * colPct}%`,+ "--ec-z": zIndex,+ } as CSSProperties+ }+ >+ <EventCalendarEvent+ segment={segment}+ className={cn(+ columnCount > 1 && "ring-1 ring-background",+ // 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(+ "pointer-events-none absolute inset-x-0.5 z-40 rounded-sm border border-primary/40 border-dashed bg-primary/5",+ viewConfig.classNames?.slotDraft,+ )}+ style={minuteBlockStyle(+ draftWindow[0],+ draftWindow[1],+ boundsStartMin,+ )}+ />+ )}+ </div>+ );+}++export { EventCalendarResourceView };+export type { EventCalendarResourceViewProps };diff --git a/packages/ui/src/event-calendar/event-calendar-time-grid.tsx b/packages/ui/src/event-calendar/event-calendar-time-grid.tsxnew file mode 100644index 000000000..22ead6d29--- /dev/null+++ b/packages/ui/src/event-calendar/event-calendar-time-grid.tsx@@ -0,0 +1,1232 @@+// Title: Event Calendar Time Grid+// Description: Shared week/day/N-days engine - hour gutter, minute-positioned events, all-day row, drag ghosts, now indicator, and configurable scrolling.++"use client";++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 type { CSSProperties, ReactNode } from "react";+import { useEffect, useMemo, useRef, useState } from "react";+import { cn } from "../lib/utils";+import { ScrollArea } from "../scroll-area";+import {+ EventCalendarViewContext,+ useEventCalendar,+ useEventCalendarDay,+ useEventCalendarSelector,+ useEventCalendarSettings,+ useEventCalendarViewConfig,+ useEventCalendarViewContext,+ useEventCalendarViewSettings,+} from "./event-calendar";+import {+ useEventCalendarGestures,+ wasRecentChipPress,+ wasRecentDrag,+} from "./event-calendar-dnd";+import {+ EVENT_CALENDAR_GHOST,+ EventCalendarEvent,+} from "./event-calendar-event";+import {+ getDayKey,+ getDayTotalMinutes,+ getRangeKey,+ resolveOffDay,+ snapMinutes,+ toZoned,+ zonedStartOfDay,+} from "./event-calendar-lib";+import type {+ CalendarView,+ EventCalendarDateRange,+ EventCalendarDragState,+ EventCalendarSegment,+} from "./event-calendar-types";++/** 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;+ return result.filter(+ (day) => ![0, 6].includes(toZoned(day, settings.timeZone).getDay()),+ );+ }, [visibleRange, settings.timeZone, 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 &&+ "sticky top-(--ec-sticky-offset,0px) z-20 bg-background",+ 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+ "w-(--ec-gutter-width,4.5rem) shrink-0 border-e ps-2 pe-2.5 pt-1.5 text-muted-foreground",+ 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 overscroll-none"+ >+ {track}+ </div>+ ) : (+ <ScrollArea className="h-full [&_[data-slot=scroll-area-viewport]]:overscroll-none">+ {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(+ "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(+ "inset-ring-0 h-full",+ !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,+ );+ 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),+ },+ );++ 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("bg-primary/10", 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);+ }+ }}+ />+ );+}++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(+ "absolute end-2.5 -top-2 text-muted-foreground",+ viewConfig.classNames?.timeGutterLabel,+ )}+ >+ {label}+ </span>+ )}+ </div>+ );+ })}+ </div>+ );+}++/** 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,+ );+ 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]),+ },+ );++ 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>+ )}+ {segments.timed.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.+ const colPct = 100 / columnCount;+ 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: `${column * colPct}%`,+ width: `${span * colPct}%`,+ "--ec-z": zIndex,+ } as CSSProperties+ }+ >+ <EventCalendarEvent+ segment={segment}+ className={cn(+ columnCount > 1 && "ring-1 ring-background",+ // 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(+ "pointer-events-none absolute inset-x-0.5 z-40 rounded-sm border border-primary/40 border-dashed bg-primary/5",+ viewConfig.classNames?.slotDraft,+ )}+ style={minuteBlockStyle(+ draftWindow[0],+ draftWindow[1],+ boundsStartMin,+ )}+ />+ )}+ </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="absolute start-(--ec-gutter-width,4.5rem) end-0 h-px bg-destructive/40" />+ {/* 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="absolute inset-x-0 top-0 h-px bg-destructive" />+ {/* 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="absolute -start-1 top-0 size-1.5 -translate-y-1/2 rounded-full bg-destructive" />+ </div>+ </div>+ );+}++interface TimeGridViewProps extends 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 {+ EventCalendarDayView,+ EventCalendarDaysView,+ EventCalendarNowIndicator,+ EventCalendarTimeGrid,+ EventCalendarTimeGutter,+ EventCalendarWeekView,+ minuteBlockStyle,+ useNow,+};+export type { EventCalendarTimeGridProps };diff --git a/packages/ui/src/event-calendar/event-calendar-types.tsx b/packages/ui/src/event-calendar/event-calendar-types.tsxnew file mode 100644index 000000000..a40191fb5--- /dev/null+++ b/packages/ui/src/event-calendar/event-calendar-types.tsx@@ -0,0 +1,276 @@+// Title: Event Calendar Types+// Description: Public TypeScript contract for the headless event calendar: events, occurrences, segments, state, and callbacks.++type EventCalendarEventId = string;++type CalendarView = "month" | "week" | "day" | "days" | "agenda" | "resource";++/**+ * A bookable resource (room, person, equipment). Nesting via children renders+ * with children; the resource day view shows leaves as booking columns.+ */+interface EventCalendarResource {+ id: string;+ title: string;+ /** Token or css color used for subtle row/column accents. */+ color?: string;+ children?: EventCalendarResource[];+}++interface EventCalendarDateRange {+ /** Inclusive instant. */+ start: Date;+ /** Exclusive instant. */+ 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;+ /** Plain instant; consumers parse ISO strings themselves. */+ start: Date;+ /** Exclusive; must be >= start. */+ end: Date;+ 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 override; default comes from interactions.drag. */+ draggable?: boolean;+ /** Per-event override; default comes from interactions.resize. */+ resizable?: boolean;+ /** Packing prominence; feeds getEventPriority ordering. */+ priority?: number;+ /** Explicit stacking override; wins over the computed z. */+ zIndex?: number;+ /** Bookable resource this event belongs to (resource view). */+ resourceId?: string;+ /** Consumer payload, fully generic. */+ 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 day this segment belongs to. */+ day: Date;+ isStart: boolean;+ isEnd: boolean;+ continuesBefore: boolean;+ continuesAfter: boolean;+ /** Timed only: minutes from the zoned day start. */+ startMin?: number;+ endMin?: number;+ /** Month / all-day lane index. */+ lane?: number;+ /** Time-grid overlap packing. */+ column?: number;+ columnCount?: number;+ columnSpan?: number;+ /** Week-row granularity (month bars / all-day lanes). */+ rowIndex?: number;+ colStart?: number;+ colSpan?: number;+}++interface EventCalendarSelection {+ eventKeys: string[];+ /** Committed slot selection; see EventCalendarSlotDraft for the in-gesture value. */+ 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;+ /**+ * True when the proposal was resolved on the day-granular surface (month+ * cells / the all-day lane) rather than minute columns - the all-day lane+ * ghost keys on this, covering timed MULTI-DAY bars whose proposals stay+ * timed (proposedAllDay alone misses them).+ */+ proposedDayGranular: boolean;+ /** Target resource when dragging across resource columns/rows. */+ proposedResourceId?: string;+ /** Last canDropEvent verdict; drives data-drop-invalid styling. */+ valid: boolean;+}++/**+ * The in-progress drag-create rectangle ONLY, cleared on commit or cancel.+ * The committed slot selection lives in EventCalendarSelection.slot.+ */+interface EventCalendarSlotDraft {+ start: Date;+ end: Date;+ allDay: boolean;+ view: CalendarView;+ /** Present when the slot was selected inside a resource column/row. */+ resourceId?: string;+}++/**+ * User-adjustable display toggles (the "View settings" submenu). Every field+ * is optional; undefined defers to the matching root view-config prop.+ */+interface EventCalendarViewSettings {+ /** Show Saturday/Sunday columns in month, week, and N-day grids. */+ weekends?: boolean;+ /** Week-number gutter in the month view. */+ weekNumbers?: boolean;+ nowIndicator?: boolean;+ /** Off-day (non-working) background marking. */+ offDays?: boolean;+}++interface EventCalendarState<TData = unknown> {+ view: CalendarView;+ /** Anchor date. */+ date: Date;+ /** For the "days" view. */+ 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;+ /** Proposed resource when the gesture crossed resource columns/rows. */+ 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;+ /** Present when the click happened inside a resource column/row. */+ resourceId?: string;+}++/**+ * Off-day marking (non-working days). `true` uses the defaults: weekends+ * with a muted background. Custom weekday sets, explicit dates, a predicate,+ * and a custom class are all supported; marked cells carry `data-off` for+ * CSS-selector customization.+ */+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;+}++/**+ * External-data contract. v1 ships the type plus docs recipes (Google+ * events.list / MS Graph calendarView map to CalendarEvent in ~15 lines);+ * OAuth, tokens, and sync loops are application backend territory.+ */+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,+};diff --git a/packages/ui/src/event-calendar/event-calendar.tsx b/packages/ui/src/event-calendar/event-calendar.tsxnew file mode 100644index 000000000..85c5a217a--- /dev/null+++ b/packages/ui/src/event-calendar/event-calendar.tsx@@ -0,0 +1,1744 @@+// Title: Event Calendar+// Description: Headless-first event calendar with month, week, day, N-day and agenda views, external CRUD contract, and a subscribable store.++"use client";++import { mergeProps } from "@base-ui/react/merge-props";+import { useRender } from "@base-ui/react/use-render";+import type { Locale } from "date-fns";+import { addDays } from "date-fns";+import type { ComponentType, ReactNode, RefObject } from "react";+import {+ createContext,+ useCallback,+ useContext,+ useEffect,+ useLayoutEffect,+ useRef,+ useState,+ useSyncExternalStore,+} from "react";+import type { ButtonProps } from "../button";+import { cn } from "../lib/utils";+import type { EventCalendarI18nConfig } from "./event-calendar-i18n";+import { mergeEventCalendarI18n } from "./event-calendar-i18n";+import type {+ EventCalendarDayBucket,+ EventCalendarIndex,+ WeekStartsOn,+} from "./event-calendar-lib";+import {+ buildEventIndex,+ defaultEventOrder,+ eventsOverlap,+ getDayKey,+ getRangeKey,+ getViewDateRange,+ stepDate,+ toZoned,+ zonedStartOfDay,+} from "./event-calendar-lib";+import type {+ CalendarEvent,+ CalendarView,+ EventCalendarDateRange,+ EventCalendarDragState,+ EventCalendarEventId,+ EventCalendarInteractions,+ EventCalendarOccurrence,+ EventCalendarOffDaysConfig,+ EventCalendarProposedUpdate,+ EventCalendarRangeInfo,+ EventCalendarResource,+ EventCalendarSegment,+ EventCalendarSelection,+ EventCalendarSlotDraft,+ EventCalendarSlotInfo,+ EventCalendarState,+ EventCalendarUpdateResult,+ EventCalendarViewSettings,+} from "./event-calendar-types";++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 };++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?: Partial<EventCalendarI18nConfig>;+ /** 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;+ return {+ ...rest,+ timeZone:+ options.timeZone ?? Intl.DateTimeFormat().resolvedOptions().timeZone,+ locale: options.locale,+ weekStartsOn: 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 ?? [],+ getEventPriority:+ options.getEventPriority ?? ((event) => event.priority ?? 0),+ eventOrder: options.eventOrder ?? defaultEventOrder,+ getOccurrences: options.getOccurrences,+ weekendDays: options.weekendDays ?? [0, 6],+ 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;+ index: EventCalendarIndex<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();+ };++ // 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;+ 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+ ) {+ 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,+ 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;+ }+ 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),+ );+ }+ return buildEventIndex(state.events, range, {+ timeZone: settings.timeZone,+ weekStartsOn: settings.weekStartsOn,+ eventOrder: settings.eventOrder,+ getOccurrences: settings.getOccurrences,+ }).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",+ ] 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,+ };+}++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);+ 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),+ },+ );+ 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;+ agendaDayHeader?: string;+ agendaDay?: 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: NonNullable<ButtonProps["variant"]>;+ /** 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 { EventCalendarContent } from "./event-calendar-content";+export {+ EventCalendarDayView,+ EventCalendarWeekView,+} from "./event-calendar-time-grid";+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 {+ CalendarEvent,+ CalendarView,+ EventCalendarOccurrence,+ EventCalendarProposedUpdate,+ EventCalendarSlotDraft,+ EventCalendarSlotInfo,+ EventCalendarUpdateResult,+} from "./event-calendar-types";+export type {+ EventCalendarActivationConfig,+ EventCalendarApi,+ EventCalendarCallbacks,+ EventCalendarClassNames,+ EventCalendarInstance,+ EventCalendarInternals,+ EventCalendarProps,+ EventCalendarRenderEventProps,+ EventCalendarSettings,+ EventCalendarViewConfig,+ UseEventCalendarStateOptions,+};diff --git a/packages/ui/src/event-calendar/icon-placeholder.tsx b/packages/ui/src/event-calendar/icon-placeholder.tsxnew file mode 100644index 000000000..6ab551eab--- /dev/null+++ b/packages/ui/src/event-calendar/icon-placeholder.tsx@@ -0,0 +1,43 @@+import type { LucideIcon } from "lucide-react";+import {+ CalendarIcon,+ ChevronDownIcon,+ ChevronLeftIcon,+ ChevronRightIcon,+ PlusIcon,+ RepeatIcon,+} from "lucide-react";+import type * as React from "react";++const ICONS: Record<string, LucideIcon> = {+ CalendarIcon,+ ChevronDownIcon,+ ChevronLeftIcon,+ ChevronRightIcon,+ PlusIcon,+ RepeatIcon,+};++/**+ * Lucide-only replacement for ReUI's multi-library IconPlaceholder. Renders the+ * lucide icon named by `lucide`; the other library props are accepted and+ * ignored so vendored call sites compile unchanged.+ */+export function IconPlaceholder({+ lucide,+ tabler: _tabler,+ hugeicons: _hugeicons,+ phosphor: _phosphor,+ remixicon: _remixicon,+ ...props+}: {+ lucide: string;+ tabler?: string;+ hugeicons?: string;+ phosphor?: string;+ remixicon?: string;+} & React.ComponentProps<LucideIcon>) {+ const Icon = ICONS[lucide];+ if (!Icon) return null;+ return <Icon {...props} />;+}diff --git a/packages/ui/src/event-calendar/icon-stack.tsx b/packages/ui/src/event-calendar/icon-stack.tsxnew file mode 100644index 000000000..7ce9c1d21--- /dev/null+++ b/packages/ui/src/event-calendar/icon-stack.tsx@@ -0,0 +1,90 @@+import type * as React from "react";++import { cn } from "../lib/utils";++type IconStackProps = React.ComponentProps<"div">;++function IconStack({ className, children, style, ...props }: IconStackProps) {+ return (+ <div+ data-slot="icon-stack"+ className={cn(+ "relative h-20 w-18 text-foreground **:data-[slot=icon-stack-layer]:fill-background",+ className,+ )}+ style={+ {+ "--icon-stack-content-x": "71%",+ "--icon-stack-content-y": "58%",+ ...style,+ } as React.CSSProperties+ }+ {...props}+ >+ <svg+ aria-hidden="true"+ viewBox="0 0 72 81"+ fill="none"+ className="h-full w-full overflow-visible"+ >+ <ellipse+ cx="36"+ cy="76"+ rx="30"+ ry="7"+ fill="currentColor"+ fillOpacity="0.055"+ className="blur-[4px]"+ />+ <IconStackLayer opacity="0.4" />+ <IconStackLayer opacity="0.6" x={13.65} y={6.04} />+ <IconStackLayer opacity="0.8" x={27.32} y={12.08} active />+ </svg>+ {children ? (+ <div+ data-slot="icon-stack-content"+ className="pointer-events-none absolute top-[var(--icon-stack-content-y)] left-[var(--icon-stack-content-x)] flex -translate-x-1/2 -translate-y-1/2 -skew-y-26 scale-x-90 items-center justify-center text-muted-foreground"+ >+ {children}+ </div>+ ) : null}+ </div>+ );+}++function IconStackLayer({+ active = false,+ opacity,+ x = 0,+ y = 0,+}: {+ active?: boolean;+ opacity: string;+ x?: number;+ y?: number;+}) {+ return (+ <g opacity={opacity} transform={`translate(${x} ${y})`}>+ <path+ data-slot="icon-stack-layer"+ d="M42.2538 2.046C41.4408 1.6325 40.3965 1.6677 39.2612 2.2424L7.9616 18.1934C5.3895 19.5039 3.301 23.1064 3.301 26.2322V64.3226C3.301 66.0677 3.9458 67.2943 4.962 67.8199L1.8363 66.229C0.8201 65.7104 0.1753 64.4771 0.1753 62.732V24.6412C0.1753 21.5085 2.2638 17.913 4.8359 16.6024L36.1355 0.6515C37.2778 0.0698 38.322 0.0416 39.128 0.4551L42.2538 2.046Z"+ stroke="currentColor"+ strokeOpacity={active ? "0.3" : "0.2"}+ strokeWidth="0.5"+ strokeLinecap="round"+ strokeLinejoin="round"+ />+ <path+ data-slot="icon-stack-layer"+ d="M42.2545 2.0456C43.2707 2.5643 43.9155 3.7979 43.9155 5.543V43.6337C43.9155 46.7665 41.827 50.3616 39.2549 51.6722L7.9554 67.6235C6.813 68.2052 5.7687 68.2331 4.9628 67.8196C3.9465 67.301 3.3018 66.0673 3.3018 64.3222V26.2318C3.3018 23.0991 5.3903 19.5036 7.9624 18.193L39.2619 2.2421C40.4043 1.6604 41.4486 1.6321 42.2545 2.0456Z"+ stroke="currentColor"+ strokeOpacity={active ? "0.3" : "0.2"}+ strokeWidth="0.5"+ strokeLinecap="round"+ strokeLinejoin="round"+ />+ </g>+ );+}++export { IconStack, type IconStackProps };diff --git a/packages/ui/src/scroll-area.tsx b/packages/ui/src/scroll-area.tsxnew file mode 100644index 000000000..e4272c00b--- /dev/null+++ b/packages/ui/src/scroll-area.tsx@@ -0,0 +1,54 @@+"use client";++import { ScrollArea as ScrollAreaPrimitive } from "@base-ui/react/scroll-area";++import { cn } from "./lib/utils";++function ScrollArea({+ className,+ children,+ ...props+}: ScrollAreaPrimitive.Root.Props) {+ return (+ <ScrollAreaPrimitive.Root+ data-slot="scroll-area"+ className={cn("relative", className)}+ {...props}+ >+ <ScrollAreaPrimitive.Viewport+ data-slot="scroll-area-viewport"+ className="size-full rounded-[inherit] outline-none transition-[color,box-shadow] focus-visible:outline-1 focus-visible:ring-[3px] focus-visible:ring-ring/50"+ >+ {children}+ </ScrollAreaPrimitive.Viewport>+ <ScrollBar />+ <ScrollAreaPrimitive.Corner />+ </ScrollAreaPrimitive.Root>+ );+}++function ScrollBar({+ className,+ orientation = "vertical",+ ...props+}: ScrollAreaPrimitive.Scrollbar.Props) {+ return (+ <ScrollAreaPrimitive.Scrollbar+ data-slot="scroll-area-scrollbar"+ data-orientation={orientation}+ orientation={orientation}+ className={cn(+ "flex touch-none select-none p-px transition-colors data-horizontal:h-2.5 data-vertical:h-full data-vertical:w-2.5 data-horizontal:flex-col data-horizontal:border-t data-horizontal:border-t-transparent data-vertical:border-l data-vertical:border-l-transparent",+ className,+ )}+ {...props}+ >+ <ScrollAreaPrimitive.Thumb+ data-slot="scroll-area-thumb"+ className="relative flex-1 rounded-full bg-border"+ />+ </ScrollAreaPrimitive.Scrollbar>+ );+}++export { ScrollArea, ScrollBar };diff --git a/packages/ui/tsconfig.json b/packages/ui/tsconfig.jsonindex 42e5369c0..0183a9447 100644--- a/packages/ui/tsconfig.json+++ b/packages/ui/tsconfig.json@@ -1,5 +1,8 @@{"extends": "@rallly/tsconfig/next.json",+ "compilerOptions": {+ "types": ["node"]+ },"include": ["**/*.ts", "**/*.tsx"],"exclude": ["node_modules"]}diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex b4c267c7a..d6c3b149a 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -94,7 +94,7 @@ importers:version: 8.1.0([email protected])'@vercel/analytics':specifier: ^1.5.0- version: 1.6.1([email protected](@opentelemetry/[email protected])(@playwright/[email protected])([email protected]([email protected]))([email protected]))([email protected])+ version: 1.6.1([email protected](@babel/[email protected])(@opentelemetry/[email protected])(@playwright/[email protected])([email protected]([email protected]))([email protected]))([email protected])dayjs:specifier: ^1.11.13version: 1.11.19@@ -133,7 +133,7 @@ importers:version: 6.0.0(@types/[email protected])([email protected])next-seo:specifier: ^6.1.0- version: 6.8.0([email protected](@opentelemetry/[email protected])(@playwright/[email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected])+ version: 6.8.0([email protected](@babel/[email protected])(@opentelemetry/[email protected])(@playwright/[email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected])pg:specifier: ^8.17.1version: 8.18.0@@ -396,9 +396,6 @@ importers:react:specifier: 19.2.6version: 19.2.6- react-big-calendar:- specifier: ^1.8.1react-dom:specifier: 19.2.6version: 19.2.6([email protected])@@ -478,9 +475,6 @@ importers:'@types/react':specifier: 19.2.13version: 19.2.13- '@types/react-big-calendar':- specifier: ^1.8.8- version: 1.16.3'@types/react-dom':specifier: 19.2.3version: 19.2.3(@types/[email protected])@@ -764,6 +758,9 @@ importers:'@base-ui/react':specifier: ^1.2.0+ '@date-fns/tz':+ specifier: ^1.5.0+ version: 1.5.0'@rallly/languages':specifier: workspace:*version: link:../languages@@ -803,6 +800,9 @@ importers:cmdk:specifier: ^1.1.1version: 1.1.1(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])+ date-fns:+ specifier: ^4.4.0+ version: 4.4.0input-otp:specifier: ^1.4.2@@ -824,6 +824,9 @@ importers:react-aria-components:specifier: ^1.16.0+ react-day-picker:+ specifier: ^10.0.1+ version: 10.0.1(@types/[email protected])([email protected])react-dom:specifier: 19.2.6version: 19.2.6([email protected])@@ -852,6 +855,9 @@ importers:'@testing-library/react':specifier: ^16.3.0version: 16.3.2(@testing-library/[email protected])(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])+ '@types/node':+ specifier: ^24.1.0+ version: 24.10.11'@types/react':specifier: 19.2.13version: 19.2.13@@ -1915,6 +1921,9 @@ packages:resolution: {integrity: sha512-Vd/9EVDiu6PPJt9yAh6roZP6El1xHrdvIVGjyBsHR0RYwNHgL7FJPyIIW4fANJNG6FtyZfvlRPpFI4ZM/lubvw==}engines: {node: '>=18'}+ '@date-fns/[email protected]':+ resolution: {integrity: sha512-lwYN/vDPeNRULcepoE/LO2Pgx+7/RV+S9ARfbc9lr2DtGkOD7pAiruHvbR1RX3Qyf6ja47EWJDMsNK5vK08DJg==}+'@discoveryjs/[email protected]':resolution: {integrity: sha512-dBVuXR082gk3jsFp7Rd/JI4kytwGHecnCoTtXFb7DB6CNHp4rg5k1bhg0nWdLGLnOV71lmDzGQaLMy8iPLY0pw==}engines: {node: '>=10.0.0'}@@ -3433,9 +3442,6 @@ packages:'@polka/[email protected]':resolution: {integrity: sha512-wwQAWhWSuHaag8c4q/KN/vCoeOJYshAIvMQwD4GpSb3OiZklFfvAgmj0VCBBImRpuF/aFgIRzllXlVX93Jevww==}- '@popperjs/[email protected]':- resolution: {integrity: sha512-P1st0aksCrn9sGZhp8GMYwBnQsbvAWsZAX44oXNNvLHGqAOcoVxmjZiohstwQ7SqKnbR47akdNi+uleWD8+g6A==}-'@posthog/[email protected]':resolution: {integrity: sha512-jXuMtZCwA7AMpYlo1wjm6GlC58YBlz/ZxpDIsF9hroUfqYoPPDmQbsQb4iiZAS43+o/kwloxdKJIlE0IiwQ5HQ==}@@ -4556,11 +4562,6 @@ packages:peerDependencies:react: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1- '@restart/[email protected]':- resolution: {integrity: sha512-f7aCv7c+nU/3mF7NWLtVVr0Ra80RqsO89hO72r+Y/nvQr5+q0UFGkocElTH6MJApvReVh6JHUFYn2cw1WdHF3w==}- peerDependencies:- react: '>=16.8.0'-'@rolldown/[email protected]':resolution: {integrity: sha512-izyXV/v+cHiRfozX62W9htOAvwMo4/bXKDrQ+vom1L1qRuexPock/7VZDAhnpHCLNejd3NJ6hiab+tO0D44Rgw==}@@ -5878,9 +5879,6 @@ packages:'@types/[email protected]':resolution: {integrity: sha512-mFNylyeyqN93lfe/9CSxOGREz8cpzAhH+E93xJ4xWQf62V8sQ/24reV2nyzUWM6H6Xji+GGHpkbLe7pVoUEskg==}- '@types/[email protected]':- resolution: {integrity: sha512-p9eZ2X9B80iKiTW4ukVj8B4K6q9/+xFtQ5MGYA5HWToY9nL4EkhV9+6ftT2VHpVMEZb5Tv00Iel516bVdO+yRw==}-'@types/[email protected]':resolution: {integrity: sha512-vIChWdVG3LG1SMxEvI/AK+FWJthlrqlTu7fbrlywTkkaONwk/UAGaULXRlf8vkzFBLVm0zkMdCquhL5aOjhXPQ==}@@ -5986,18 +5984,12 @@ packages:'@types/[email protected]':resolution: {integrity: sha512-AUZTa7hQ2KY5L7AmtSiqxlhWxb4ina0yd8hNbl4TWuqnv/pFP0nDMb3YrfSBf4hJVGLh2YEIBfKaBW/9UEl6IQ==}- '@types/[email protected]':- resolution: {integrity: sha512-F6bEyamV9jKGAFBEmlQnesRPGOQqS2+Uwi0Em15xenOxHaf2hv6L8YCVn3rPdPJOiJfPiCnLIRyvwVaqMY3MIw==}-'@types/[email protected]':resolution: {integrity: sha512-eOunJqu0K1923aExK6y8p6fsihYEn/BYuQ4g0CxAAgFc4b/ZLN4CrsRZ55srTdqoiLzU2B2evC+apEIxprEzkQ==}'@types/[email protected]':resolution: {integrity: sha512-hKormJbkJqzQGhziax5PItDUTMAM9uE2XXQmM37dyd4hVM+5aVl7oVxMVUiVQn2oCQFN/LKCZdvSM0pFRqbSmQ==}- '@types/[email protected]':- resolution: {integrity: sha512-CR+5BKMhlr/wPgsp+sXOeNKNkoU1h/+6H1XoWuL7xnurvzGRQv/EnM8jPS9yxxBvXI8pjQBaJcI7RTSGiewG/Q==}-'@types/[email protected]':resolution: {integrity: sha512-jp2L/eY6fn+KgVVQAOqYItbF0VY/YApe5Mz2F0aykSO8gx31bYCZyvSeYxCHKvzHG5eZjc+zyaS5BrBWya2+kQ==}peerDependencies:@@ -6036,9 +6028,6 @@ packages:'@types/[email protected]':resolution: {integrity: sha512-zFDAD+tlpf2r4asuHEj0XH6pY6i0g5NeAHPn+15wk3BV6JA69eERFXC1gyGThDkVa1zCyKr5jox1+2LbV/AMLg==}- '@types/[email protected]':- resolution: {integrity: sha512-D1XC7WK8K+zZEveUPY+cf4+kgauk8N4eHr/XIHXGlGYkHLud6hK9lYfZk1ry1TNh798cZUCgb6MqGEG8DkJt6Q==}-'@types/[email protected]':resolution: {integrity: sha512-oJoftv0LSuaDZE3Le4DbKX+KS9G36NzOeSap90UIK0yMA/NhKJhqlSGtNDORNRaIbQfzjXDrQa0ytJ6mNRGz/Q==}@@ -7071,8 +7060,8 @@ packages:resolution: {integrity: sha512-BS8PfmtDGnrgYdOonGZQdLZslWIeCGFP9tpan0hi1Co2Zr2NKADsvGYA8XxuG/4UWgJ6Cjtv+YJnB6MM69QGlQ==}engines: {node: '>= 0.4'}- resolution: {integrity: sha512-QWxYLR5P/6GStZcdem+V1xoto6DMadYWpMXU82ES3/RfR3Wdwr3D0+be7mgOJ+Ov0G9D5Dmb9T17sNLQYj9XOg==}+ resolution: {integrity: sha512-+1UMbeh68lH1SegH83CGWwpb6OHHbpSgr3+s5Eww5M4CAgswBpoWS0AjTOfEJ33HiYKz1hdj/KTFprzXHmq/6w==}resolution: {integrity: sha512-2P0p0pFGzHS5EMnhdxQi7aJN+iMheud0UhG4dlE1DLAlvL8JHjJJTX/CSm4JXwV0Ka5nGk3zC5mcb5bUQUxxMA==}@@ -7237,9 +7226,6 @@ packages:resolution: {integrity: sha512-7ZgogeTnjuHbo+ct10G9Ffp0mif17idi0IyWNVA/wcwcm7NPOD/WEHVP3n7n3MhXqxoIYm8d6MuZohYWIZ4T3w==}- resolution: {integrity: sha512-nRCa7CK3VTrM2NmGkIy4cbK7IZlgBE/PYMn55rrXefr5xXDP0LdtfPnblFDoVdcAfslJ7or6iqAUnx0CCGIWQA==}-resolution: {integrity: sha512-wIkAryiqt/nV5EQKqQpo3SToSOV9J0DnbJqwK7Wv/Trc92zIAYZ4FlMu+JPFW1DfGFt81ZTCGgDEabffXeLyJg==}@@ -7841,9 +7827,6 @@ packages:resolution: {integrity: sha512-Wjlyrolmm8uDpm/ogGyXZXb1Z+Ca2B8NbJwqBVg0axK9GbBeoS7yGV6vjXnYdGm6X53iehEuxxbyiKp8QmN4Vw==}engines: {node: 18 || 20 || >=22}- resolution: {integrity: sha512-5e01v8eLGfuQSOvx2MsDMOWS0GFtCx1wPzQSmcHw4hkxFzrQDBO3Xwg/m8Hr/7qXMrHeOIE29qWVzyv06u1TZA==}-resolution: {integrity: sha512-WOBp/EEGUiIsJSp7wcv/y6MO+lV9UoncWqxuFfm8eBwzWNgyfBd6Gz+IeKQ9jCmyhoH99g15M3T+QaVHFjizVA==}engines: {node: '>=4'}@@ -8219,9 +8202,6 @@ packages:resolution: {integrity: sha512-m3Ofv/X/tV8Y3tHXLohcuVuhWKo7BBq62cqY15etqmLxg2DZ34AGGgQDeR+SCta2+zICb1NX83af0GJmbQ1++g==}- resolution: {integrity: sha512-phJfQVBuaJM5raOpJjSfkiD6BpbCE4Ns//LaXl6wGYtUBY83nWS6Rf9tXm2e8VaK60JEjYldbPif/A2B1C2gNA==}-resolution: {integrity: sha512-XXADHxXmvT9+CRxhXg56LJovE+bmWnEWB78LB83VZTprKTmaC5QfruXocxzTZ2Kl0DNwKuBdlIhjL8LeY8Sf8Q==}engines: {node: '>= 12'}@@ -8704,9 +8684,6 @@ packages:resolution: {integrity: sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw==}engines: {node: '>=10'}- resolution: {integrity: sha512-kVI48u3PZr38HdYz98UmfPnXl2DXrpdctLrFLCd3kOx1xUkOmpFPx7gCWWM5MPkL/fD8zb+Ph0QzjGFs4+hHWg==}-resolution: {integrity: sha512-FT1yDzDYEoYWhnSGnpE/4Kj1fLZkDFyqRb7fNt6FdYOSxlUWAtp42Eh6Wb0rGIv/m9Bgo7x4GhQbm5Ys4SG5ow==}@@ -8733,10 +8710,6 @@ packages:resolution: {integrity: sha512-9Ri+o0JYgehTaVBBDoMqIl8GXtbWg711O3srftcHhZ0dqnETqLaoIK0x17fUw9rFSlK/0NlsKe0Ahhyl5pXE2g==}- resolution: {integrity: sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==}- hasBin: true-resolution: {integrity: sha512-7fm3l3NAF9WfN6W3JOmf5drwpVqX78JtoGJ3A6W0a6ZnldM41w2fV5D490psKFTpMds8TJse/eHLFFsNHHjHgg==}@@ -8767,10 +8740,6 @@ packages:peerDependencies:react: ^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0- resolution: {integrity: sha512-vtEhXh/gNjI9Yg1u4jX/0YVPMvxzHuGgCm6tC5kZyb08yjGWGnqAjGJvcXbqQR2P3MyMEFnRbpcdFS6PBcLqew==}- engines: {node: '>=12'}-resolution: {integrity: sha512-h5bgJWpxJNswbU7qCrV0tIKQCaS3blPDrqKWx+QxzuzL1zGUzij9XCWLrSLsJPu5t+eWA/ycetzYAO5IOMcWAQ==}hasBin: true@@ -8882,9 +8851,6 @@ packages:resolution: {integrity: sha512-dq+qelQ9akHpcOl/gUVRTxVIOkAJ1wR3QAvb4RsVjS8oVoFjDGTc679wJYmUmknUF5HwMLOgb5O+a3KxfWapPQ==}engines: {node: '>= 0.6'}- resolution: {integrity: sha512-rkpe71W0N0c0Xz6QD0eJETuWAJGnJ9afsl1srmwPrI+yBCkge5EycXXbYRyvL29zZVUWQCY7InPRCv3GDXuZNw==}-resolution: {integrity: sha512-cCi6g3/Zr1iqQi6ySbseM1Xvooa98N0w31jzUYrXPX2xqObmFGHJ0tQ5u74H3mVh7wLouTseZyYIq39g8cNp1w==}@@ -9113,12 +9079,6 @@ packages:resolution: {integrity: sha512-EGWKgxALGMgzvxYF1UyGTy0HXX/2vHLkw6+NvDKW2jypWbHpjQuj4UMcqQWXHERJhVGKikolT06G3bcKe4fi7w==}- resolution: {integrity: sha512-f22b8LV1gbTO2ms2j2z13MuPogNoh5UzxL3nzNAYKGraILnbGc9NEE6dyiiiLv46DGRb8A4kg8UKWLjPthxBHw==}-- resolution: {integrity: sha512-uEmtNhbDOrWPFS+hdjFCBfy9f2YoyzRpwcl+DqpC6taX21FzsTLQVbMV/W7PzNSX6x/bhC1zA3c2UQ5NzH6how==}-resolution: {integrity: sha512-XRPebVypsl0UM+7v0Hr8o9UAj0S2djsQWRdHBd5iVouVpMrQqAI0C/rDAT3QaYnXnHuC5hMcwDHCboNeyYjPoQ==}@@ -9770,9 +9730,6 @@ packages:resolution: {integrity: sha512-NxNv/kLguCA7p3jE8oL2aEBsrJWgAakBpgmgK6lpPWV+WuOmY6r2/zbAVnP+T8bQlA0nzHXSJSJW0Hq7ylaD2Q==}engines: {node: '>= 6'}- resolution: {integrity: sha512-oj87CgZICdulUohogVAR7AjlC0327U4el4L6eAvOqCeudMDVU0NThNaV+b9Df4dXgSP1gXMTnPdhfe/2qDH5cg==}-resolution: {integrity: sha512-TjNPblN4BwAWMXU8s9AEz4JmQxnD1NNL7bNOY/AKUzyamc379FWASUhc/K1pL2noVb+XmZKLL68cjzLsiOAMaA==}@@ -9920,11 +9877,15 @@ packages:react: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1react-dom: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1- resolution: {integrity: sha512-FrvbDx2LF6JAWFD96LU1jjloppC5OgIvMYUYIPzAw5Aq+ArYFPxAjLqXc4DyxfsQDN0TJTMuS/BIbcSB7Pg0YA==}+ resolution: {integrity: sha512-eNh6BlwcYInWaJtRv18mXQ06Ys/H6rdTZAnTaSdOYJuTpwP1JMCHNd1FDRadA+gbeinq+psdULN5Xnowy9mV8w==}+ engines: {node: '>=18'}peerDependencies:- react: ^16.14.0 || ^17 || ^18 || ^19- react-dom: ^16.14.0 || ^17 || ^18 || ^19+ '@types/react': '>=16.8.0'+ react: '>=16.8.0'+ peerDependenciesMeta:+ '@types/react':+ optional: trueresolution: {integrity: sha512-0prMI+hvBbPjsWnxDLxlCGyM8PN6UuWjEUCYmZhO67xIV9Xasa/r/vDnq+Xyq4Lo27g8QSbO5YzARu0D1Sps3g==}@@ -9972,27 +9933,15 @@ packages:peerDependencies:react: '>=16.13.1'- resolution: {integrity: sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==}-resolution: {integrity: sha512-w2GsyukL62IJnlaff/nRegPQR94C/XXamvMWmSHRJ4y7Ts/4ocGRmTHvOs8PSE6pB3dWOrD/nueuU5sduBsQ4w==}- resolution: {integrity: sha512-fBASbA6LnOU9dOU2eW7aQ8xmYBSXUIWr+UmF9b1efZBazGNO+rcXT/icdKnYm2pTwcRylVUYwW7H1PHfLekVzA==}-resolution: {integrity: sha512-qKxVopLT/TyA6BX3Ue5NwabOsAzm0Q7kAPwq6L+wWDwisYs7R8vZ0nRXqq6rkueboxpkjvLGU9fWifiX/ZZFxQ==}peerDependencies:'@types/react': '>=18'react: '>=18'- resolution: {integrity: sha512-GLLSOLWr21CqtJn8geSwQfoJufdt3mfdsnIiQswouuQ2MMPns+ihZklxvsTDKD3cR2tF8ELbi5xUsvqVhR6WvA==}- peerDependencies:- react: '>=16.3.0'- react-dom: '>=16.3.0'-resolution: {integrity: sha512-2NPMOzgTlG0ZWdIf3qG+dcbLSoAc/uLfOwckc3ofy5sSK0pLJqnQLpUFxvGcN2rlXSjnVtGeeFLNimCQEj5gOQ==}engines: {node: '>=0.10.0'}@@ -11013,11 +10962,6 @@ packages:resolution: {integrity: sha512-mlExGW4w71ebDJviH16lQLtZS32VKqsSfk80GCfUlwT/4/hNRFsoscrF/c++9xinkMzECL1uL9DDwXqFWkruPg==}- resolution: {integrity: sha512-svtcfoTADIB0nT9nltgjujTi7BzVmwjZClOmskKu/E8FW9BXzg9os8OLr4f8Dlnk0rYWJIWr4wv9eKUXiQvQwQ==}- peerDependencies:- react: '>=15.0.0'-resolution: {integrity: sha512-Ql87qFHB3s/De2ClA9e0gsnS6zXG27SkTiSJwjCc9MebbfapQfuPzumMIUMi38ezPZVNFcHI9sUIepeQfw8J8Q==}@@ -11284,9 +11228,6 @@ packages:resolution: {integrity: sha512-o8qghlI8NZHU1lLPrpi2+Uq7abh4GGPpYANlalzWxyWteJOCsr/P+oPBA49TOLu5FTZO4d3F9MnWJfiMo4BkmA==}engines: {node: '>=18'}- resolution: {integrity: sha512-rpJyN222KWIvHJ/F53XSZv0Zl/accqHR8et1kpaMTD/fLCRxtV8iX8czMzY7sVZupTI3zcUTg8eycS2kNF9l6w==}-resolution: {integrity: sha512-Zn5uXdcFNIA1+1Ei5McRd+iRzfhENPCe7LeABkJtNulSxjma+l7ltNx55BWZkRlwRnpOgHqxnjyaDgJnNXnqzg==}engines: {node: '>=10.13.0'}@@ -13136,6 +13077,8 @@ snapshots:'@csstools/[email protected]': {}+ '@date-fns/[email protected]': {}+'@discoveryjs/[email protected]': {}'@electric-sql/[email protected](@electric-sql/[email protected])':@@ -14764,8 +14707,6 @@ snapshots:'@polka/[email protected]': {}- '@popperjs/[email protected]': {}-'@posthog/[email protected]':dependencies:'@posthog/types': 1.393.0@@ -16320,11 +16261,6 @@ snapshots:'@react-types/shared': 3.33.1([email protected])react: 19.2.6- '@restart/[email protected]([email protected])':- dependencies:- dequal: 2.0.3- react: 19.2.6-'@rolldown/[email protected]': {}'@rollup/[email protected]([email protected])':@@ -17808,8 +17744,6 @@ snapshots:dependencies:'@types/node': 24.10.11- '@types/[email protected]': {}-'@types/[email protected]':dependencies:'@types/ms': 2.1.0@@ -17935,18 +17869,10 @@ snapshots:'@types/[email protected]': {}- '@types/[email protected]': {}-'@types/[email protected]': {}'@types/[email protected]': {}- '@types/[email protected]':- dependencies:- '@types/date-arithmetic': 4.1.4- '@types/prop-types': 15.7.15- '@types/react': 19.2.13-'@types/[email protected](@types/[email protected])':dependencies:'@types/react': 19.2.13@@ -17987,8 +17913,6 @@ snapshots:'@types/[email protected]': {}- '@types/[email protected]': {}-'@types/[email protected]':dependencies:'@types/node': 24.10.11@@ -18033,7 +17957,7 @@ snapshots:dependencies:uncrypto: 0.1.3- '@vercel/[email protected]([email protected](@opentelemetry/[email protected])(@playwright/[email protected])([email protected]([email protected]))([email protected]))([email protected])':+ '@vercel/[email protected]([email protected](@babel/[email protected])(@opentelemetry/[email protected])(@playwright/[email protected])([email protected]([email protected]))([email protected]))([email protected])':optionalDependencies:next: 16.2.6(@babel/[email protected])(@opentelemetry/[email protected])(@playwright/[email protected])([email protected]([email protected]))([email protected])react: 19.2.6@@ -19009,7 +18933,7 @@ snapshots:es-errors: 1.3.0is-data-view: 1.0.2- [email protected]: {}+ [email protected]: {}@@ -19135,11 +19059,6 @@ snapshots:- dependencies:- '@babel/runtime': 7.28.6- csstype: 3.2.3-dependencies:domelementtype: 2.3.0@@ -19937,8 +19856,6 @@ snapshots:minipass: 7.1.3path-scurry: 2.0.2- [email protected]: {}-@@ -20556,10 +20473,6 @@ snapshots:'@formatjs/icu-messageformat-parser': 2.11.4tslib: 2.8.1- dependencies:- loose-envify: 1.4.0-@@ -20991,8 +20904,6 @@ snapshots:dependencies:p-locate: 5.0.0- [email protected]: {}-@@ -21018,10 +20929,6 @@ snapshots:- dependencies:- js-tokens: 4.0.0-dependencies:tslib: 2.8.1@@ -21044,8 +20951,6 @@ snapshots:dependencies:react: 19.2.6- [email protected]: {}-@@ -21296,8 +21201,6 @@ snapshots:- [email protected]: {}-@@ -21691,12 +21594,6 @@ snapshots:- dependencies:- moment: 2.30.1-- [email protected]: {}-dependencies:motion-utils: 12.29.2@@ -21810,7 +21707,7 @@ snapshots:react: 19.2.6react-dom: 19.2.6([email protected])- [email protected]([email protected](@opentelemetry/[email protected])(@playwright/[email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected]):+ [email protected]([email protected](@babel/[email protected])(@opentelemetry/[email protected])(@playwright/[email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected]):dependencies:next: 16.2.6(@babel/[email protected])(@opentelemetry/[email protected])(@playwright/[email protected])([email protected]([email protected]))([email protected])react: 19.2.6@@ -22349,12 +22246,6 @@ snapshots:kleur: 3.0.3sisteransi: 1.0.5- dependencies:- loose-envify: 1.4.0- object-assign: 4.1.1- react-is: 16.13.1-dependencies:graceful-fs: 4.2.11@@ -22636,26 +22527,13 @@ snapshots:react: 19.2.6react-dom: 19.2.6([email protected])dependencies:- '@babel/runtime': 7.28.6- clsx: 1.2.1- date-arithmetic: 4.1.0- dayjs: 1.11.19- dom-helpers: 5.2.1- globalize: 0.1.1- invariant: 2.2.4- lodash: 4.17.23- lodash-es: 4.17.23- luxon: 3.7.2- memoize-one: 6.0.0- moment: 2.30.1- moment-timezone: 0.5.48- prop-types: 15.8.1+ '@date-fns/tz': 1.5.0+ date-fns: 4.4.0react: 19.2.6- react-dom: 19.2.6([email protected])- uncontrollable: 7.2.1([email protected])+ optionalDependencies:+ '@types/react': 19.2.13dependencies:@@ -22717,12 +22595,8 @@ snapshots:dependencies:react: 19.2.6- [email protected]: {}-- [email protected]: {}-dependencies:'@types/hast': 3.0.4@@ -22741,19 +22615,6 @@ snapshots:transitivePeerDependencies:- supports-color- dependencies:- '@babel/runtime': 7.28.6- '@popperjs/core': 2.11.8- '@restart/hooks': 0.4.16([email protected])- '@types/warning': 3.0.3- dom-helpers: 5.2.1- prop-types: 15.8.1- react: 19.2.6- react-dom: 19.2.6([email protected])- uncontrollable: 7.2.1([email protected])- warning: 4.0.3-dependencies:react: 19.2.3@@ -24091,14 +23952,6 @@ snapshots:buffer: 5.7.1through: 2.3.8- dependencies:- '@babel/runtime': 7.28.6- '@types/react': 19.2.13- invariant: 2.2.4- react: 19.2.6- react-lifecycles-compat: 3.0.4-@@ -24356,10 +24209,6 @@ snapshots:dependencies:xml-name-validator: 5.0.0- dependencies:- loose-envify: 1.4.0-dependencies:glob-to-regexp: 0.4.1