@super-calendar/core 2.17.0 → 2.18.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/README.md +8 -0
- package/dist/index.d.mts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +13 -10
- package/dist/index.mjs +9 -11
- package/dist/{recurrence-CvIJfSMl.mjs → recurrence-15B6fu6K.mjs} +306 -101
- package/dist/{recurrence-D_oJ7A9D.js → recurrence-M-rJQgqd.js} +334 -99
- package/dist/{timezone-vbd68uRS.d.mts → timezone-BY2vQwRx.d.mts} +109 -13
- package/dist/{timezone-vbd68uRS.d.ts → timezone-BY2vQwRx.d.ts} +109 -13
- package/dist/vanilla.d.mts +2 -2
- package/dist/vanilla.d.ts +2 -2
- package/dist/vanilla.js +6 -1
- package/dist/vanilla.mjs +1 -1
- package/package.json +1 -1
- package/src/types.ts +7 -0
- package/src/utils/dates.ts +7 -2
- package/src/utils/drag.ts +14 -6
- package/src/utils/eventSource.ts +2 -0
- package/src/utils/ical.ts +5 -0
- package/src/utils/layout.ts +19 -5
- package/src/utils/monthGrid.ts +7 -1
- package/src/utils/multiWeekGrid.ts +2 -1
- package/src/utils/recurrence.ts +203 -77
- package/src/utils/timezone.ts +151 -48
- package/src/utils/useMonthGrid.ts +5 -0
- package/src/utils/useNow.ts +4 -9
- package/src/utils/zoneFields.ts +71 -0
package/src/utils/layout.ts
CHANGED
|
@@ -106,7 +106,14 @@ export function layoutDayEvents<T>(events: CalendarEvent<T>[], day: Date): Posit
|
|
|
106
106
|
// paint as bands (see `backgroundBandsForDay`), not boxes.
|
|
107
107
|
.filter((event) => !isAllDayEvent(event) && !isBackgroundEvent(event))
|
|
108
108
|
// Overlaps this day if it starts before the day ends and ends after it begins.
|
|
109
|
-
|
|
109
|
+
// A zero-length event occupies its own instant, so one at midnight belongs to
|
|
110
|
+
// the day it starts.
|
|
111
|
+
.filter(
|
|
112
|
+
(event) =>
|
|
113
|
+
event.start < nextDayStart &&
|
|
114
|
+
(event.end > dayStart ||
|
|
115
|
+
(event.end.getTime() === event.start.getTime() && event.start >= dayStart)),
|
|
116
|
+
)
|
|
110
117
|
.map((event) => {
|
|
111
118
|
const segStart = maxDate([event.start, dayStart]);
|
|
112
119
|
const segEnd = minDate([event.end, nextDayStart]);
|
|
@@ -123,6 +130,11 @@ export function layoutDayEvents<T>(events: CalendarEvent<T>[], day: Date): Posit
|
|
|
123
130
|
let cluster: Segment<T>[] = [];
|
|
124
131
|
let clusterEnd = Number.NEGATIVE_INFINITY;
|
|
125
132
|
|
|
133
|
+
// Columns are packed by each segment's minimum box (see `durationHours`), so
|
|
134
|
+
// two short events whose minimum boxes would overlap sit side by side even
|
|
135
|
+
// when their times don't.
|
|
136
|
+
const drawnEndOf = (seg: Segment<T>) => Math.max(seg.end, seg.start + MIN_DURATION_HOURS);
|
|
137
|
+
|
|
126
138
|
const flushCluster = () => {
|
|
127
139
|
const columnEnds: number[] = [];
|
|
128
140
|
const columnOf = new Map<Segment<T>, number>();
|
|
@@ -130,9 +142,9 @@ export function layoutDayEvents<T>(events: CalendarEvent<T>[], day: Date): Posit
|
|
|
130
142
|
let column = columnEnds.findIndex((end) => end <= seg.start);
|
|
131
143
|
if (column === -1) {
|
|
132
144
|
column = columnEnds.length;
|
|
133
|
-
columnEnds.push(seg
|
|
145
|
+
columnEnds.push(drawnEndOf(seg));
|
|
134
146
|
} else {
|
|
135
|
-
columnEnds[column] = seg
|
|
147
|
+
columnEnds[column] = drawnEndOf(seg);
|
|
136
148
|
}
|
|
137
149
|
columnOf.set(seg, column);
|
|
138
150
|
}
|
|
@@ -153,7 +165,7 @@ export function layoutDayEvents<T>(events: CalendarEvent<T>[], day: Date): Posit
|
|
|
153
165
|
for (const seg of segments) {
|
|
154
166
|
if (cluster.length > 0 && seg.start >= clusterEnd) flushCluster();
|
|
155
167
|
cluster.push(seg);
|
|
156
|
-
clusterEnd = Math.max(clusterEnd, seg
|
|
168
|
+
clusterEnd = Math.max(clusterEnd, drawnEndOf(seg));
|
|
157
169
|
}
|
|
158
170
|
if (cluster.length > 0) flushCluster();
|
|
159
171
|
|
|
@@ -189,7 +201,9 @@ export function eventDayKeys<T>(event: CalendarEvent<T>): string[] {
|
|
|
189
201
|
const last = startOfDay(lastInstant);
|
|
190
202
|
|
|
191
203
|
const keys: string[] = [];
|
|
192
|
-
|
|
204
|
+
// Midnight can normalize to 01:00 on a clock change. Reset each subsequent
|
|
205
|
+
// day so its index still matches startOfDay(date).
|
|
206
|
+
for (let cursor = first; cursor <= last; cursor = startOfDay(addDays(cursor, 1))) {
|
|
193
207
|
keys.push(cursor.toISOString());
|
|
194
208
|
}
|
|
195
209
|
return keys;
|
package/src/utils/monthGrid.ts
CHANGED
|
@@ -202,6 +202,11 @@ export interface UseMonthGridOptions extends DateSelectionConstraints {
|
|
|
202
202
|
selectedRange?: DateRange;
|
|
203
203
|
/** A date-fns locale for the weekday labels. */
|
|
204
204
|
locale?: Locale;
|
|
205
|
+
/**
|
|
206
|
+
* The calendar day flagged `isToday`. Defaults to the device's current day;
|
|
207
|
+
* pass `nowInTimeZone(now, timeZone)` for a grid shown in another time zone.
|
|
208
|
+
*/
|
|
209
|
+
today?: Date;
|
|
205
210
|
}
|
|
206
211
|
|
|
207
212
|
/**
|
|
@@ -222,6 +227,7 @@ export function buildMonthGrid(month: Date, options: UseMonthGridOptions = {}):
|
|
|
222
227
|
maxDate,
|
|
223
228
|
isDateDisabled,
|
|
224
229
|
locale,
|
|
230
|
+
today,
|
|
225
231
|
} = options;
|
|
226
232
|
|
|
227
233
|
const rows = buildMonthWeeks(month, weekStartsOn, { showSixWeeks, isRTL, hiddenDays });
|
|
@@ -233,7 +239,7 @@ export function buildMonthGrid(month: Date, options: UseMonthGridOptions = {}):
|
|
|
233
239
|
id: format(date, "yyyy-MM-dd"),
|
|
234
240
|
label: format(date, "d"),
|
|
235
241
|
isCurrentMonth: isSameMonth(date, month),
|
|
236
|
-
isToday: getIsToday(date),
|
|
242
|
+
isToday: getIsToday(date, today),
|
|
237
243
|
isWeekend: isWeekend(date),
|
|
238
244
|
// Shared with MonthView, so the headless grid matches the built-in view.
|
|
239
245
|
...daySelectionState(
|
|
@@ -76,6 +76,7 @@ export function buildMultiWeekGrid(date: Date, options: MultiWeekGridOptions = {
|
|
|
76
76
|
maxDate,
|
|
77
77
|
isDateDisabled,
|
|
78
78
|
locale,
|
|
79
|
+
today,
|
|
79
80
|
} = options;
|
|
80
81
|
|
|
81
82
|
if (!(date instanceof Date) || Number.isNaN(date.getTime())) {
|
|
@@ -114,7 +115,7 @@ export function buildMultiWeekGrid(date: Date, options: MultiWeekGridOptions = {
|
|
|
114
115
|
date: day,
|
|
115
116
|
id: format(day, "yyyy-MM-dd"),
|
|
116
117
|
label: format(day, "d"),
|
|
117
|
-
isToday: getIsToday(day),
|
|
118
|
+
isToday: getIsToday(day, today),
|
|
118
119
|
isWeekend: isWeekend(day),
|
|
119
120
|
...daySelectionState(day, selection, constraints),
|
|
120
121
|
})),
|
package/src/utils/recurrence.ts
CHANGED
|
@@ -1,12 +1,7 @@
|
|
|
1
|
-
import { addDays, addMonths, addWeeks, addYears, startOfWeek } from "date-fns";
|
|
2
1
|
import type { CalendarEvent, RecurrenceFrequency, RecurrenceRule } from "../types";
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
weekly: addWeeks,
|
|
7
|
-
monthly: addMonths,
|
|
8
|
-
yearly: addYears,
|
|
9
|
-
};
|
|
2
|
+
import { isAllDayEvent } from "./layout";
|
|
3
|
+
import { toZonedTime, zonedTimeToUtc } from "./timezone";
|
|
4
|
+
import { utcTime, zoneFields } from "./zoneFields";
|
|
10
5
|
|
|
11
6
|
// Runaway guard on in-range occurrences. Generous enough for realistic windows
|
|
12
7
|
// (e.g. ~13 years of a daily event); set `count`/`until`, or query a tighter
|
|
@@ -22,35 +17,91 @@ const APPROX_STEP_MS: Record<RecurrenceFrequency, number> = {
|
|
|
22
17
|
yearly: 31556952e3,
|
|
23
18
|
};
|
|
24
19
|
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
20
|
+
const DAY_MS = 864e5;
|
|
21
|
+
// The largest time value a `Date` can hold.
|
|
22
|
+
const MAX_DATE_MS = 8.64e15;
|
|
23
|
+
|
|
24
|
+
const WEEKDAYS: ReadonlySet<number> = new Set([0, 1, 2, 3, 4, 5, 6]);
|
|
25
|
+
|
|
26
|
+
// The wall clock a rule repeats on. A rule keeps its event's clock time from one
|
|
27
|
+
// occurrence to the next, so the occurrences depend on whose clock that is: the
|
|
28
|
+
// device's, or a named zone's with its own DST changes.
|
|
29
|
+
interface Clock {
|
|
30
|
+
/** The year, month (0 = January), day, hour, minute, second and ms `instant` reads. */
|
|
31
|
+
fields(instant: Date): [number, number, number, number, number, number, number];
|
|
32
|
+
/**
|
|
33
|
+
* The instant a reading names. Fields may overflow (day 32, month 13) and roll
|
|
34
|
+
* over as in the `Date` constructor.
|
|
35
|
+
*/
|
|
36
|
+
at(
|
|
37
|
+
year: number,
|
|
38
|
+
month: number,
|
|
39
|
+
day: number,
|
|
40
|
+
hour: number,
|
|
41
|
+
minute: number,
|
|
42
|
+
second: number,
|
|
43
|
+
ms: number,
|
|
44
|
+
): Date;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
const DEVICE_CLOCK: Clock = {
|
|
48
|
+
fields: (instant) => [
|
|
49
|
+
instant.getFullYear(),
|
|
50
|
+
instant.getMonth(),
|
|
51
|
+
instant.getDate(),
|
|
52
|
+
instant.getHours(),
|
|
53
|
+
instant.getMinutes(),
|
|
54
|
+
instant.getSeconds(),
|
|
55
|
+
instant.getMilliseconds(),
|
|
56
|
+
],
|
|
57
|
+
at(year, month, day, hour, minute, second, ms) {
|
|
58
|
+
// Setters, not the constructor, which reads a year below 100 as 19xx.
|
|
59
|
+
const date = new Date(2000, 0, 1);
|
|
60
|
+
date.setFullYear(year, month, day);
|
|
61
|
+
date.setHours(hour, minute, second, ms);
|
|
62
|
+
return date;
|
|
63
|
+
},
|
|
64
|
+
};
|
|
65
|
+
|
|
66
|
+
// `timeZone`'s clock. A reading equal to `start`'s returns `start` itself, so a
|
|
67
|
+
// first occurrence in the hour a fall-back change repeats keeps its instant.
|
|
68
|
+
function zoneClock(timeZone: string, start: Date): Clock {
|
|
69
|
+
const fields: Clock["fields"] = (instant) => [
|
|
70
|
+
...zoneFields(instant, timeZone),
|
|
71
|
+
instant.getUTCMilliseconds(),
|
|
72
|
+
];
|
|
73
|
+
const origin = fields(start);
|
|
74
|
+
return {
|
|
75
|
+
fields,
|
|
76
|
+
at(...reading) {
|
|
77
|
+
if (reading.every((value, index) => value === origin[index])) return new Date(start);
|
|
78
|
+
const wallClock = utcTime(...reading);
|
|
79
|
+
// Resolving a reading needs a day's room either side of it.
|
|
80
|
+
if (!(Math.abs(wallClock) <= MAX_DATE_MS - DAY_MS)) return new Date(Number.NaN);
|
|
81
|
+
return zonedTimeToUtc(new Date(wallClock), timeZone);
|
|
82
|
+
},
|
|
83
|
+
};
|
|
35
84
|
}
|
|
36
85
|
|
|
37
|
-
//
|
|
38
|
-
|
|
86
|
+
// Calendar arithmetic on plain fields, the same on every clock.
|
|
87
|
+
const weekdayOf = (year: number, month: number, day: number): number =>
|
|
88
|
+
new Date(utcTime(year, month, day)).getUTCDay();
|
|
89
|
+
const daysInMonth = (year: number, month: number): number =>
|
|
90
|
+
new Date(utcTime(year, month + 1, 0)).getUTCDate();
|
|
91
|
+
|
|
92
|
+
// The day of the month of the `week`th `weekday` in a given month (`week` 1–5, or
|
|
93
|
+
// -1 for the last). Returns null when that week doesn't exist (e.g. a 5th Monday
|
|
94
|
+
// it lacks).
|
|
39
95
|
function nthWeekdayOfMonth(
|
|
40
96
|
year: number,
|
|
41
97
|
month: number,
|
|
42
98
|
week: number,
|
|
43
99
|
weekday: number,
|
|
44
|
-
):
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
}
|
|
50
|
-
const firstWeekday = new Date(year, month, 1).getDay();
|
|
51
|
-
const day = 1 + ((weekday - firstWeekday + 7) % 7) + (week - 1) * 7;
|
|
52
|
-
const date = new Date(year, month, day);
|
|
53
|
-
return date.getMonth() === month ? date : null;
|
|
100
|
+
): number | null {
|
|
101
|
+
const lastDay = daysInMonth(year, month);
|
|
102
|
+
if (week === -1) return lastDay - ((weekdayOf(year, month, lastDay) - weekday + 7) % 7);
|
|
103
|
+
const day = 1 + ((weekday - weekdayOf(year, month, 1) + 7) % 7) + (week - 1) * 7;
|
|
104
|
+
return day <= lastDay ? day : null;
|
|
54
105
|
}
|
|
55
106
|
|
|
56
107
|
// Occurrence start dates from `event.start` forward, in chronological order, up
|
|
@@ -62,8 +113,15 @@ function* occurrenceStarts(
|
|
|
62
113
|
rule: RecurrenceRule,
|
|
63
114
|
earliestStart: Date,
|
|
64
115
|
rangeEnd: Date,
|
|
116
|
+
clock: Clock,
|
|
65
117
|
): Generator<Date> {
|
|
66
118
|
const interval = Math.max(1, Math.trunc(rule.interval ?? 1));
|
|
119
|
+
const [startYear, startMonth, startDay, hour, minute, second, ms] = clock.fields(start);
|
|
120
|
+
// The start's time of day on a calendar day, and that day's midnight.
|
|
121
|
+
const onDay = (year: number, month: number, day: number) =>
|
|
122
|
+
clock.at(year, month, day, hour, minute, second, ms);
|
|
123
|
+
const dayStart = (year: number, month: number, day: number) =>
|
|
124
|
+
clock.at(year, month, day, 0, 0, 0, 0);
|
|
67
125
|
// `produced` counts occurrences from the origin, honouring `count`; `emitted`
|
|
68
126
|
// counts only in-window yields, so the runaway guard isn't spent on the
|
|
69
127
|
// throwaway occurrences that precede a far-future query window.
|
|
@@ -83,34 +141,41 @@ function* occurrenceStarts(
|
|
|
83
141
|
};
|
|
84
142
|
|
|
85
143
|
if (rule.freq === "weekly" && rule.weekdays?.length) {
|
|
86
|
-
|
|
87
|
-
|
|
144
|
+
// The week start decides which days share a week, so it changes the result
|
|
145
|
+
// only when `interval` skips weeks. RFC 5545 defaults WKST to Monday.
|
|
146
|
+
const weekStartsOn = WEEKDAYS.has(rule.weekStartsOn as number) ? rule.weekStartsOn! : 1;
|
|
147
|
+
const offsets = [...new Set(rule.weekdays.map((day) => (day - weekStartsOn + 7) % 7))].sort(
|
|
148
|
+
(a, b) => a - b,
|
|
149
|
+
);
|
|
150
|
+
// The week's first day, as a day of the start's month (zero or negative when
|
|
151
|
+
// the week began in the month before).
|
|
152
|
+
let weekStart =
|
|
153
|
+
startDay - ((weekdayOf(startYear, startMonth, startDay) - weekStartsOn + 7) % 7);
|
|
88
154
|
while (true) {
|
|
89
|
-
for (const
|
|
90
|
-
const date =
|
|
155
|
+
for (const offset of offsets) {
|
|
156
|
+
const date = onDay(startYear, startMonth, weekStart + offset);
|
|
91
157
|
const verdict = consider(date);
|
|
92
158
|
if (verdict === "stop") return;
|
|
93
159
|
if (verdict === "skip") continue;
|
|
94
160
|
yield date;
|
|
95
161
|
}
|
|
96
|
-
|
|
97
|
-
if (!(
|
|
98
|
-
weekStart = nextWeek;
|
|
162
|
+
weekStart += 7 * interval;
|
|
163
|
+
if (!(dayStart(startYear, startMonth, weekStart).getTime() <= rangeEnd.getTime())) return;
|
|
99
164
|
}
|
|
100
165
|
}
|
|
101
166
|
|
|
102
167
|
if (rule.freq === "monthly" && rule.monthDays?.length) {
|
|
103
|
-
let year =
|
|
104
|
-
let month =
|
|
168
|
+
let year = startYear;
|
|
169
|
+
let month = startMonth;
|
|
105
170
|
while (true) {
|
|
106
|
-
const
|
|
171
|
+
const lastDay = daysInMonth(year, month);
|
|
107
172
|
// Resolve each configured day to a concrete date-of-month (negatives count
|
|
108
173
|
// from the end), drop days this month lacks, and emit in chronological order.
|
|
109
|
-
const days = [...new Set(rule.monthDays.map((d) => (d < 0 ?
|
|
110
|
-
.filter((d) => d >= 1 && d <=
|
|
174
|
+
const days = [...new Set(rule.monthDays.map((d) => (d < 0 ? lastDay + d + 1 : d)))]
|
|
175
|
+
.filter((d) => d >= 1 && d <= lastDay)
|
|
111
176
|
.sort((a, b) => a - b);
|
|
112
177
|
for (const d of days) {
|
|
113
|
-
const date =
|
|
178
|
+
const date = onDay(year, month, d);
|
|
114
179
|
const verdict = consider(date);
|
|
115
180
|
if (verdict === "stop") return;
|
|
116
181
|
if (verdict === "skip") continue;
|
|
@@ -120,19 +185,19 @@ function* occurrenceStarts(
|
|
|
120
185
|
year += Math.floor(month / 12);
|
|
121
186
|
month = ((month % 12) + 12) % 12;
|
|
122
187
|
// No occurrence yielded yet but we've run past the range: stop.
|
|
123
|
-
if (!(
|
|
188
|
+
if (!(dayStart(year, month, 1).getTime() <= rangeEnd.getTime())) return;
|
|
124
189
|
}
|
|
125
190
|
}
|
|
126
191
|
|
|
127
192
|
if ((rule.freq === "monthly" || rule.freq === "yearly") && rule.nthWeekday) {
|
|
128
193
|
const { week, weekday } = rule.nthWeekday;
|
|
129
194
|
const stepMonths = rule.freq === "monthly" ? interval : 12 * interval;
|
|
130
|
-
let year =
|
|
131
|
-
let month =
|
|
195
|
+
let year = startYear;
|
|
196
|
+
let month = startMonth;
|
|
132
197
|
while (true) {
|
|
133
198
|
const day = nthWeekdayOfMonth(year, month, week, weekday);
|
|
134
|
-
if (day) {
|
|
135
|
-
const date =
|
|
199
|
+
if (day !== null) {
|
|
200
|
+
const date = onDay(year, month, day);
|
|
136
201
|
const verdict = consider(date);
|
|
137
202
|
if (verdict === "stop") return;
|
|
138
203
|
if (verdict === "emit") yield date;
|
|
@@ -141,34 +206,41 @@ function* occurrenceStarts(
|
|
|
141
206
|
year += Math.floor(month / 12);
|
|
142
207
|
month = ((month % 12) + 12) % 12;
|
|
143
208
|
// No occurrence yielded yet but we've run past the range: stop.
|
|
144
|
-
if (!(
|
|
209
|
+
if (!(dayStart(year, month, 1).getTime() <= rangeEnd.getTime())) return;
|
|
145
210
|
}
|
|
146
211
|
}
|
|
147
212
|
|
|
148
213
|
if (rule.freq === "yearly" && rule.months?.length) {
|
|
149
|
-
const day = start.getDate();
|
|
150
214
|
const months = [...new Set(rule.months)].filter((m) => m >= 1 && m <= 12).sort((a, b) => a - b);
|
|
151
|
-
let year =
|
|
215
|
+
let year = startYear;
|
|
152
216
|
while (true) {
|
|
153
217
|
for (const m of months) {
|
|
154
218
|
const month = m - 1;
|
|
155
219
|
// Skip a year whose listed month lacks the start's day (e.g. Feb 29).
|
|
156
|
-
if (
|
|
157
|
-
const date =
|
|
220
|
+
if (startDay > daysInMonth(year, month)) continue;
|
|
221
|
+
const date = onDay(year, month, startDay);
|
|
158
222
|
const verdict = consider(date);
|
|
159
223
|
if (verdict === "stop") return;
|
|
160
224
|
if (verdict === "skip") continue;
|
|
161
225
|
yield date;
|
|
162
226
|
}
|
|
163
227
|
year += interval;
|
|
164
|
-
if (!(
|
|
228
|
+
if (!(dayStart(year, 0, 1).getTime() <= rangeEnd.getTime())) return;
|
|
165
229
|
}
|
|
166
230
|
}
|
|
167
231
|
|
|
168
232
|
// Fallback: plain daily/weekly/monthly/yearly stepping. Each occurrence is
|
|
169
233
|
// computed from the original `start` (never the previous occurrence), so a
|
|
170
|
-
// month-end or Feb-29 start doesn't drift
|
|
171
|
-
|
|
234
|
+
// month-end or Feb-29 start doesn't drift: a shorter month clamps to its last
|
|
235
|
+
// day, and the next longer one returns to the start's day.
|
|
236
|
+
const occAt = (n: number): Date => {
|
|
237
|
+
if (n === 0) return new Date(start.getTime());
|
|
238
|
+
const steps = n * interval;
|
|
239
|
+
if (rule.freq === "daily") return onDay(startYear, startMonth, startDay + steps);
|
|
240
|
+
if (rule.freq === "weekly") return onDay(startYear, startMonth, startDay + 7 * steps);
|
|
241
|
+
const month = startMonth + (rule.freq === "monthly" ? steps : 12 * steps);
|
|
242
|
+
return onDay(startYear, month, Math.min(startDay, daysInMonth(startYear, month)));
|
|
243
|
+
};
|
|
172
244
|
const lowerBound = earliestStart.getTime();
|
|
173
245
|
// Fast-forward to the first occurrence that can overlap the window so a
|
|
174
246
|
// far-future query doesn't iterate (and exhaust the guard) from `start`.
|
|
@@ -201,16 +273,44 @@ function instanceAt<T>(event: CalendarEvent<T>, start: Date, durationMs: number)
|
|
|
201
273
|
return instance;
|
|
202
274
|
}
|
|
203
275
|
|
|
276
|
+
// `date` on `timeZone`'s wall clock; an invalid date stays invalid, where `Intl`
|
|
277
|
+
// would throw.
|
|
278
|
+
const zonedOrInvalid = (date: Date, timeZone: string): Date =>
|
|
279
|
+
Number.isNaN(date.getTime()) ? date : toZonedTime(date, timeZone);
|
|
280
|
+
|
|
281
|
+
// A reading of exactly midnight.
|
|
282
|
+
const isMidnight = (fields: readonly number[]): boolean =>
|
|
283
|
+
fields[3] === 0 && fields[4] === 0 && fields[5] === 0 && fields[6] === 0;
|
|
284
|
+
|
|
285
|
+
/** Options for {@link expandRecurringEvents}. */
|
|
286
|
+
export interface ExpandRecurringEventsOptions {
|
|
287
|
+
/**
|
|
288
|
+
* The IANA time zone whose wall clock the rules repeat on (e.g.
|
|
289
|
+
* `"America/New_York"`). A timed event keeps its clock time in that zone across
|
|
290
|
+
* the zone's DST changes, and its weekday, month-day and exception rules read
|
|
291
|
+
* that zone's calendar. An exception that reads the event's own time of day
|
|
292
|
+
* there (or equals one of the `rdates`) drops the occurrence at that instant;
|
|
293
|
+
* any other exception at midnight, on the device or in the zone, drops its
|
|
294
|
+
* whole day. Omit it to repeat on the device's clock. All-day events
|
|
295
|
+
* name calendar days, so they always repeat on the device's calendar.
|
|
296
|
+
*/
|
|
297
|
+
timeZone?: string;
|
|
298
|
+
}
|
|
299
|
+
|
|
204
300
|
/**
|
|
205
301
|
* Materialise recurring events into concrete occurrences overlapping
|
|
206
302
|
* `[rangeStart, rangeEnd]`. Non-recurring events pass through untouched, so the
|
|
207
303
|
* result is ready to hand to `<Calendar events={...} />`. Each occurrence keeps
|
|
208
304
|
* the original event's duration and fields (minus `recurrence`).
|
|
305
|
+
*
|
|
306
|
+
* Pass `timeZone` to repeat timed events on that zone's wall clock instead of
|
|
307
|
+
* the device's. `rangeStart` and `rangeEnd` are real instants either way.
|
|
209
308
|
*/
|
|
210
309
|
export function expandRecurringEvents<T>(
|
|
211
310
|
events: CalendarEvent<T>[],
|
|
212
311
|
rangeStart: Date,
|
|
213
312
|
rangeEnd: Date,
|
|
313
|
+
{ timeZone }: ExpandRecurringEventsOptions = {},
|
|
214
314
|
): CalendarEvent<T>[] {
|
|
215
315
|
const out: CalendarEvent<T>[] = [];
|
|
216
316
|
for (const event of events) {
|
|
@@ -219,38 +319,64 @@ export function expandRecurringEvents<T>(
|
|
|
219
319
|
continue;
|
|
220
320
|
}
|
|
221
321
|
const durationMs = event.end.getTime() - event.start.getTime();
|
|
222
|
-
//
|
|
223
|
-
//
|
|
224
|
-
//
|
|
225
|
-
//
|
|
226
|
-
|
|
227
|
-
const
|
|
228
|
-
const
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
exdate.getSeconds() === 0 &&
|
|
234
|
-
exdate.getMilliseconds() === 0;
|
|
235
|
-
if (isMidnight) excludedDays.add(dayKey(exdate));
|
|
236
|
-
else excludedInstants.add(exdate.getTime());
|
|
237
|
-
}
|
|
322
|
+
// An all-day event names calendar days, which a display zone doesn't shift
|
|
323
|
+
// (see `eventsInTimeZone`), so it repeats on the device's calendar and the
|
|
324
|
+
// window is read as the zone's days.
|
|
325
|
+
// An invalid start has no reading on a zone's clock; the device clock turns
|
|
326
|
+
// it into no occurrences.
|
|
327
|
+
const zoned = timeZone != null && !isAllDayEvent(event) && !Number.isNaN(event.start.getTime());
|
|
328
|
+
const clock = zoned ? zoneClock(timeZone, event.start) : DEVICE_CLOCK;
|
|
329
|
+
const [from, to] =
|
|
330
|
+
timeZone != null && isAllDayEvent(event)
|
|
331
|
+
? [zonedOrInvalid(rangeStart, timeZone), zonedOrInvalid(rangeEnd, timeZone)]
|
|
332
|
+
: [rangeStart, rangeEnd];
|
|
238
333
|
// Union the rule's occurrences with any explicit RDATE additions, keyed by
|
|
239
334
|
// exact start time so a date the rule already produces isn't duplicated.
|
|
240
335
|
const starts = new Map<number, Date>();
|
|
241
336
|
// Occurrences starting up to one duration before the range can still overlap it.
|
|
242
|
-
const earliestStart = new Date(
|
|
243
|
-
for (const start of occurrenceStarts(event.start, event.recurrence, earliestStart,
|
|
337
|
+
const earliestStart = new Date(from.getTime() - durationMs);
|
|
338
|
+
for (const start of occurrenceStarts(event.start, event.recurrence, earliestStart, to, clock)) {
|
|
244
339
|
starts.set(start.getTime(), start);
|
|
245
340
|
}
|
|
246
341
|
for (const rdate of event.recurrence.rdates ?? []) {
|
|
247
|
-
if (rdate.getTime() <=
|
|
342
|
+
if (rdate.getTime() <= to.getTime()) starts.set(rdate.getTime(), rdate);
|
|
343
|
+
}
|
|
344
|
+
// Exceptions (EXDATE): a date-only exception (local midnight) drops every
|
|
345
|
+
// occurrence on that calendar day (RFC 5545 VALUE=DATE); a timed exception
|
|
346
|
+
// drops only the occurrence starting at that exact instant, so two
|
|
347
|
+
// same-day occurrences can be cancelled independently.
|
|
348
|
+
const dayKey = (fields: readonly number[]) => `${fields[0]}-${fields[1]}-${fields[2]}`;
|
|
349
|
+
const excludedDays = new Set<string>();
|
|
350
|
+
const excludedInstants = new Set<number>();
|
|
351
|
+
const startFields = clock.fields(event.start);
|
|
352
|
+
const rdateTimes = new Set((event.recurrence.rdates ?? []).map((rdate) => rdate.getTime()));
|
|
353
|
+
for (const exdate of event.recurrence.exdates ?? []) {
|
|
354
|
+
if (Number.isNaN(exdate.getTime())) continue;
|
|
355
|
+
const onDevice = DEVICE_CLOCK.fields(exdate);
|
|
356
|
+
if (!zoned) {
|
|
357
|
+
if (isMidnight(onDevice)) excludedDays.add(dayKey(onDevice));
|
|
358
|
+
else excludedInstants.add(exdate.getTime());
|
|
359
|
+
continue;
|
|
360
|
+
}
|
|
361
|
+
// On a zone's clock, device midnight is an arbitrary time of day, so an
|
|
362
|
+
// exception that can be an occurrence's own start (it reads the start's
|
|
363
|
+
// time of day in the zone, or is one of the `rdates`) is that occurrence's.
|
|
364
|
+
// Any other date at midnight, on the device (a parsed `VALUE=DATE`) or in
|
|
365
|
+
// the zone, names the calendar day it reads there. Decided from the dates
|
|
366
|
+
// alone, so the answer doesn't change with the query window.
|
|
367
|
+
const inZone = clock.fields(exdate);
|
|
368
|
+
excludedInstants.add(exdate.getTime());
|
|
369
|
+
if (rdateTimes.has(exdate.getTime())) continue;
|
|
370
|
+
if ([3, 4, 5, 6].every((index) => inZone[index] === startFields[index])) continue;
|
|
371
|
+
if (isMidnight(onDevice)) excludedDays.add(dayKey(onDevice));
|
|
372
|
+
else if (isMidnight(inZone)) excludedDays.add(dayKey(inZone));
|
|
248
373
|
}
|
|
249
374
|
const ordered = [...starts.values()].sort((a, b) => a.getTime() - b.getTime());
|
|
250
375
|
for (const start of ordered) {
|
|
251
376
|
// Skip occurrences that end before the range opens, but keep iterating.
|
|
252
|
-
if (start.getTime() + durationMs <
|
|
253
|
-
if (
|
|
377
|
+
if (start.getTime() + durationMs < from.getTime()) continue;
|
|
378
|
+
if (excludedInstants.has(start.getTime())) continue;
|
|
379
|
+
if (excludedDays.size > 0 && excludedDays.has(dayKey(clock.fields(start)))) continue;
|
|
254
380
|
const instance = instanceAt(event, start, durationMs);
|
|
255
381
|
if (Number.isFinite(instance.end.getTime())) out.push(instance);
|
|
256
382
|
}
|