@super-calendar/core 2.15.0 → 2.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1625 @@
1
+ import { addDays, addMonths, addWeeks, addYears, differenceInCalendarDays, eachDayOfInterval, endOfMonth, endOfWeek, format, getHours, getMinutes, isAfter, isBefore, isSameDay, isSameMonth, isToday, max, min, startOfDay, startOfMonth, startOfWeek } from "date-fns";
2
+ // src/tokens.ts
3
+ /** The default light-theme colour palette. */
4
+ const lightColors = {
5
+ surface: "#FFFFFF",
6
+ gridLine: "#E2E4E9",
7
+ weekendBackground: "#F6F7F9",
8
+ outsideHoursBackground: "#F1F2F4",
9
+ todayBackground: "#1F6FEB",
10
+ todayText: "#FFFFFF",
11
+ selectedBackground: "#1F6FEB",
12
+ selectedText: "#FFFFFF",
13
+ rangeBackground: "#DCE7FF",
14
+ hoverBackground: "#E6ECF5",
15
+ nowIndicator: "#E5484D",
16
+ text: "#1A1B1E",
17
+ textMuted: "#6B7280",
18
+ textDisabled: "#B5B9C0",
19
+ eventBackground: "#DCE7FF",
20
+ eventText: "#1A1B1E",
21
+ backgroundEvent: "#E3F4E4"
22
+ };
23
+ /** The default dark-theme colour palette. */
24
+ const darkColors = {
25
+ surface: "#1A1B1E",
26
+ gridLine: "#2A2E37",
27
+ weekendBackground: "#15171C",
28
+ outsideHoursBackground: "#101216",
29
+ todayBackground: "#1F6FEB",
30
+ todayText: "#FFFFFF",
31
+ selectedBackground: "#1F6FEB",
32
+ selectedText: "#FFFFFF",
33
+ rangeBackground: "#243B53",
34
+ hoverBackground: "#2E3138",
35
+ nowIndicator: "#E5484D",
36
+ text: "#ECEDEE",
37
+ textMuted: "#9BA1A6",
38
+ textDisabled: "#4B4F58",
39
+ eventBackground: "#243B53",
40
+ eventText: "#EAF2FF",
41
+ backgroundEvent: "#17301F"
42
+ };
43
+ // src/presentation.ts
44
+ /** The band shape for a day, given the fill-cell option. */
45
+ function rangeBandKind(day, fillCell) {
46
+ if (!day.isInRange || day.isRangeStart && day.isRangeEnd) return "none";
47
+ if (fillCell) return "fill";
48
+ if (day.isRangeStart) return "pill-start";
49
+ if (day.isRangeEnd) return "pill-end";
50
+ return "pill-mid";
51
+ }
52
+ /** Whether a band shape rounds its leading / trailing edge (pill ends). */
53
+ function bandRounding(kind) {
54
+ return {
55
+ start: kind === "pill-start",
56
+ end: kind === "pill-end"
57
+ };
58
+ }
59
+ /**
60
+ * The filled-badge kind for a day. `isSelected` is true for both range endpoints
61
+ * and discrete selected days; today always wins when it coincides.
62
+ */
63
+ function dayBadgeKind(day, isToday) {
64
+ if (isToday) return "today";
65
+ if (day.isSelected) return "selected";
66
+ return "none";
67
+ }
68
+ // src/utils/dates.ts
69
+ /** The seven dates of the week containing `date`, starting on `weekStartsOn`. */
70
+ const getWeekDays = (date, weekStartsOn) => {
71
+ const start = startOfWeek(date, { weekStartsOn });
72
+ return Array.from({ length: 7 }, (_, index) => addDays(start, index));
73
+ };
74
+ /**
75
+ * How many day columns a time-grid mode shows. `custom` uses `numberOfDays`.
76
+ * Throws a `RangeError` for `multiweek`, which has week rows instead of day
77
+ * columns; use `buildMultiWeekGrid` for it.
78
+ */
79
+ const viewDayCount = (mode, numberOfDays = 1) => {
80
+ switch (mode) {
81
+ case "week": return 7;
82
+ case "3days": return 3;
83
+ case "custom": return Math.max(1, Math.floor(numberOfDays));
84
+ case "multiweek": throw new RangeError("The multiweek mode has week rows, not day columns. Use buildMultiWeekGrid for its days.");
85
+ default: return 1;
86
+ }
87
+ };
88
+ /**
89
+ * Days in the inclusive span from `weekStartsOn` to `weekEndsOn` (1–7),
90
+ * wrapping when the end precedes the start (e.g. Sat→Wed). Mirrors
91
+ * react-native-big-calendar's `weekDaysCount`.
92
+ */
93
+ const weekDaysCount = (weekStartsOn, weekEndsOn) => {
94
+ if (weekEndsOn < weekStartsOn) {
95
+ let count = 1;
96
+ let i = weekStartsOn;
97
+ while (i !== weekEndsOn && count <= 7) {
98
+ i = (i + 1) % 7;
99
+ count++;
100
+ }
101
+ return count;
102
+ }
103
+ if (weekEndsOn > weekStartsOn) return weekEndsOn - weekStartsOn + 1;
104
+ return 1;
105
+ };
106
+ /**
107
+ * The day columns to render for a time-grid page. `week` spans the calendar week
108
+ * (honouring `weekStartsOn`). `custom` with a `weekEndsOn` spans the partial week
109
+ * from `weekStartsOn` to `weekEndsOn` (anchored to `date`'s week, paging by week);
110
+ * otherwise every mode shows `viewDayCount` consecutive days starting at `date`.
111
+ * Throws a `RangeError` for `multiweek` (see `viewDayCount`).
112
+ */
113
+ const getViewDays = (mode, date, weekStartsOn, numberOfDays = 1, isRTL = false, weekEndsOn, hiddenDays) => {
114
+ const hidden = hiddenDays && hiddenDays.length > 0 && hiddenDays.length < 7 ? hiddenDays : [];
115
+ let days;
116
+ if (mode === "week") days = filterHiddenDays(getWeekDays(date, weekStartsOn), hidden);
117
+ else if (mode === "custom" && weekEndsOn != null) {
118
+ const subject = startOfDay(date);
119
+ const offset = weekStartsOn - subject.getDay();
120
+ days = filterHiddenDays(Array.from({ length: weekDaysCount(weekStartsOn, weekEndsOn) }, (_, index) => addDays(subject, index + offset)), hidden);
121
+ } else {
122
+ const count = viewDayCount(mode, numberOfDays);
123
+ days = [];
124
+ let cursor = startOfDay(date);
125
+ while (days.length < count) {
126
+ if (!hidden.includes(cursor.getDay())) days.push(cursor);
127
+ cursor = addDays(cursor, 1);
128
+ }
129
+ }
130
+ return isRTL ? days.reverse() : days;
131
+ };
132
+ /**
133
+ * The calendar weeks covering `month`, padded to whole weeks starting on
134
+ * `weekStartsOn`. `showSixWeeks` always returns six rows (42 days) for a
135
+ * fixed-height grid; `isRTL` reverses each week's day order.
136
+ */
137
+ const buildMonthWeeks = (month, weekStartsOn, { showSixWeeks = false, isRTL = false, hiddenDays } = {}) => {
138
+ const start = startOfWeek(startOfMonth(month), { weekStartsOn });
139
+ const end = showSixWeeks ? addDays(start, 41) : endOfWeek(endOfMonth(month), { weekStartsOn });
140
+ const days = eachDayOfInterval({
141
+ start,
142
+ end
143
+ });
144
+ const weeks = [];
145
+ for (let index = 0; index < days.length; index += 7) {
146
+ const week = filterHiddenDays(days.slice(index, index + 7), hiddenDays);
147
+ if (week.length > 0) weeks.push(isRTL ? week.reverse() : week);
148
+ }
149
+ return weeks;
150
+ };
151
+ /**
152
+ * Drop the days whose weekday (0=Sunday…6=Saturday) is listed in `hiddenDays`.
153
+ * Hiding all seven weekdays is treated as hiding nothing (matching
154
+ * `getViewDays`), so a misconfiguration degrades to the full grid, not a blank.
155
+ */
156
+ const filterHiddenDays = (days, hiddenDays) => hiddenDays && hiddenDays.length > 0 && new Set(hiddenDays).size < 7 ? days.filter((day) => !hiddenDays.includes(day.getDay())) : days;
157
+ /** True when `date` is a Saturday or Sunday. */
158
+ const isWeekend = (date) => {
159
+ const day = date.getDay();
160
+ return day === 0 || day === 6;
161
+ };
162
+ /** True when `date` falls on the current calendar day. */
163
+ const getIsToday = (date) => isToday(date);
164
+ /** True when `a` and `b` are the same calendar day (ignoring the time of day). */
165
+ const isSameCalendarDay = (a, b) => isSameDay(a, b);
166
+ /** Minutes elapsed since midnight (0–1439). */
167
+ const minutesIntoDay = (date) => getHours(date) * 60 + getMinutes(date);
168
+ /** The twelve month anchors (first-of-month) of `date`'s year, January first. */
169
+ const getYearMonths = (date) => Array.from({ length: 12 }, (_, i) => new Date(date.getFullYear(), i, 1));
170
+ // src/utils/dateRange.ts
171
+ /** Whether `date` passes the min/max/disabled constraints (compared by calendar day). */
172
+ function isDateSelectable(date, constraints = {}) {
173
+ const day = startOfDay(date);
174
+ if (constraints.minDate && isBefore(day, startOfDay(constraints.minDate))) return false;
175
+ if (constraints.maxDate && isAfter(day, startOfDay(constraints.maxDate))) return false;
176
+ if (constraints.isDateDisabled?.(day)) return false;
177
+ return true;
178
+ }
179
+ /**
180
+ * The range after pressing `pressed`, mirroring the familiar date-picker model:
181
+ * - no range yet, or a complete range exists → start fresh (`{ start: pressed, end: null }`),
182
+ * so a third press resets the selection.
183
+ * - an open range (a start but no end) → close it, auto-swapping when the press
184
+ * precedes the start so `start <= end` always holds.
185
+ *
186
+ * Returns `current` unchanged when `pressed` isn't selectable.
187
+ */
188
+ function nextDateRange(current, pressed, constraints = {}) {
189
+ if (!isDateSelectable(pressed, constraints)) return current;
190
+ const day = startOfDay(pressed);
191
+ if (!current || current.end) return {
192
+ start: day,
193
+ end: null
194
+ };
195
+ if (isBefore(day, current.start)) return {
196
+ start: day,
197
+ end: current.start
198
+ };
199
+ return {
200
+ start: current.start,
201
+ end: day
202
+ };
203
+ }
204
+ /** True when `date` is one of the range's two endpoints. */
205
+ function isRangeEndpoint(date, range) {
206
+ if (!range) return false;
207
+ if (isSameCalendarDay(date, range.start)) return true;
208
+ return range.end ? isSameCalendarDay(date, range.end) : false;
209
+ }
210
+ /** True when `date` falls within a complete range (endpoints included). */
211
+ function isWithinDateRange(date, range) {
212
+ if (!range || !range.end) return false;
213
+ const day = startOfDay(date).getTime();
214
+ const a = startOfDay(range.start).getTime();
215
+ const b = startOfDay(range.end).getTime();
216
+ return day >= Math.min(a, b) && day <= Math.max(a, b);
217
+ }
218
+ /**
219
+ * The canonical per-day selection state, shared by `MonthView` (rendering) and
220
+ * `buildMonthGrid` (the headless grid) so the built-in views and a custom
221
+ * calendar can never disagree on what a day's state is.
222
+ */
223
+ function daySelectionState(date, selection, constraints = {}) {
224
+ const isDisabled = !isDateSelectable(date, constraints);
225
+ const range = selection.selectedRange ?? null;
226
+ return {
227
+ isDisabled,
228
+ isSelected: !isDisabled && ((selection.selectedDates?.some((selected) => isSameCalendarDay(selected, date)) ?? false) || isRangeEndpoint(date, range)),
229
+ isInRange: !isDisabled && isWithinDateRange(date, range),
230
+ isRangeStart: !isDisabled && range != null && isSameCalendarDay(date, range.start),
231
+ isRangeEnd: !isDisabled && range?.end != null && isSameCalendarDay(date, range.end)
232
+ };
233
+ }
234
+ // src/utils/minDuration.ts
235
+ const MIN_DURATION_HOURS = .25;
236
+ // src/utils/layout.ts
237
+ /**
238
+ * The fractional hour `date` shows on the clock, which is the time-grid row it
239
+ * belongs in, clamped to `[dayStart, nextDayStart]` so the midnight that ends
240
+ * the day reads 24. On a DST change day this differs from the time elapsed
241
+ * since midnight: after clocks go back, 10:00 is 11 hours in but reads 10.
242
+ * Worklet-safe, so a UI-thread preview places events the same way.
243
+ */
244
+ function wallClockHours(date, dayStart, nextDayStart) {
245
+ "worklet";
246
+ if (date.getTime() >= nextDayStart.getTime()) return 24;
247
+ if (date.getTime() <= dayStart.getTime()) return 0;
248
+ return date.getHours() + date.getMinutes() / 60 + date.getSeconds() / 3600 + date.getMilliseconds() / 36e5;
249
+ }
250
+ /**
251
+ * The hours between `from` and `to` as the clock reads them: the elapsed hours
252
+ * plus any DST offset change between the two, so 01:30 to 03:30 is 2 even on a
253
+ * spring-forward day when only 1 hour passes. In the hour a fall-back change
254
+ * repeats the clock can read earlier at `to` than at `from` (01:30 EDT to 01:00
255
+ * EST); such a span keeps its elapsed length so it still has a size to draw.
256
+ * Worklet-safe, so a UI-thread drag preview sizes boxes the same way.
257
+ */
258
+ function clockHoursBetween(from, to) {
259
+ "worklet";
260
+ const elapsed = (to.getTime() - from.getTime()) / 36e5;
261
+ const clock = elapsed + (from.getTimezoneOffset() - to.getTimezoneOffset()) / 60;
262
+ return clock > 0 || elapsed <= 0 ? clock : elapsed;
263
+ }
264
+ /**
265
+ * The instant a time grid draws the bottom edge of `[start, end]` at. That is
266
+ * `end`, except in the hour a fall-back change repeats: a span whose clock runs
267
+ * backwards (01:30 EDT to 01:00 EST) is drawn its elapsed length from `start`
268
+ * (see {@link clockHoursBetween}), so its edge reads 02:00. Resizing from that
269
+ * instant keeps the edge under the pointer. Worklet-safe.
270
+ */
271
+ function drawnEnd(start, end) {
272
+ "worklet";
273
+ const offsetChange = end.getTimezoneOffset() - start.getTimezoneOffset();
274
+ const elapsed = end.getTime() - start.getTime();
275
+ if (elapsed <= 0 || elapsed - offsetChange * 6e4 > 0) return end;
276
+ return new Date(end.getTime() + offsetChange * 6e4);
277
+ }
278
+ const clockSpan = (from, to, dayStart, nextDayStart) => {
279
+ const start = wallClockHours(from, dayStart, nextDayStart);
280
+ return {
281
+ start,
282
+ end: Math.min(24, start + clockHoursBetween(from, to))
283
+ };
284
+ };
285
+ /**
286
+ * Lay out a single day's events: events that overlap in time are split into
287
+ * side-by-side columns. Multi-day events are clipped to the portion that falls
288
+ * on `day` (e.g. a 23:00→01:00 event renders 23:00–24:00 on the start day and
289
+ * 00:00–01:00 on the next). Pure — safe to call per render, never per frame.
290
+ */
291
+ function layoutDayEvents(events, day) {
292
+ const dayStart = startOfDay(day);
293
+ const nextDayStart = addDays(dayStart, 1);
294
+ const segments = events.filter((event) => !isAllDayEvent(event) && !isBackgroundEvent(event)).filter((event) => event.start < nextDayStart && event.end > dayStart).map((event) => {
295
+ const segStart = max([event.start, dayStart]);
296
+ const segEnd = min([event.end, nextDayStart]);
297
+ return {
298
+ event,
299
+ ...clockSpan(segStart, segEnd, dayStart, nextDayStart),
300
+ continuesBefore: event.start < dayStart,
301
+ continuesAfter: event.end > nextDayStart
302
+ };
303
+ }).sort((a, b) => a.start - b.start);
304
+ const positioned = [];
305
+ let cluster = [];
306
+ let clusterEnd = Number.NEGATIVE_INFINITY;
307
+ const flushCluster = () => {
308
+ const columnEnds = [];
309
+ const columnOf = /* @__PURE__ */ new Map();
310
+ for (const seg of cluster) {
311
+ let column = columnEnds.findIndex((end) => end <= seg.start);
312
+ if (column === -1) {
313
+ column = columnEnds.length;
314
+ columnEnds.push(seg.end);
315
+ } else columnEnds[column] = seg.end;
316
+ columnOf.set(seg, column);
317
+ }
318
+ for (const seg of cluster) positioned.push({
319
+ event: seg.event,
320
+ startHours: seg.start,
321
+ durationHours: Math.max(seg.end - seg.start, MIN_DURATION_HOURS),
322
+ column: columnOf.get(seg) ?? 0,
323
+ columns: columnEnds.length,
324
+ continuesBefore: seg.continuesBefore,
325
+ continuesAfter: seg.continuesAfter
326
+ });
327
+ cluster = [];
328
+ };
329
+ for (const seg of segments) {
330
+ if (cluster.length > 0 && seg.start >= clusterEnd) flushCluster();
331
+ cluster.push(seg);
332
+ clusterEnd = Math.max(clusterEnd, seg.end);
333
+ }
334
+ if (cluster.length > 0) flushCluster();
335
+ return positioned;
336
+ }
337
+ const atMidnight = (date) => date.getHours() === 0 && date.getMinutes() === 0 && date.getSeconds() === 0 && date.getMilliseconds() === 0;
338
+ /**
339
+ * Whether an event belongs in the all-day lane. An explicit `allDay` flag wins;
340
+ * otherwise it's inferred when the event spans whole days (both `start` and
341
+ * `end` land on midnight, e.g. an iCal-style all-day event). Pure.
342
+ */
343
+ function isAllDayEvent(event) {
344
+ if (typeof event.allDay === "boolean") return event.allDay;
345
+ return event.end > event.start && atMidnight(event.start) && atMidnight(event.end);
346
+ }
347
+ /**
348
+ * The `startOfDay` ISO keys of every calendar day an event touches (inclusive).
349
+ * An event ending exactly at midnight does not count the following day. Used to
350
+ * index events by day for the month grid. Pure.
351
+ */
352
+ function eventDayKeys(event) {
353
+ const first = startOfDay(event.start);
354
+ const lastInstant = event.end > event.start ? /* @__PURE__ */ new Date(event.end.getTime() - 1) : event.start;
355
+ const last = startOfDay(lastInstant);
356
+ const keys = [];
357
+ for (let cursor = first; cursor <= last; cursor = addDays(cursor, 1)) keys.push(cursor.toISOString());
358
+ return keys;
359
+ }
360
+ /**
361
+ * Index events by the `startOfDay` ISO key of every day they touch (via
362
+ * {@link eventDayKeys}), so a month grid can look up a day's events with
363
+ * `startOfDay(date).toISOString()`. Built once and shared across month cells.
364
+ */
365
+ function groupEventsByDay(events) {
366
+ const map = /* @__PURE__ */ new Map();
367
+ for (const event of events) for (const key of eventDayKeys(event)) {
368
+ const list = map.get(key);
369
+ if (list) list.push(event);
370
+ else map.set(key, [event]);
371
+ }
372
+ return map;
373
+ }
374
+ /**
375
+ * Order a day's events for the month and list views: all-day events come first
376
+ * (they head the day regardless of their start time), then timed events by start.
377
+ * Shared by both renderers so the order is identical. Use as an `Array.sort`
378
+ * comparator.
379
+ */
380
+ function compareDayEvents(a, b) {
381
+ const aAllDay = isAllDayEvent(a);
382
+ if (aAllDay !== isAllDayEvent(b)) return aAllDay ? -1 : 1;
383
+ return a.start.getTime() - b.start.getTime();
384
+ }
385
+ /**
386
+ * The closed hour-spans of a day to shade on the time grid, given a
387
+ * `businessHours` callback and the visible `[minHour, maxHour]` window: the spans
388
+ * before open and after close (clamped to the window), the whole window when the
389
+ * day is closed (`null`) or the open hours are inverted/empty, or none when the
390
+ * callback returns `undefined`. Shared by both renderers so shading stays
391
+ * identical. Co-located with `groupEventsByDay`; both feed the grid layout.
392
+ */
393
+ function closedHourBands(day, businessHours, minHour = 0, maxHour = 24) {
394
+ const open = businessHours?.(day);
395
+ if (open === void 0) return [];
396
+ if (open === null) return [{
397
+ start: minHour,
398
+ end: maxHour
399
+ }];
400
+ const windows = (Array.isArray(open) ? open : [open]).map((w) => ({
401
+ start: Math.max(minHour, Math.min(maxHour, w.start)),
402
+ end: Math.max(minHour, Math.min(maxHour, w.end))
403
+ })).filter((w) => w.end > w.start).sort((a, b) => a.start - b.start);
404
+ if (windows.length === 0) return [{
405
+ start: minHour,
406
+ end: maxHour
407
+ }];
408
+ const merged = [];
409
+ for (const w of windows) {
410
+ const last = merged[merged.length - 1];
411
+ if (last && w.start <= last.end) last.end = Math.max(last.end, w.end);
412
+ else merged.push({ ...w });
413
+ }
414
+ const bands = [];
415
+ let cursor = minHour;
416
+ for (const w of merged) {
417
+ if (w.start > cursor) bands.push({
418
+ start: cursor,
419
+ end: w.start
420
+ });
421
+ cursor = w.end;
422
+ }
423
+ if (cursor < maxHour) bands.push({
424
+ start: cursor,
425
+ end: maxHour
426
+ });
427
+ return bands;
428
+ }
429
+ /** True when the event paints as a shaded background band, not an event box. */
430
+ function isBackgroundEvent(event) {
431
+ return event.display === "background";
432
+ }
433
+ /**
434
+ * The background events of `events` sliced to `day`, as fractional-hour bands
435
+ * (an all-day or multi-day background covers the day's full window). Shared by
436
+ * both renderers so the shading can't disagree.
437
+ */
438
+ function backgroundBandsForDay(events, day) {
439
+ const dayStart = startOfDay(day);
440
+ const nextDayStart = addDays(dayStart, 1);
441
+ const out = [];
442
+ for (const event of events) {
443
+ if (!isBackgroundEvent(event)) continue;
444
+ if (event.start >= nextDayStart || event.end <= dayStart) continue;
445
+ const from = event.start > dayStart ? event.start : dayStart;
446
+ const to = event.end < nextDayStart ? event.end : nextDayStart;
447
+ const { start: startHours, end: endHours } = clockSpan(from, to, dayStart, nextDayStart);
448
+ if (endHours > startHours) out.push({
449
+ event,
450
+ startHours,
451
+ endHours
452
+ });
453
+ }
454
+ return out;
455
+ }
456
+ // src/utils/drag.ts
457
+ /**
458
+ * True when two time ranges overlap. Edges touching (one ends exactly when the
459
+ * next begins) do not count as an overlap. Compares absolute instants, so events
460
+ * at the same wall-clock time on different days do not overlap.
461
+ */
462
+ function eventsOverlap(aStart, aEnd, bStart, bEnd) {
463
+ return aStart.getTime() < bEnd.getTime() && bStart.getTime() < aEnd.getTime();
464
+ }
465
+ /**
466
+ * True when the range `[start, end)` would overlap any event in `events` other
467
+ * than `moved` (compared by reference). Used by the `eventOverlap` guard to reject
468
+ * a drag/resize that would land an event on top of another.
469
+ */
470
+ function overlapsOtherEvents(events, moved, start, end) {
471
+ return events.some((e) => e !== moved && eventsOverlap(e.start, e.end, start, end));
472
+ }
473
+ /**
474
+ * How many calendar days one time-grid page spans, used to advance the view by a
475
+ * whole page (e.g. when dragging an event past the edge into the next week).
476
+ * Deliberately ignores `hiddenDays` so a week always steps 7, matching the
477
+ * keyboard PageUp/PageDown paging and `Calendar`'s own page step.
478
+ */
479
+ function pageStepDays(mode, date, weekStartsOn, numberOfDays = 1) {
480
+ return getViewDays(mode, date, weekStartsOn, numberOfDays).length;
481
+ }
482
+ /**
483
+ * Minutes to shift an event, snapping a vertical pixel drag to the nearest
484
+ * `stepMinutes`. Runs on the UI thread inside the drag gesture. Returns 0 for a
485
+ * degenerate grid (non-positive height/step).
486
+ */
487
+ function snapDeltaMinutes(translationPx, cellHeightPx, stepMinutes) {
488
+ "worklet";
489
+ if (cellHeightPx <= 0 || stepMinutes <= 0) return 0;
490
+ const rawMinutes = translationPx / cellHeightPx * 60;
491
+ return Math.round(rawMinutes / stepMinutes) * stepMinutes;
492
+ }
493
+ /**
494
+ * Where a moved event may start, in minutes from midnight, given the grid's
495
+ * visible hour window. A move keeps its duration, so only the start is held
496
+ * inside the window: it can reach one `snapMinutes` step before `maxHour`, and
497
+ * the end is free to run past the end of the day, continuing on the following
498
+ * day. That keeps the event starting in the column it was dropped on (a
499
+ * cross-day *move* is the horizontal drag) while still allowing a range that
500
+ * spans midnight. Runs on the UI thread inside the drag gesture.
501
+ */
502
+ function clampMoveStartMinutes(startMinutes, minHour, maxHour, snapMinutes) {
503
+ "worklet";
504
+ const lower = minHour * 60;
505
+ const upper = Math.max(lower, maxHour * 60 - snapMinutes);
506
+ return Math.min(Math.max(startMinutes, lower), upper);
507
+ }
508
+ function nearestOccurrence(date, target) {
509
+ "worklet";
510
+ const offset = date.getTimezoneOffset();
511
+ const later = new Date(date.getTime() + 108e5).getTimezoneOffset() - offset;
512
+ const earlier = offset - (/* @__PURE__ */ new Date(date.getTime() - 108e5)).getTimezoneOffset();
513
+ let best = date;
514
+ for (const change of [later, -earlier]) {
515
+ if (change === 0) continue;
516
+ const other = new Date(date.getTime() + change * 6e4);
517
+ if (other.getHours() !== date.getHours() || other.getMinutes() !== date.getMinutes()) continue;
518
+ if (Math.abs(other.getTime() - target) < Math.abs(best.getTime() - target)) best = other;
519
+ }
520
+ return best;
521
+ }
522
+ /**
523
+ * A copy of `date` shifted by `minutes` (may be negative) on the clock, so a
524
+ * shift across a DST change keeps the clock time. When the resulting clock time
525
+ * occurs twice (the hour a fall-back change repeats), the occurrence nearer to
526
+ * `minutes` of elapsed time wins.
527
+ */
528
+ function shiftMinutes(date, minutes) {
529
+ "worklet";
530
+ const next = new Date(date);
531
+ next.setMinutes(next.getMinutes() + minutes);
532
+ return nearestOccurrence(next, date.getTime() + minutes * 6e4);
533
+ }
534
+ const localTime = (date) => date.getTime() - date.getTimezoneOffset() * 6e4;
535
+ /**
536
+ * Where moving `[start, end]` by `minutes` on the clock lands, in clock hours:
537
+ * how far the start moves, and how many rows the moved span covers. The span
538
+ * keeps its elapsed duration, as {@link resolveDraggedBounds} commits a move, so
539
+ * gaining or losing a DST change changes its row count, and a start that lands
540
+ * in the hour a spring-forward change skips moves on past it. The row count is
541
+ * at least the layout's minimum box, as the committed event will be drawn.
542
+ * Worklet-safe, for live drag previews.
543
+ */
544
+ function movedClockSpan(start, end, minutes) {
545
+ "worklet";
546
+ const nextStart = shiftMinutes(start, minutes);
547
+ const nextEnd = new Date(nextStart.getTime() + end.getTime() - start.getTime());
548
+ return {
549
+ startHours: (nextStart.getTime() - start.getTime()) / 36e5 + (start.getTimezoneOffset() - nextStart.getTimezoneOffset()) / 60,
550
+ hours: Math.max(clockHoursBetween(nextStart, nextEnd), MIN_DURATION_HOURS)
551
+ };
552
+ }
553
+ /**
554
+ * Resolve a committed drag into the event's new bounds: `start` shifts by
555
+ * `deltaStartMinutes`, `end` by `deltaEndMinutes` (a move passes the same delta
556
+ * to both and preserves elapsed duration, including across DST; a resize passes
557
+ * 0 for the unchanged edge). Returns `null` only when the change
558
+ * would *shrink* the event below one `snapMinutes` step, so a resize can't commit
559
+ * a degenerate duration; a pure move (both deltas equal) keeps its duration and is
560
+ * never rejected, even for an already sub-step event. Pure, so the commit path is
561
+ * unit-testable without a running gesture.
562
+ */
563
+ function resolveDraggedBounds(start, end, deltaStartMinutes, deltaEndMinutes, snapMinutes) {
564
+ const nextStart = shiftMinutes(start, deltaStartMinutes);
565
+ const oldDuration = end.getTime() - start.getTime();
566
+ let nextEnd = end;
567
+ if (deltaStartMinutes === deltaEndMinutes) nextEnd = new Date(nextStart.getTime() + oldDuration);
568
+ else if (deltaEndMinutes !== 0) {
569
+ const target = shiftMinutes(drawnEnd(start, end), deltaEndMinutes);
570
+ nextEnd = nearestOccurrence(target, end.getTime() + deltaEndMinutes * 6e4);
571
+ if (localTime(drawnEnd(nextStart, nextEnd)) !== localTime(target)) return null;
572
+ }
573
+ const newDuration = nextEnd.getTime() - nextStart.getTime();
574
+ if (newDuration < snapMinutes * 6e4 && newDuration < oldDuration) return null;
575
+ return {
576
+ start: nextStart,
577
+ end: nextEnd
578
+ };
579
+ }
580
+ /**
581
+ * The all-day range swept out between two day cells of the month grid, ordered
582
+ * whichever way the sweep ran: `start` is midnight of the first day and `end` is
583
+ * midnight after the last, so a one-day sweep still yields a usable event. Shared
584
+ * by both renderers so a month drag-to-create means the same thing on each.
585
+ */
586
+ function monthCreateRange(anchor, hover) {
587
+ const a = startOfDay(anchor);
588
+ const b = startOfDay(hover);
589
+ const first = a.getTime() <= b.getTime() ? a : b;
590
+ const last = a.getTime() <= b.getTime() ? b : a;
591
+ return {
592
+ start: first,
593
+ end: addDays(last, 1)
594
+ };
595
+ }
596
+ /**
597
+ * The new bounds for an event picked up on `fromDay` and dropped on `toDay` in
598
+ * the month grid: both ends move by the same number of calendar days, so the
599
+ * event keeps its time of day and duration (DST included). Returns `null` when
600
+ * the drop lands on the day it started, so a stray drag commits nothing.
601
+ */
602
+ function monthDropBounds(event, fromDay, toDay) {
603
+ const delta = differenceInCalendarDays(startOfDay(toDay), startOfDay(fromDay));
604
+ if (delta === 0) return null;
605
+ return {
606
+ start: addDays(event.start, delta),
607
+ end: addDays(event.end, delta)
608
+ };
609
+ }
610
+ /**
611
+ * The start/end of a new event swept out on `day` by dragging from `startPx` to
612
+ * `endPx` (vertical pixels from the grid's top, i.e. the `minHour` line). Both
613
+ * ends snap to `snapMinutes`; the range is ordered (drag up or down) and widened
614
+ * to at least one step so a stationary press still yields a usable event.
615
+ * Returns `null` for a degenerate grid (non-positive height/step). Pure, so the
616
+ * commit path is unit-testable without a running gesture.
617
+ */
618
+ function cellRangeFromDrag(day, startPx, endPx, cellHeightPx, minHour, snapMinutes) {
619
+ if (cellHeightPx <= 0 || snapMinutes <= 0) return null;
620
+ const snapAt = (px) => {
621
+ const rawMinutes = (minHour + px / cellHeightPx) * 60;
622
+ return Math.round(rawMinutes / snapMinutes) * snapMinutes;
623
+ };
624
+ const MAX = 1440;
625
+ let lower = Math.max(0, Math.min(MAX - snapMinutes, snapAt(startPx)));
626
+ let upper = Math.max(0, Math.min(MAX, snapAt(endPx)));
627
+ if (upper < lower) [lower, upper] = [upper, lower];
628
+ if (upper - lower < snapMinutes) upper = Math.min(MAX, lower + snapMinutes);
629
+ const start = new Date(day);
630
+ start.setHours(0, 0, 0, 0);
631
+ start.setMinutes(lower);
632
+ const end = new Date(day);
633
+ end.setHours(0, 0, 0, 0);
634
+ end.setMinutes(upper);
635
+ return {
636
+ start,
637
+ end
638
+ };
639
+ }
640
+ // src/utils/labels.ts
641
+ const minutes = (n) => `${n} minute${n === 1 ? "" : "s"}`;
642
+ const page = (days, mode) => mode === "week" ? "week" : days === 1 ? "day" : `${days} days`;
643
+ /** The built-in English {@link CalendarLabels}. */
644
+ const defaultCalendarLabels = {
645
+ today: "today",
646
+ selected: "selected",
647
+ unavailable: "unavailable",
648
+ hasEvents: "has events",
649
+ eventCount: (count) => count === 1 ? "1 event" : `${count} events`,
650
+ moreEvents: (count) => `${count} more events`,
651
+ allDay: "all-day",
652
+ allDayEvent: "all day",
653
+ timeRange: (start, end) => `${start} to ${end}`,
654
+ close: "Close",
655
+ moveLater: (n) => `Move ${minutes(n)} later`,
656
+ moveEarlier: (n) => `Move ${minutes(n)} earlier`,
657
+ extend: (n) => `Extend by ${minutes(n)}`,
658
+ shorten: (n) => `Shorten by ${minutes(n)}`,
659
+ moveToNextPage: (days, mode) => `Move to next ${page(days, mode)}`,
660
+ moveToPreviousPage: (days, mode) => `Move to previous ${page(days, mode)}`,
661
+ moveToResource: (title) => `Move to ${title}`,
662
+ eventActions: (title) => title ? `Move or resize ${title}` : "Move or resize event",
663
+ editEvents: "Edit events",
664
+ eventChangeRejected: "This change is not allowed."
665
+ };
666
+ /** Fill the labels a consumer left out with {@link defaultCalendarLabels}. */
667
+ function resolveCalendarLabels(labels) {
668
+ return labels ? {
669
+ ...defaultCalendarLabels,
670
+ ...labels
671
+ } : defaultCalendarLabels;
672
+ }
673
+ /**
674
+ * Screen-reader label for a day: the formatted date followed by its state
675
+ * words, joined with ", " (e.g. "Friday, 17 July 2026, today, 3 events").
676
+ */
677
+ function dayAccessibilityLabel(args) {
678
+ const { labels } = args;
679
+ return [
680
+ args.dateLabel,
681
+ args.isToday ? labels.today : null,
682
+ args.isSelected ? labels.selected : null,
683
+ args.isDisabled ? labels.unavailable : null,
684
+ args.hasEvents ? labels.hasEvents : null,
685
+ args.eventCount == null ? null : labels.eventCount(args.eventCount)
686
+ ].filter(Boolean).join(", ");
687
+ }
688
+ // src/utils/eventDisplay.ts
689
+ /**
690
+ * Minimum event-box height (px) before the built-in renderer shows the time line
691
+ * on a narrow multi-column timed grid. Tied to the default theme's font sizes.
692
+ */
693
+ const MIN_BOX_HEIGHT_FOR_TIME = 56;
694
+ /** Hard-clip an overflowing title by default; opt into a trailing ellipsis. */
695
+ function titleEllipsizeMode(ellipsizeTitle) {
696
+ return ellipsizeTitle ? "tail" : "clip";
697
+ }
698
+ /**
699
+ * Screen-reader label for an event: its title followed by "all day" or its time
700
+ * range (which the grid otherwise only conveys visually). Empty title is dropped.
701
+ */
702
+ function eventAccessibilityLabel(args) {
703
+ const labels = args.labels ?? defaultCalendarLabels;
704
+ const timeFormat = args.ampm ? "h:mm a" : "HH:mm";
705
+ const time = args.isAllDay ? args.allDayLabel ?? labels.allDayEvent : labels.timeRange(format(args.start, timeFormat), format(args.end, timeFormat));
706
+ return [args.title, time].filter(Boolean).join(", ");
707
+ }
708
+ /**
709
+ * Month and multi-week cells and the all-day lane show a single clipped line;
710
+ * timed-grid titles (`undefined`) wrap to fill the box.
711
+ */
712
+ function titleNumberOfLines(mode, isAllDay) {
713
+ return mode === "month" || mode === "multiweek" || isAllDay ? 1 : void 0;
714
+ }
715
+ /**
716
+ * The secondary line under the title in the built-in renderer, or `null` when
717
+ * none should show. Timed events get their `start - end` range. An all-day event
718
+ * gets the literal "All day" in the schedule (which has no all-day lane to
719
+ * signal it positionally) and nothing on the day/week grid (the lane already
720
+ * does). Month and multi-week cells and `showTime={false}` always return `null`.
721
+ */
722
+ function eventTimeLabel(args) {
723
+ if (!args.showTime || args.mode === "month" || args.mode === "multiweek") return null;
724
+ if (args.isAllDay) return args.mode === "schedule" ? args.allDayLabel ?? "All day" : null;
725
+ const timeFormat = args.ampm ? "h:mm a" : "HH:mm";
726
+ return `${format(args.start, timeFormat)} - ${format(args.end, timeFormat)}`;
727
+ }
728
+ /**
729
+ * The default hour-axis label shared by both renderers' time grids, so the gutter
730
+ * reads the same on each: 24-hour "HH:00" (e.g. "08:00"), or a compact 12-hour
731
+ * "h AM/PM" (e.g. "8 AM") when `ampm` is set. Exported so a custom hour renderer
732
+ * can reuse the same formatting.
733
+ */
734
+ function formatHour(hour, opts) {
735
+ if (opts?.ampm) {
736
+ const period = hour < 12 ? "AM" : "PM";
737
+ return `${hour % 12 === 0 ? 12 : hour % 12} ${period}`;
738
+ }
739
+ return `${String(hour).padStart(2, "0")}:00`;
740
+ }
741
+ /**
742
+ * Whether the time line fits in the box. The wide `day` column and contexts with
743
+ * no live box height (e.g. schedule, where `boxHeightPx` is undefined) always
744
+ * show it; narrow multi-column modes only once the box is at least
745
+ * {@link MIN_BOX_HEIGHT_FOR_TIME} tall. Runs on the UI thread inside the event
746
+ * renderer's animated style.
747
+ */
748
+ function isTimeVisibleAtHeight(boxHeightPx, mode) {
749
+ "worklet";
750
+ if (boxHeightPx == null || mode === "day") return true;
751
+ return boxHeightPx >= 56;
752
+ }
753
+ /**
754
+ * Lay out the built-in timed-grid event chip for a box of `boxHeightPx`: how
755
+ * many whole title lines fit, and whether the time line still has room below
756
+ * them. The title is primary, so the title fills the box in whole lines (never a
757
+ * half-cropped line) and the time only shows once a full line is left over. Pass
758
+ * `titleLineHeightPx`/`timeLineHeightPx` matching the rendered line heights so
759
+ * the clamp lands on a line boundary.
760
+ *
761
+ * Worklet-safe, so the native renderer can drive the title's max-height on the UI
762
+ * thread as the grid zooms; the dom renderer calls it with its static box height.
763
+ * A `boxHeightPx` of `undefined` (the schedule has no live box height) returns
764
+ * `titleMaxLines: 0` (no clamp) with the unconditional time visibility.
765
+ */
766
+ function eventChipLayout(args) {
767
+ "worklet";
768
+ const wantTime = args.hasTime && isTimeVisibleAtHeight(args.boxHeightPx, args.mode);
769
+ if (args.boxHeightPx == null || args.titleLineHeightPx <= 0) return {
770
+ titleMaxLines: 0,
771
+ showTime: wantTime
772
+ };
773
+ const inner = args.boxHeightPx - args.paddingYPx * 2;
774
+ const titleMaxLines = Math.max(1, Math.floor((inner - (wantTime ? args.timeLineHeightPx : 0)) / args.titleLineHeightPx));
775
+ return {
776
+ titleMaxLines,
777
+ showTime: wantTime && inner - titleMaxLines * args.titleLineHeightPx >= args.timeLineHeightPx
778
+ };
779
+ }
780
+ /**
781
+ * Derive how many event chips fit in a month cell from the measured space.
782
+ * `chipRowHeightPx` is one chip plus its gap; `moreRowHeightPx` is the overflow
783
+ * label plus its gap. Both counts are clamped to >= 0.
784
+ */
785
+ function monthEventCapacity(availableHeightPx, chipRowHeightPx, moreRowHeightPx) {
786
+ if (chipRowHeightPx <= 0) return {
787
+ full: 0,
788
+ withMore: 0
789
+ };
790
+ return {
791
+ full: Math.max(0, Math.floor(availableHeightPx / chipRowHeightPx)),
792
+ withMore: Math.max(0, Math.floor((availableHeightPx - moreRowHeightPx) / chipRowHeightPx))
793
+ };
794
+ }
795
+ /**
796
+ * Chips to show for a day: all of them when they fit, otherwise `withMore` (at
797
+ * least one) so the rest collapse into a "+N more" label.
798
+ */
799
+ function monthVisibleCount(total, capacity) {
800
+ if (total <= capacity.full) return total;
801
+ return Math.max(1, capacity.withMore);
802
+ }
803
+ // src/utils/timezone.ts
804
+ /**
805
+ * Reinterpret an instant as its wall-clock time in `timeZone`, returned as a
806
+ * device-local `Date` whose fields (hours, minutes, …) read back as that zone's
807
+ * clock. The calendar lays events out from `getHours()`/`getMinutes()`, so
808
+ * passing zoned dates makes it render in `timeZone` regardless of the device.
809
+ *
810
+ * DST-correct via `Intl` (available on modern React Native Hermes/JSC and the
811
+ * web). The result is for display/layout only; it no longer points at the
812
+ * original UTC instant, so don't round-trip it back to a real time.
813
+ */
814
+ function toZonedTime(date, timeZone) {
815
+ const parts = new Intl.DateTimeFormat("en-US", {
816
+ timeZone,
817
+ hourCycle: "h23",
818
+ year: "numeric",
819
+ month: "2-digit",
820
+ day: "2-digit",
821
+ hour: "2-digit",
822
+ minute: "2-digit",
823
+ second: "2-digit"
824
+ }).formatToParts(date);
825
+ const field = (type) => {
826
+ const part = parts.find((p) => p.type === type);
827
+ return part ? Number(part.value) : 0;
828
+ };
829
+ const hour = field("hour") % 24;
830
+ return new Date(field("year"), field("month") - 1, field("day"), hour, field("minute"), field("second"), date.getMilliseconds());
831
+ }
832
+ function zoneOffsetMs(instant, timeZone) {
833
+ const z = toZonedTime(instant, timeZone);
834
+ return Date.UTC(z.getFullYear(), z.getMonth(), z.getDate(), z.getHours(), z.getMinutes(), z.getSeconds(), z.getMilliseconds()) - instant.getTime();
835
+ }
836
+ /**
837
+ * The inverse of {@link toZonedTime}: given a wall-clock time in `timeZone`,
838
+ * return the absolute UTC instant. Pass the wall clock as a `Date` whose **UTC**
839
+ * fields hold the components (e.g. `new Date(Date.UTC(y, m, d, h, min))`). Used to
840
+ * resolve iCal `TZID` times; DST-correct via a two-pass offset (ambiguous
841
+ * fall-back times resolve to the post-transition offset).
842
+ */
843
+ function zonedTimeToUtc(wallClock, timeZone) {
844
+ const guess = wallClock.getTime();
845
+ const firstPass = zoneOffsetMs(new Date(guess), timeZone);
846
+ const secondPass = zoneOffsetMs(new Date(guess - firstPass), timeZone);
847
+ return new Date(guess - secondPass);
848
+ }
849
+ /**
850
+ * Map every event's `start`/`end` through {@link toZonedTime} so the calendar
851
+ * displays them in `timeZone`. Other fields are preserved. Memoize the result
852
+ * (e.g. with `useMemo`) since it allocates new dates.
853
+ */
854
+ function eventsInTimeZone(events, timeZone) {
855
+ return events.map((event) => ({
856
+ ...event,
857
+ start: toZonedTime(event.start, timeZone),
858
+ end: toZonedTime(event.end, timeZone)
859
+ }));
860
+ }
861
+ // src/utils/ical.ts
862
+ const RRULE_FREQ = {
863
+ DAILY: "daily",
864
+ WEEKLY: "weekly",
865
+ MONTHLY: "monthly",
866
+ YEARLY: "yearly"
867
+ };
868
+ const FREQ_RRULE = {
869
+ daily: "DAILY",
870
+ weekly: "WEEKLY",
871
+ monthly: "MONTHLY",
872
+ yearly: "YEARLY"
873
+ };
874
+ const BYDAY = [
875
+ "SU",
876
+ "MO",
877
+ "TU",
878
+ "WE",
879
+ "TH",
880
+ "FR",
881
+ "SA"
882
+ ];
883
+ const pad = (n, width = 2) => String(n).padStart(width, "0");
884
+ function escapeText(value) {
885
+ return value.replace(/\\/g, "\\\\").replace(/;/g, "\\;").replace(/,/g, "\\,").replace(/\n/g, "\\n");
886
+ }
887
+ function unescapeText(value) {
888
+ let out = "";
889
+ for (let i = 0; i < value.length; i++) {
890
+ const ch = value[i];
891
+ if (ch === "\\" && i + 1 < value.length) {
892
+ const next = value[++i];
893
+ out += next === "n" || next === "N" ? "\n" : next;
894
+ } else out += ch;
895
+ }
896
+ return out;
897
+ }
898
+ function foldLine(line) {
899
+ if (line.length <= 75) return line;
900
+ const parts = [line.slice(0, 75)];
901
+ let rest = line.slice(75);
902
+ while (rest.length > 74) {
903
+ parts.push(` ${rest.slice(0, 74)}`);
904
+ rest = rest.slice(74);
905
+ }
906
+ parts.push(` ${rest}`);
907
+ return parts.join("\r\n");
908
+ }
909
+ function unfoldLines(text) {
910
+ const raw = text.split(/\r\n|\r|\n/);
911
+ const out = [];
912
+ for (const line of raw) if ((line.startsWith(" ") || line.startsWith(" ")) && out.length) out[out.length - 1] += line.slice(1);
913
+ else out.push(line);
914
+ return out;
915
+ }
916
+ /** Serialize a Date as a UTC iCal date-time (`YYYYMMDDTHHMMSSZ`). */
917
+ function formatUtc(d) {
918
+ return `${d.getUTCFullYear()}${pad(d.getUTCMonth() + 1)}${pad(d.getUTCDate())}T${pad(d.getUTCHours())}${pad(d.getUTCMinutes())}${pad(d.getUTCSeconds())}Z`;
919
+ }
920
+ /** Serialize a Date as an iCal date-only value (`YYYYMMDD`) from its local parts. */
921
+ function formatDateOnly(d) {
922
+ return `${d.getFullYear()}${pad(d.getMonth() + 1)}${pad(d.getDate())}`;
923
+ }
924
+ /**
925
+ * Parse an iCal DATE / DATE-TIME value. `dateOnly` marks all-day (`VALUE=DATE`);
926
+ * `tzid` is the IANA zone from a `TZID=` param, used to resolve the local time to
927
+ * the correct UTC instant.
928
+ */
929
+ function parseIcalDate(value, dateOnly, tzid) {
930
+ const y = Number(value.slice(0, 4));
931
+ const mo = Number(value.slice(4, 6)) - 1;
932
+ const d = Number(value.slice(6, 8));
933
+ if (dateOnly || !value.includes("T")) return new Date(y, mo, d);
934
+ const h = Number(value.slice(9, 11));
935
+ const mi = Number(value.slice(11, 13));
936
+ const s = Number(value.slice(13, 15));
937
+ if (value.endsWith("Z")) return new Date(Date.UTC(y, mo, d, h, mi, s));
938
+ if (tzid) try {
939
+ return zonedTimeToUtc(new Date(Date.UTC(y, mo, d, h, mi, s)), tzid);
940
+ } catch {}
941
+ return new Date(y, mo, d, h, mi, s);
942
+ }
943
+ /** Parse an iCal/ISO-8601 DURATION (e.g. `PT1H30M`, `P1D`, `P1W`) to milliseconds. */
944
+ function parseDuration(value) {
945
+ const m = /^([+-]?)P(?:(\d+)W)?(?:(\d+)D)?(?:T(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?)?$/.exec(value.trim());
946
+ if (!m || !m[2] && !m[3] && !m[4] && !m[5] && !m[6]) return null;
947
+ const sign = m[1] === "-" ? -1 : 1;
948
+ const [w, d, h, mi, s] = [
949
+ m[2],
950
+ m[3],
951
+ m[4],
952
+ m[5],
953
+ m[6]
954
+ ].map((x) => Number(x ?? 0));
955
+ return sign * ((((w * 7 + d) * 24 + h) * 60 + mi) * 60 + s) * 1e3;
956
+ }
957
+ function parseRRule(value) {
958
+ const parts = /* @__PURE__ */ new Map();
959
+ for (const pair of value.split(";")) {
960
+ const [k, v] = pair.split("=");
961
+ if (k && v) parts.set(k.toUpperCase(), v);
962
+ }
963
+ const freq = parts.get("FREQ");
964
+ if (!freq || !RRULE_FREQ[freq]) return void 0;
965
+ const rule = { freq: RRULE_FREQ[freq] };
966
+ const interval = parts.get("INTERVAL");
967
+ if (interval) rule.interval = Number(interval);
968
+ const count = parts.get("COUNT");
969
+ if (count) rule.count = Number(count);
970
+ const until = parts.get("UNTIL");
971
+ if (until) rule.until = parseIcalDate(until, !until.includes("T"));
972
+ const byday = parts.get("BYDAY");
973
+ if (byday) {
974
+ const tokens = byday.split(",").map((t) => t.trim().toUpperCase());
975
+ const monthly = rule.freq === "monthly" || rule.freq === "yearly";
976
+ const ordinal = /^([+-]?\d+)(SU|MO|TU|WE|TH|FR|SA)$/;
977
+ const plain = [];
978
+ for (const token of tokens) {
979
+ const m = monthly ? ordinal.exec(token) : null;
980
+ if (m) {
981
+ const weekday = BYDAY.indexOf(m[2]);
982
+ if (weekday >= 0 && !rule.nthWeekday) rule.nthWeekday = {
983
+ week: Number(m[1]),
984
+ weekday
985
+ };
986
+ continue;
987
+ }
988
+ const index = BYDAY.indexOf(token);
989
+ if (index >= 0) plain.push(index);
990
+ }
991
+ if (plain.length) rule.weekdays = plain;
992
+ }
993
+ const bymonthday = parts.get("BYMONTHDAY");
994
+ if (bymonthday) {
995
+ const days = bymonthday.split(",").map((d) => Number(d.trim())).filter((d) => Number.isInteger(d) && d !== 0);
996
+ if (days.length) rule.monthDays = days;
997
+ }
998
+ const bymonth = parts.get("BYMONTH");
999
+ if (bymonth) {
1000
+ const months = bymonth.split(",").map((m) => Number(m.trim())).filter((m) => Number.isInteger(m) && m >= 1 && m <= 12);
1001
+ if (months.length) rule.months = months;
1002
+ }
1003
+ return rule;
1004
+ }
1005
+ function formatRRule(rule) {
1006
+ const parts = [`FREQ=${FREQ_RRULE[rule.freq]}`];
1007
+ if (rule.interval && rule.interval !== 1) parts.push(`INTERVAL=${rule.interval}`);
1008
+ if (rule.count != null) parts.push(`COUNT=${rule.count}`);
1009
+ if (rule.until) parts.push(`UNTIL=${formatUtc(rule.until)}`);
1010
+ if (rule.nthWeekday) parts.push(`BYDAY=${rule.nthWeekday.week}${BYDAY[rule.nthWeekday.weekday]}`);
1011
+ else if (rule.weekdays?.length) parts.push(`BYDAY=${rule.weekdays.map((d) => BYDAY[d]).join(",")}`);
1012
+ if (rule.monthDays?.length) parts.push(`BYMONTHDAY=${rule.monthDays.join(",")}`);
1013
+ if (rule.months?.length) parts.push(`BYMONTH=${rule.months.join(",")}`);
1014
+ return parts.join(";");
1015
+ }
1016
+ function parseLine(line) {
1017
+ const colon = line.indexOf(":");
1018
+ const head = colon === -1 ? line : line.slice(0, colon);
1019
+ const value = colon === -1 ? "" : line.slice(colon + 1);
1020
+ const [name, ...paramParts] = head.split(";");
1021
+ const params = /* @__PURE__ */ new Map();
1022
+ for (const p of paramParts) {
1023
+ const eq = p.indexOf("=");
1024
+ if (eq !== -1) params.set(p.slice(0, eq).toUpperCase(), p.slice(eq + 1));
1025
+ }
1026
+ return {
1027
+ name: name.toUpperCase(),
1028
+ params,
1029
+ value
1030
+ };
1031
+ }
1032
+ /**
1033
+ * Parse an iCalendar (`.ics`) string into events. Reads every `VEVENT`; ignores
1034
+ * VTODO/VJOURNAL/VTIMEZONE and unknown properties. Events without a usable
1035
+ * `DTSTART` are skipped. All-day events (`VALUE=DATE`) with no `DTEND` get a
1036
+ * one-day span.
1037
+ *
1038
+ * @example
1039
+ * ```ts
1040
+ * const events = parseICalendar(await file.text());
1041
+ * ```
1042
+ */
1043
+ function parseICalendar(ics) {
1044
+ const lines = unfoldLines(ics);
1045
+ const events = [];
1046
+ let current = null;
1047
+ let allDay = false;
1048
+ let durationMs = null;
1049
+ let exdates = [];
1050
+ let rdates = [];
1051
+ for (const raw of lines) {
1052
+ const line = parseLine(raw);
1053
+ if (line.name === "BEGIN" && line.value === "VEVENT") {
1054
+ current = {};
1055
+ allDay = false;
1056
+ durationMs = null;
1057
+ exdates = [];
1058
+ rdates = [];
1059
+ continue;
1060
+ }
1061
+ if (line.name === "END" && line.value === "VEVENT") {
1062
+ if (current?.start) {
1063
+ if (!current.end && durationMs != null) current.end = new Date(current.start.getTime() + durationMs);
1064
+ if (current.recurrence && exdates.length) current.recurrence.exdates = exdates;
1065
+ if (current.recurrence && rdates.length) current.recurrence.rdates = rdates;
1066
+ if (allDay) {
1067
+ current.allDay = true;
1068
+ if (!current.end) current.end = new Date(current.start.getTime() + 864e5);
1069
+ } else if (!current.end) current.end = current.start;
1070
+ events.push(current);
1071
+ }
1072
+ current = null;
1073
+ continue;
1074
+ }
1075
+ if (!current) continue;
1076
+ const dateOnly = line.params.get("VALUE") === "DATE";
1077
+ const tzid = line.params.get("TZID");
1078
+ switch (line.name) {
1079
+ case "SUMMARY":
1080
+ current.title = unescapeText(line.value);
1081
+ break;
1082
+ case "DESCRIPTION":
1083
+ current.description = unescapeText(line.value);
1084
+ break;
1085
+ case "LOCATION":
1086
+ current.location = unescapeText(line.value);
1087
+ break;
1088
+ case "UID":
1089
+ current.uid = line.value;
1090
+ break;
1091
+ case "DTSTART":
1092
+ current.start = parseIcalDate(line.value, dateOnly, tzid);
1093
+ if (dateOnly) allDay = true;
1094
+ break;
1095
+ case "DTEND":
1096
+ current.end = parseIcalDate(line.value, dateOnly, tzid);
1097
+ break;
1098
+ case "DURATION":
1099
+ durationMs = parseDuration(line.value);
1100
+ break;
1101
+ case "EXDATE":
1102
+ for (const v of line.value.split(",")) if (v) exdates.push(parseIcalDate(v, dateOnly || !v.includes("T"), tzid));
1103
+ break;
1104
+ case "RDATE":
1105
+ for (const v of line.value.split(",")) if (v) rdates.push(parseIcalDate(v, dateOnly || !v.includes("T"), tzid));
1106
+ break;
1107
+ case "RRULE": {
1108
+ const rule = parseRRule(line.value);
1109
+ if (rule) current.recurrence = rule;
1110
+ break;
1111
+ }
1112
+ }
1113
+ }
1114
+ return events;
1115
+ }
1116
+ function line(name, value) {
1117
+ return foldLine(`${name}:${value}`);
1118
+ }
1119
+ function stableUid(event) {
1120
+ if (event.uid) return event.uid;
1121
+ const title = (event.title ?? "event").replace(/\s+/g, "-");
1122
+ return `${formatUtc(event.start)}-${title}@super-calendar`;
1123
+ }
1124
+ /**
1125
+ * Serialize events to an iCalendar (`.ics`) string. Timed events are written in
1126
+ * UTC (`...Z`); all-day events (`allDay: true`) use `VALUE=DATE`. A `recurrence`
1127
+ * becomes an `RRULE`, and `uid` / `description` / `location` round-trip.
1128
+ *
1129
+ * @example
1130
+ * ```ts
1131
+ * const ics = toICalendar(events);
1132
+ * ```
1133
+ */
1134
+ function toICalendar(events, options = {}) {
1135
+ const stamp = formatUtc(options.now ?? /* @__PURE__ */ new Date());
1136
+ const out = [
1137
+ "BEGIN:VCALENDAR",
1138
+ "VERSION:2.0",
1139
+ line("PRODID", options.prodId ?? "-//super-calendar//EN"),
1140
+ "CALSCALE:GREGORIAN"
1141
+ ];
1142
+ for (const event of events) {
1143
+ out.push("BEGIN:VEVENT");
1144
+ out.push(line("UID", stableUid(event)));
1145
+ out.push(line("DTSTAMP", stamp));
1146
+ if (event.allDay) {
1147
+ out.push(line("DTSTART;VALUE=DATE", formatDateOnly(event.start)));
1148
+ out.push(line("DTEND;VALUE=DATE", formatDateOnly(event.end)));
1149
+ } else {
1150
+ out.push(line("DTSTART", formatUtc(event.start)));
1151
+ out.push(line("DTEND", formatUtc(event.end)));
1152
+ }
1153
+ if (event.title) out.push(line("SUMMARY", escapeText(event.title)));
1154
+ if (event.description) out.push(line("DESCRIPTION", escapeText(event.description)));
1155
+ if (event.location) out.push(line("LOCATION", escapeText(event.location)));
1156
+ if (event.recurrence) out.push(line("RRULE", formatRRule(event.recurrence)));
1157
+ if (event.recurrence?.exdates?.length) out.push(event.allDay ? line("EXDATE;VALUE=DATE", event.recurrence.exdates.map(formatDateOnly).join(",")) : line("EXDATE", event.recurrence.exdates.map(formatUtc).join(",")));
1158
+ if (event.recurrence?.rdates?.length) out.push(event.allDay ? line("RDATE;VALUE=DATE", event.recurrence.rdates.map(formatDateOnly).join(",")) : line("RDATE", event.recurrence.rdates.map(formatUtc).join(",")));
1159
+ out.push("END:VEVENT");
1160
+ }
1161
+ out.push("END:VCALENDAR");
1162
+ return out.join("\r\n");
1163
+ }
1164
+ // src/utils/eventSource.ts
1165
+ function dateFromJSON(value, field) {
1166
+ if (typeof value !== "string") throw new Error(`Event source ${field} must be a date string`);
1167
+ const date = new Date(value);
1168
+ if (!Number.isFinite(date.getTime())) throw new Error(`Event source ${field} is not a valid date`);
1169
+ return date;
1170
+ }
1171
+ function objectFromJSON(value, field) {
1172
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error(`Event source ${field} must be an object`);
1173
+ return value;
1174
+ }
1175
+ function arrayFromJSON(value, field) {
1176
+ if (!Array.isArray(value)) throw new Error(`Event source ${field} must be an array`);
1177
+ return value;
1178
+ }
1179
+ function integerFromJSON(value, field, min, max = Number.MAX_SAFE_INTEGER) {
1180
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value < min || value > max) throw new Error(`Event source ${field} must be an integer from ${min} to ${max}`);
1181
+ return value;
1182
+ }
1183
+ function weekdayFromJSON(value, field) {
1184
+ switch (value) {
1185
+ case 0:
1186
+ case 1:
1187
+ case 2:
1188
+ case 3:
1189
+ case 4:
1190
+ case 5:
1191
+ case 6: return value;
1192
+ default: throw new Error(`Event source ${field} must be a weekday from 0 to 6`);
1193
+ }
1194
+ }
1195
+ function recurrenceFromJSON(value, field) {
1196
+ const input = objectFromJSON(value, field);
1197
+ const { freq } = input;
1198
+ if (freq !== "daily" && freq !== "weekly" && freq !== "monthly" && freq !== "yearly") throw new Error(`Event source ${field}.freq must be daily, weekly, monthly, or yearly`);
1199
+ const rule = { freq };
1200
+ if (input.interval !== void 0) rule.interval = integerFromJSON(input.interval, `${field}.interval`, 1);
1201
+ if (input.count !== void 0) rule.count = integerFromJSON(input.count, `${field}.count`, 0);
1202
+ if (input.until !== void 0) rule.until = dateFromJSON(input.until, `${field}.until`);
1203
+ for (const key of ["exdates", "rdates"]) if (input[key] !== void 0) rule[key] = arrayFromJSON(input[key], `${field}.${key}`).map((date, index) => dateFromJSON(date, `${field}.${key}[${index}]`));
1204
+ if (input.weekdays !== void 0) rule.weekdays = arrayFromJSON(input.weekdays, `${field}.weekdays`).map((day) => weekdayFromJSON(day, `${field}.weekdays`));
1205
+ if (input.months !== void 0) rule.months = arrayFromJSON(input.months, `${field}.months`).map((month) => integerFromJSON(month, `${field}.months`, 1, 12));
1206
+ if (input.monthDays !== void 0) rule.monthDays = arrayFromJSON(input.monthDays, `${field}.monthDays`).map((day) => {
1207
+ const parsed = integerFromJSON(day, `${field}.monthDays`, -31, 31);
1208
+ if (parsed === 0) throw new Error(`Event source ${field}.monthDays cannot contain zero`);
1209
+ return parsed;
1210
+ });
1211
+ if (input.nthWeekday !== void 0) {
1212
+ const nth = objectFromJSON(input.nthWeekday, `${field}.nthWeekday`);
1213
+ rule.nthWeekday = {
1214
+ week: nth.week === -1 ? -1 : integerFromJSON(nth.week, `${field}.nthWeekday.week`, 1, 5),
1215
+ weekday: weekdayFromJSON(nth.weekday, `${field}.nthWeekday.weekday`)
1216
+ };
1217
+ }
1218
+ return rule;
1219
+ }
1220
+ const defaultMap = (items) => items.map((raw, index) => {
1221
+ const field = `item ${index}`;
1222
+ const item = objectFromJSON(raw, field);
1223
+ for (const key of ["title", "dragHandleColor"]) if (item[key] !== void 0 && typeof item[key] !== "string") throw new Error(`Event source ${field}.${key} must be a string`);
1224
+ for (const key of [
1225
+ "allDay",
1226
+ "disabled",
1227
+ "draggable",
1228
+ "startEditable",
1229
+ "durationEditable"
1230
+ ]) if (item[key] !== void 0 && typeof item[key] !== "boolean") throw new Error(`Event source ${field}.${key} must be a boolean`);
1231
+ if (item.display !== void 0 && item.display !== "auto" && item.display !== "background") throw new Error(`Event source ${field}.display must be auto or background`);
1232
+ return {
1233
+ ...item,
1234
+ start: dateFromJSON(item.start, `${field}.start`),
1235
+ end: dateFromJSON(item.end, `${field}.end`),
1236
+ ...item.recurrence === void 0 ? {} : { recurrence: recurrenceFromJSON(item.recurrence, `${field}.recurrence`) }
1237
+ };
1238
+ });
1239
+ /** Load one event batch. A caller can abort URL requests with signal. */
1240
+ async function loadEventSource({ source, format, map, signal }) {
1241
+ if (typeof source === "function") return await source();
1242
+ else {
1243
+ const response = await fetch(source, signal ? { signal } : void 0);
1244
+ if (!response.ok) throw new Error(`Event source responded ${response.status}`);
1245
+ if (format === "ics" || format == null && /\.ics(\?|$)/.test(source)) return parseICalendar(await response.text());
1246
+ else {
1247
+ const items = arrayFromJSON(await response.json(), "JSON");
1248
+ return map ? map(items) : defaultMap(items);
1249
+ }
1250
+ }
1251
+ }
1252
+ // src/utils/monthGrid.ts
1253
+ /** The last calendar day an event visibly covers (a midnight end ends the day before). */
1254
+ function lastCoveredDay(event) {
1255
+ const endMs = event.end.getTime();
1256
+ return startOfDay(new Date(Math.max(event.start.getTime(), endMs - 1))).getTime();
1257
+ }
1258
+ /**
1259
+ * Lay out one week row's events as continuous horizontal bars: each event becomes
1260
+ * a single segment spanning the columns it covers (not a chip repeated per day),
1261
+ * stacked into lanes so overlapping events sit on separate rows. Multi-day events
1262
+ * that cross the row edges are marked `continuesBefore`/`continuesAfter`. Shared by
1263
+ * both renderers so the month grid draws identical spanning bars.
1264
+ *
1265
+ * Column indices map into the given `days` array in whatever display order it uses,
1266
+ * so this is order-independent: a right-to-left (reversed) week lays out correctly,
1267
+ * and `continuesBefore`/`continuesAfter` track the array's first/last column edge
1268
+ * (not chronology), so the clipped end is squared on the right visual side.
1269
+ *
1270
+ * Lanes are packed greedily after sorting by start column then longest span first,
1271
+ * matching how calendars keep long events on the upper lanes.
1272
+ */
1273
+ function layoutMonthWeek(days, events) {
1274
+ if (days.length === 0) return {
1275
+ segments: [],
1276
+ laneCount: 0
1277
+ };
1278
+ const dayStarts = days.map((d) => startOfDay(d).getTime());
1279
+ const rowStart = Math.min(...dayStarts);
1280
+ const rowEnd = Math.max(...dayStarts);
1281
+ const ascending = dayStarts[0] <= dayStarts[dayStarts.length - 1];
1282
+ const placed = [];
1283
+ for (const event of events) {
1284
+ const evStart = startOfDay(event.start).getTime();
1285
+ const evLast = lastCoveredDay(event);
1286
+ if (evLast < rowStart || evStart > rowEnd) continue;
1287
+ let startCol = -1;
1288
+ let endCol = -1;
1289
+ for (let i = 0; i < dayStarts.length; i++) if (dayStarts[i] >= evStart && dayStarts[i] <= evLast) {
1290
+ if (startCol === -1) startCol = i;
1291
+ endCol = i;
1292
+ }
1293
+ if (startCol === -1) continue;
1294
+ const startsBefore = evStart < rowStart;
1295
+ const endsAfter = evLast > rowEnd;
1296
+ placed.push({
1297
+ event,
1298
+ startCol,
1299
+ endCol,
1300
+ lane: 0,
1301
+ continuesBefore: ascending ? startsBefore : endsAfter,
1302
+ continuesAfter: ascending ? endsAfter : startsBefore
1303
+ });
1304
+ }
1305
+ placed.sort((a, b) => a.startCol - b.startCol || b.endCol - b.startCol - (a.endCol - a.startCol));
1306
+ const laneEnds = [];
1307
+ for (const seg of placed) {
1308
+ let lane = laneEnds.findIndex((end) => end < seg.startCol);
1309
+ if (lane === -1) {
1310
+ lane = laneEnds.length;
1311
+ laneEnds.push(seg.endCol);
1312
+ } else laneEnds[lane] = seg.endCol;
1313
+ seg.lane = lane;
1314
+ }
1315
+ return {
1316
+ segments: placed,
1317
+ laneCount: laneEnds.length
1318
+ };
1319
+ }
1320
+ /** date-fns tokens for each {@link WeekdayFormat}. */
1321
+ const WEEKDAY_TOKENS = {
1322
+ narrow: "EEEEE",
1323
+ short: "EEE",
1324
+ long: "EEEE"
1325
+ };
1326
+ /**
1327
+ * The date-fns format token for a {@link WeekdayFormat}. Exposed so a renderer
1328
+ * that formats its own weekday header (rather than reading {@link buildMonthGrid})
1329
+ * keeps the same mapping.
1330
+ */
1331
+ function weekdayFormatToken(format) {
1332
+ return WEEKDAY_TOKENS[format];
1333
+ }
1334
+ /**
1335
+ * Pure month-grid builder: the weeks and weekday headers for `month`, each day
1336
+ * annotated with selection/disabled/today state. Use this when you need the
1337
+ * data outside React; inside a component prefer {@link useMonthGrid}.
1338
+ */
1339
+ function buildMonthGrid(month, options = {}) {
1340
+ const { weekStartsOn = 0, weekdayFormat = "short", showSixWeeks = false, isRTL = false, hiddenDays, selectedDates, selectedRange, minDate, maxDate, isDateDisabled, locale } = options;
1341
+ const rows = buildMonthWeeks(month, weekStartsOn, {
1342
+ showSixWeeks,
1343
+ isRTL,
1344
+ hiddenDays
1345
+ });
1346
+ const weeks = rows.map((days) => ({
1347
+ id: days[0].toISOString(),
1348
+ days: days.map((date) => ({
1349
+ date,
1350
+ id: format(date, "yyyy-MM-dd"),
1351
+ label: format(date, "d"),
1352
+ isCurrentMonth: isSameMonth(date, month),
1353
+ isToday: getIsToday(date),
1354
+ isWeekend: isWeekend(date),
1355
+ ...daySelectionState(date, {
1356
+ selectedDates,
1357
+ selectedRange
1358
+ }, {
1359
+ minDate,
1360
+ maxDate,
1361
+ isDateDisabled
1362
+ })
1363
+ }))
1364
+ }));
1365
+ if (rows.length === 0) return {
1366
+ weeks: [],
1367
+ weekdays: []
1368
+ };
1369
+ return {
1370
+ weeks,
1371
+ weekdays: rows[0].map((date) => ({
1372
+ date,
1373
+ label: format(date, WEEKDAY_TOKENS[weekdayFormat], { locale })
1374
+ }))
1375
+ };
1376
+ }
1377
+ // src/utils/multiWeekGrid.ts
1378
+ /**
1379
+ * Pure multi-week builder: `numberOfWeeks` consecutive full calendar weeks,
1380
+ * starting with the week that contains `date` (aligned back to `weekStartsOn`).
1381
+ * Each day carries the same selection, disabled, today, and weekend state as
1382
+ * {@link buildMonthGrid}. Hidden weekdays shrink the rows without changing the
1383
+ * period; `isRTL` reverses each row's display order.
1384
+ *
1385
+ * The result is fully materialized, so its size grows with `numberOfWeeks`.
1386
+ *
1387
+ * @throws RangeError when `date` is invalid, `numberOfWeeks` is not a positive
1388
+ * safe integer, or the last week falls outside the range `Date` can represent.
1389
+ */
1390
+ function buildMultiWeekGrid(date, options = {}) {
1391
+ const { numberOfWeeks = 2, weekStartsOn = 0, weekdayFormat = "short", isRTL = false, hiddenDays, selectedDates, selectedRange, minDate, maxDate, isDateDisabled, locale } = options;
1392
+ if (!(date instanceof Date) || Number.isNaN(date.getTime())) throw new RangeError("buildMultiWeekGrid: date must be a valid Date.");
1393
+ if (!Number.isSafeInteger(numberOfWeeks) || numberOfWeeks < 1) throw new RangeError(`buildMultiWeekGrid: numberOfWeeks must be a positive whole number, received ${String(numberOfWeeks)}.`);
1394
+ const start = startOfWeek(date, { weekStartsOn });
1395
+ const endExclusive = addDays(start, numberOfWeeks * 7);
1396
+ if (Number.isNaN(endExclusive.getTime())) throw new RangeError(`buildMultiWeekGrid: ${numberOfWeeks} weeks from ${format(start, "yyyy-MM-dd")} cannot be represented as a Date.`);
1397
+ const constraints = {
1398
+ minDate,
1399
+ maxDate,
1400
+ isDateDisabled
1401
+ };
1402
+ const selection = {
1403
+ selectedDates,
1404
+ selectedRange
1405
+ };
1406
+ let first = null;
1407
+ let last = null;
1408
+ const weeks = [];
1409
+ for (let row = 0; row < numberOfWeeks; row++) {
1410
+ const weekStart = addDays(start, row * 7);
1411
+ const all = Array.from({ length: 7 }, (_, index) => addDays(weekStart, index));
1412
+ const visible = filterHiddenDays(all, hiddenDays);
1413
+ if (visible.length > 0) {
1414
+ if (first === null) first = visible[0];
1415
+ last = visible[visible.length - 1];
1416
+ }
1417
+ const ordered = isRTL ? [...visible].reverse() : visible;
1418
+ weeks.push({
1419
+ id: format(weekStart, "yyyy-MM-dd"),
1420
+ days: ordered.map((day) => ({
1421
+ date: day,
1422
+ id: format(day, "yyyy-MM-dd"),
1423
+ label: format(day, "d"),
1424
+ isToday: getIsToday(day),
1425
+ isWeekend: isWeekend(day),
1426
+ ...daySelectionState(day, selection, constraints)
1427
+ }))
1428
+ });
1429
+ }
1430
+ const token = weekdayFormatToken(weekdayFormat);
1431
+ const weekdays = weeks[0].days.map((day) => ({
1432
+ date: day.date,
1433
+ label: format(day.date, token, { locale })
1434
+ }));
1435
+ return {
1436
+ period: {
1437
+ start,
1438
+ endExclusive
1439
+ },
1440
+ visibleRange: {
1441
+ start: first ?? start,
1442
+ endExclusive: last ? addDays(last, 1) : endExclusive
1443
+ },
1444
+ weeks,
1445
+ weekdays
1446
+ };
1447
+ }
1448
+ // src/utils/recurrence.ts
1449
+ const STEP = {
1450
+ daily: addDays,
1451
+ weekly: addWeeks,
1452
+ monthly: addMonths,
1453
+ yearly: addYears
1454
+ };
1455
+ const MAX_OCCURRENCES = 5e3;
1456
+ const APPROX_STEP_MS = {
1457
+ daily: 864e5,
1458
+ weekly: 6048e5,
1459
+ monthly: 2629746e3,
1460
+ yearly: 31556952e3
1461
+ };
1462
+ function withTimeOf(date, source) {
1463
+ const next = new Date(date);
1464
+ next.setHours(source.getHours(), source.getMinutes(), source.getSeconds(), source.getMilliseconds());
1465
+ return next;
1466
+ }
1467
+ function nthWeekdayOfMonth(year, month, week, weekday) {
1468
+ if (week === -1) {
1469
+ const lastDay = new Date(year, month + 1, 0);
1470
+ const back = (lastDay.getDay() - weekday + 7) % 7;
1471
+ return new Date(year, month, lastDay.getDate() - back);
1472
+ }
1473
+ const day = 1 + (weekday - new Date(year, month, 1).getDay() + 7) % 7 + (week - 1) * 7;
1474
+ const date = new Date(year, month, day);
1475
+ return date.getMonth() === month ? date : null;
1476
+ }
1477
+ function* occurrenceStarts(start, rule, earliestStart, rangeEnd) {
1478
+ const interval = Math.max(1, Math.trunc(rule.interval ?? 1));
1479
+ let produced = 0;
1480
+ let emitted = 0;
1481
+ const consider = (date) => {
1482
+ if (date.getTime() < start.getTime()) return "skip";
1483
+ if (!(date.getTime() <= rangeEnd.getTime())) return "stop";
1484
+ if (rule.until != null && date.getTime() > rule.until.getTime()) return "stop";
1485
+ if (rule.count != null && produced >= rule.count) return "stop";
1486
+ produced += 1;
1487
+ if (date.getTime() < earliestStart.getTime()) return "skip";
1488
+ if (emitted >= MAX_OCCURRENCES) return "stop";
1489
+ emitted += 1;
1490
+ return "emit";
1491
+ };
1492
+ if (rule.freq === "weekly" && rule.weekdays?.length) {
1493
+ const weekdays = [...new Set(rule.weekdays)].sort((a, b) => a - b);
1494
+ let weekStart = startOfWeek(start, { weekStartsOn: 0 });
1495
+ while (true) {
1496
+ for (const weekday of weekdays) {
1497
+ const date = withTimeOf(addDays(weekStart, weekday), start);
1498
+ const verdict = consider(date);
1499
+ if (verdict === "stop") return;
1500
+ if (verdict === "skip") continue;
1501
+ yield date;
1502
+ }
1503
+ const nextWeek = addWeeks(weekStart, interval);
1504
+ if (!(nextWeek.getTime() <= rangeEnd.getTime())) return;
1505
+ weekStart = nextWeek;
1506
+ }
1507
+ }
1508
+ if (rule.freq === "monthly" && rule.monthDays?.length) {
1509
+ let year = start.getFullYear();
1510
+ let month = start.getMonth();
1511
+ while (true) {
1512
+ const daysInMonth = new Date(year, month + 1, 0).getDate();
1513
+ const days = [...new Set(rule.monthDays.map((d) => d < 0 ? daysInMonth + d + 1 : d))].filter((d) => d >= 1 && d <= daysInMonth).sort((a, b) => a - b);
1514
+ for (const d of days) {
1515
+ const date = withTimeOf(new Date(year, month, d), start);
1516
+ const verdict = consider(date);
1517
+ if (verdict === "stop") return;
1518
+ if (verdict === "skip") continue;
1519
+ yield date;
1520
+ }
1521
+ month += interval;
1522
+ year += Math.floor(month / 12);
1523
+ month = (month % 12 + 12) % 12;
1524
+ if (!(new Date(year, month, 1).getTime() <= rangeEnd.getTime())) return;
1525
+ }
1526
+ }
1527
+ if ((rule.freq === "monthly" || rule.freq === "yearly") && rule.nthWeekday) {
1528
+ const { week, weekday } = rule.nthWeekday;
1529
+ const stepMonths = rule.freq === "monthly" ? interval : 12 * interval;
1530
+ let year = start.getFullYear();
1531
+ let month = start.getMonth();
1532
+ while (true) {
1533
+ const day = nthWeekdayOfMonth(year, month, week, weekday);
1534
+ if (day) {
1535
+ const date = withTimeOf(day, start);
1536
+ const verdict = consider(date);
1537
+ if (verdict === "stop") return;
1538
+ if (verdict === "emit") yield date;
1539
+ }
1540
+ month += stepMonths;
1541
+ year += Math.floor(month / 12);
1542
+ month = (month % 12 + 12) % 12;
1543
+ if (!(new Date(year, month, 1).getTime() <= rangeEnd.getTime())) return;
1544
+ }
1545
+ }
1546
+ if (rule.freq === "yearly" && rule.months?.length) {
1547
+ const day = start.getDate();
1548
+ const months = [...new Set(rule.months)].filter((m) => m >= 1 && m <= 12).sort((a, b) => a - b);
1549
+ let year = start.getFullYear();
1550
+ while (true) {
1551
+ for (const m of months) {
1552
+ const month = m - 1;
1553
+ if (day > new Date(year, month + 1, 0).getDate()) continue;
1554
+ const date = withTimeOf(new Date(year, month, day), start);
1555
+ const verdict = consider(date);
1556
+ if (verdict === "stop") return;
1557
+ if (verdict === "skip") continue;
1558
+ yield date;
1559
+ }
1560
+ year += interval;
1561
+ if (!(new Date(year, 0, 1).getTime() <= rangeEnd.getTime())) return;
1562
+ }
1563
+ }
1564
+ const occAt = (n) => STEP[rule.freq](start, n * interval);
1565
+ const lowerBound = earliestStart.getTime();
1566
+ let n = 0;
1567
+ if (occAt(0).getTime() < lowerBound) {
1568
+ n = Math.max(0, Math.floor((lowerBound - start.getTime()) / (APPROX_STEP_MS[rule.freq] * interval)));
1569
+ while (n > 0 && occAt(n - 1).getTime() >= lowerBound) n -= 1;
1570
+ while (occAt(n).getTime() < lowerBound) n += 1;
1571
+ }
1572
+ while (true) {
1573
+ if (rule.count != null && n >= rule.count) return;
1574
+ if (emitted >= MAX_OCCURRENCES) return;
1575
+ const date = occAt(n);
1576
+ if (!(date.getTime() <= rangeEnd.getTime())) return;
1577
+ if (rule.until != null && date.getTime() > rule.until.getTime()) return;
1578
+ emitted += 1;
1579
+ n += 1;
1580
+ yield date;
1581
+ }
1582
+ }
1583
+ function instanceAt(event, start, durationMs) {
1584
+ const instance = {
1585
+ ...event,
1586
+ start,
1587
+ end: new Date(start.getTime() + durationMs)
1588
+ };
1589
+ delete instance.recurrence;
1590
+ return instance;
1591
+ }
1592
+ /**
1593
+ * Materialise recurring events into concrete occurrences overlapping
1594
+ * `[rangeStart, rangeEnd]`. Non-recurring events pass through untouched, so the
1595
+ * result is ready to hand to `<Calendar events={...} />`. Each occurrence keeps
1596
+ * the original event's duration and fields (minus `recurrence`).
1597
+ */
1598
+ function expandRecurringEvents(events, rangeStart, rangeEnd) {
1599
+ const out = [];
1600
+ for (const event of events) {
1601
+ if (!event.recurrence) {
1602
+ out.push(event);
1603
+ continue;
1604
+ }
1605
+ const durationMs = event.end.getTime() - event.start.getTime();
1606
+ const dayKey = (d) => `${d.getFullYear()}-${d.getMonth()}-${d.getDate()}`;
1607
+ const excludedDays = /* @__PURE__ */ new Set();
1608
+ const excludedInstants = /* @__PURE__ */ new Set();
1609
+ for (const exdate of event.recurrence.exdates ?? []) if (exdate.getHours() === 0 && exdate.getMinutes() === 0 && exdate.getSeconds() === 0 && exdate.getMilliseconds() === 0) excludedDays.add(dayKey(exdate));
1610
+ else excludedInstants.add(exdate.getTime());
1611
+ const starts = /* @__PURE__ */ new Map();
1612
+ const earliestStart = new Date(rangeStart.getTime() - durationMs);
1613
+ for (const start of occurrenceStarts(event.start, event.recurrence, earliestStart, rangeEnd)) starts.set(start.getTime(), start);
1614
+ for (const rdate of event.recurrence.rdates ?? []) if (rdate.getTime() <= rangeEnd.getTime()) starts.set(rdate.getTime(), rdate);
1615
+ const ordered = [...starts.values()].sort((a, b) => a.getTime() - b.getTime());
1616
+ for (const start of ordered) {
1617
+ if (start.getTime() + durationMs < rangeStart.getTime()) continue;
1618
+ if (excludedDays.has(dayKey(start)) || excludedInstants.has(start.getTime())) continue;
1619
+ const instance = instanceAt(event, start, durationMs);
1620
+ if (Number.isFinite(instance.end.getTime())) out.push(instance);
1621
+ }
1622
+ }
1623
+ return out;
1624
+ }
1625
+ export { filterHiddenDays as $, movedClockSpan as A, drawnEnd as B, defaultCalendarLabels as C, eventsOverlap as D, clampMoveStartMinutes as E, snapDeltaMinutes as F, layoutDayEvents as G, groupEventsByDay as H, backgroundBandsForDay as I, isDateSelectable as J, wallClockHours as K, clockHoursBetween as L, pageStepDays as M, resolveDraggedBounds as N, monthCreateRange as O, shiftMinutes as P, buildMonthWeeks as Q, closedHourBands as R, dayAccessibilityLabel as S, cellRangeFromDrag as T, isAllDayEvent as U, eventDayKeys as V, isBackgroundEvent as W, isWithinDateRange as X, isRangeEndpoint as Y, nextDateRange as Z, isTimeVisibleAtHeight as _, weekdayFormatToken as a, isWeekend as at, titleEllipsizeMode as b, toICalendar as c, weekDaysCount as ct, zonedTimeToUtc as d, rangeBandKind as dt, getIsToday as et, MIN_BOX_HEIGHT_FOR_TIME as f, darkColors as ft, formatHour as g, eventTimeLabel as h, layoutMonthWeek as i, isSameCalendarDay as it, overlapsOtherEvents as j, monthDropBounds as k, eventsInTimeZone as l, bandRounding as lt, eventChipLayout as m, buildMultiWeekGrid as n, getWeekDays as nt, loadEventSource as o, minutesIntoDay as ot, eventAccessibilityLabel as p, lightColors as pt, daySelectionState as q, buildMonthGrid as r, getYearMonths as rt, parseICalendar as s, viewDayCount as st, expandRecurringEvents as t, getViewDays as tt, toZonedTime as u, dayBadgeKind as ut, monthEventCapacity as v, resolveCalendarLabels as w, titleNumberOfLines as x, monthVisibleCount as y, compareDayEvents as z };