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