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