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