@super-calendar/core 2.17.0 → 2.19.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.
@@ -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
- const STEP: Record<RecurrenceFrequency, (date: Date, amount: number) => Date> = {
5
- daily: addDays,
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
- // Copy `source`'s time of day onto `date`.
26
- function withTimeOf(date: Date, source: Date): Date {
27
- const next = new Date(date);
28
- next.setHours(
29
- source.getHours(),
30
- source.getMinutes(),
31
- source.getSeconds(),
32
- source.getMilliseconds(),
33
- );
34
- return next;
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
- // The date of the `week`th `weekday` in a given month (`week` 1–5, or -1 for the
38
- // last). Returns null when that week doesn't exist (e.g. a 5th Monday it lacks).
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
- ): Date | null {
45
- if (week === -1) {
46
- const lastDay = new Date(year, month + 1, 0);
47
- const back = (lastDay.getDay() - weekday + 7) % 7;
48
- return new Date(year, month, lastDay.getDate() - back);
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
- const weekdays = [...new Set(rule.weekdays)].sort((a, b) => a - b);
87
- let weekStart = startOfWeek(start, { weekStartsOn: 0 });
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 weekday of weekdays) {
90
- const date = withTimeOf(addDays(weekStart, weekday), start);
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
- const nextWeek = addWeeks(weekStart, interval);
97
- if (!(nextWeek.getTime() <= rangeEnd.getTime())) return;
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 = start.getFullYear();
104
- let month = start.getMonth();
168
+ let year = startYear;
169
+ let month = startMonth;
105
170
  while (true) {
106
- const daysInMonth = new Date(year, month + 1, 0).getDate();
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 ? daysInMonth + d + 1 : d)))]
110
- .filter((d) => d >= 1 && d <= daysInMonth)
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 = withTimeOf(new Date(year, month, d), start);
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 (!(new Date(year, month, 1).getTime() <= rangeEnd.getTime())) return;
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 = start.getFullYear();
131
- let month = start.getMonth();
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 = withTimeOf(day, start);
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 (!(new Date(year, month, 1).getTime() <= rangeEnd.getTime())) return;
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 = start.getFullYear();
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 (day > new Date(year, month + 1, 0).getDate()) continue;
157
- const date = withTimeOf(new Date(year, month, day), start);
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 (!(new Date(year, 0, 1).getTime() <= rangeEnd.getTime())) return;
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 as date-fns clamps shorter months.
171
- const occAt = (n: number) => STEP[rule.freq](start, n * interval);
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
- // Exceptions (EXDATE): a date-only exception (local midnight) drops every
223
- // occurrence on that calendar day (RFC 5545 VALUE=DATE); a timed exception
224
- // drops only the occurrence starting at that exact instant, so two
225
- // same-day occurrences can be cancelled independently.
226
- const dayKey = (d: Date) => `${d.getFullYear()}-${d.getMonth()}-${d.getDate()}`;
227
- const excludedDays = new Set<string>();
228
- const excludedInstants = new Set<number>();
229
- for (const exdate of event.recurrence.exdates ?? []) {
230
- const isMidnight =
231
- exdate.getHours() === 0 &&
232
- exdate.getMinutes() === 0 &&
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(rangeStart.getTime() - durationMs);
243
- for (const start of occurrenceStarts(event.start, event.recurrence, earliestStart, rangeEnd)) {
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() <= rangeEnd.getTime()) starts.set(rdate.getTime(), rdate);
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 < rangeStart.getTime()) continue;
253
- if (excludedDays.has(dayKey(start)) || excludedInstants.has(start.getTime())) continue;
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
  }
@@ -1,4 +1,6 @@
1
1
  import type { CalendarEvent } from "../types";
2
+ import { isAllDayEvent } from "./layout";
3
+ import { utcTime, zoneFields } from "./zoneFields";
2
4
 
3
5
  /**
4
6
  * Reinterpret an instant as its wall-clock time in `timeZone`, returned as a
@@ -11,48 +13,27 @@ import type { CalendarEvent } from "../types";
11
13
  * original UTC instant, so don't round-trip it back to a real time.
12
14
  */
13
15
  export function toZonedTime(date: Date, timeZone: string): Date {
14
- const parts = new Intl.DateTimeFormat("en-US", {
15
- timeZone,
16
- hourCycle: "h23",
17
- year: "numeric",
18
- month: "2-digit",
19
- day: "2-digit",
20
- hour: "2-digit",
21
- minute: "2-digit",
22
- second: "2-digit",
23
- }).formatToParts(date);
24
-
25
- const field = (type: Intl.DateTimeFormatPartTypes): number => {
26
- const part = parts.find((p) => p.type === type);
27
- return part ? Number(part.value) : 0;
28
- };
16
+ const [year, month, day, hour, minute, second] = zoneFields(date, timeZone);
17
+ return new Date(year, month, day, hour, minute, second, date.getMilliseconds());
18
+ }
29
19
 
30
- // `h23` can report midnight as 24; normalise to 0.
31
- const hour = field("hour") % 24;
32
- return new Date(
33
- field("year"),
34
- field("month") - 1,
35
- field("day"),
36
- hour,
37
- field("minute"),
38
- field("second"),
39
- date.getMilliseconds(),
40
- );
20
+ /**
21
+ * The current instant, or the fixed `now` when given, as the wall clock of
22
+ * `timeZone` (see {@link toZonedTime}). Without a `timeZone` it is the instant
23
+ * itself, read on the device clock. Compare calendar days against it to find
24
+ * "today" for a calendar displayed in another time zone.
25
+ */
26
+ export function nowInTimeZone(now?: Date, timeZone?: string): Date {
27
+ const instant = now ?? new Date();
28
+ return timeZone ? toZonedTime(instant, timeZone) : instant;
41
29
  }
42
30
 
43
31
  // `timeZone`'s offset from UTC (ms) at `instant`: the zone's wall clock read as
44
- // if it were UTC, minus the real instant.
32
+ // if it were UTC, minus the real instant. Read from plain fields, so the
33
+ // device's own DST changes can't distort it.
45
34
  function zoneOffsetMs(instant: Date, timeZone: string): number {
46
- const z = toZonedTime(instant, timeZone);
47
- const wallAsUtc = Date.UTC(
48
- z.getFullYear(),
49
- z.getMonth(),
50
- z.getDate(),
51
- z.getHours(),
52
- z.getMinutes(),
53
- z.getSeconds(),
54
- z.getMilliseconds(),
55
- );
35
+ const [year, month, day, hour, minute, second] = zoneFields(instant, timeZone);
36
+ const wallAsUtc = utcTime(year, month, day, hour, minute, second, instant.getUTCMilliseconds());
56
37
  return wallAsUtc - instant.getTime();
57
38
  }
58
39
 
@@ -60,28 +41,150 @@ function zoneOffsetMs(instant: Date, timeZone: string): number {
60
41
  * The inverse of {@link toZonedTime}: given a wall-clock time in `timeZone`,
61
42
  * return the absolute UTC instant. Pass the wall clock as a `Date` whose **UTC**
62
43
  * fields hold the components (e.g. `new Date(Date.UTC(y, m, d, h, min))`). Used to
63
- * resolve iCal `TZID` times; DST-correct via a two-pass offset (ambiguous
64
- * fall-back times resolve to the post-transition offset).
44
+ * resolve iCal `TZID` times; DST-correct via a two-pass offset. A time in the
45
+ * hour a spring-forward change skips names no instant; it resolves the same
46
+ * distance after the skipped hour (02:30 becomes 03:30), as a device clock does.
65
47
  */
66
48
  export function zonedTimeToUtc(wallClock: Date, timeZone: string): Date {
67
49
  const guess = wallClock.getTime();
68
50
  const firstPass = zoneOffsetMs(new Date(guess), timeZone);
69
51
  const secondPass = zoneOffsetMs(new Date(guess - firstPass), timeZone);
70
- return new Date(guess - secondPass);
52
+ const instant = new Date(guess - secondPass);
53
+ // Neither offset maps a skipped time back to itself. Read it with the offset
54
+ // in force before the change, which is the smaller of the two.
55
+ if (firstPass !== secondPass && zoneOffsetMs(instant, timeZone) !== secondPass) {
56
+ return new Date(guess - Math.min(firstPass, secondPass));
57
+ }
58
+ return instant;
59
+ }
60
+
61
+ /**
62
+ * The inverse of {@link toZonedTime}: the real instant for a date whose
63
+ * device-local fields hold a wall-clock time in `timeZone`, such as a date a
64
+ * calendar displaying that zone reports. DST-correct via {@link zonedTimeToUtc}.
65
+ */
66
+ export function fromZonedTime(date: Date, timeZone: string): Date {
67
+ return zonedTimeToUtc(
68
+ new Date(
69
+ utcTime(
70
+ date.getFullYear(),
71
+ date.getMonth(),
72
+ date.getDate(),
73
+ date.getHours(),
74
+ date.getMinutes(),
75
+ date.getSeconds(),
76
+ date.getMilliseconds(),
77
+ ),
78
+ ),
79
+ timeZone,
80
+ );
71
81
  }
72
82
 
83
+ // Each display copy made by `eventsInTimeZone`, mapped to the event it copies
84
+ // and the zone it was shifted into.
85
+ const zonedSources = new WeakMap<object, { event: object; timeZone: string }>();
86
+
73
87
  /**
74
- * Map every event's `start`/`end` through {@link toZonedTime} so the calendar
75
- * displays them in `timeZone`. Other fields are preserved. Memoize the result
76
- * (e.g. with `useMemo`) since it allocates new dates.
88
+ * Shift every timed event's `start`/`end` through {@link toZonedTime} so the
89
+ * calendar displays them in `timeZone`. Other fields are preserved. All-day
90
+ * events (see `isAllDayEvent`) name calendar days, not instants, so they are
91
+ * returned as they are and stay on their days. Memoize the result (e.g. with
92
+ * `useMemo`) since it allocates new dates.
77
93
  */
78
94
  export function eventsInTimeZone<T>(
79
95
  events: CalendarEvent<T>[],
80
96
  timeZone: string,
81
97
  ): CalendarEvent<T>[] {
82
- return events.map((event) => ({
83
- ...event,
84
- start: toZonedTime(event.start, timeZone),
85
- end: toZonedTime(event.end, timeZone),
86
- }));
98
+ return events.map((event) => {
99
+ if (isAllDayEvent(event)) return event;
100
+ const zoned = {
101
+ ...event,
102
+ start: toZonedTime(event.start, timeZone),
103
+ end: toZonedTime(event.end, timeZone),
104
+ };
105
+ zonedSources.set(zoned, { event, timeZone });
106
+ return zoned;
107
+ });
108
+ }
109
+
110
+ /**
111
+ * The event a display copy made by {@link eventsInTimeZone} stands for, with its
112
+ * real `start` and `end`. Any other event is returned as it is. Use it in the
113
+ * callbacks of a view that displays zoned events, to get back the event you
114
+ * passed in.
115
+ */
116
+ export function zonedEventSource<T>(event: CalendarEvent<T>): CalendarEvent<T> {
117
+ return (zonedSources.get(event)?.event as CalendarEvent<T> | undefined) ?? event;
118
+ }
119
+
120
+ /** Options for {@link zonedDragBounds}. */
121
+ export interface ZonedDragBoundsOptions {
122
+ /**
123
+ * Keep the event's real elapsed duration when the drag moved both edges, as a
124
+ * time-grid move does: the start is read off the zone's wall clock and the end
125
+ * follows it, so a move across a DST change in the zone doesn't stretch or
126
+ * shrink the event. Leave it off for a month-grid drop, which keeps the clock
127
+ * time of both edges.
128
+ */
129
+ keepDuration?: boolean;
130
+ }
131
+
132
+ /**
133
+ * Convert the bounds a view reports for a dragged event back to real instants.
134
+ * `event` is the displayed event the view passed to `onDragEvent`, and `start`
135
+ * / `end` the bounds it reported. For a display copy made by
136
+ * {@link eventsInTimeZone}, each bound is read as a wall-clock time in that
137
+ * zone, following the zone's own DST changes; an edge the drag left alone keeps
138
+ * the source event's exact instant. Bounds of any other event (an all-day
139
+ * event, or one that was never shifted) are returned unchanged.
140
+ *
141
+ * Returns `null` when the reported span doesn't survive the conversion: an edge
142
+ * dropped into the hour a spring-forward change skips moves to after it, which
143
+ * can leave the event ending at or before its start. Reject such a drop.
144
+ */
145
+ export function zonedDragBounds<T>(
146
+ event: CalendarEvent<T>,
147
+ start: Date,
148
+ end: Date,
149
+ { keepDuration = false }: ZonedDragBoundsOptions = {},
150
+ ): { start: Date; end: Date } | null {
151
+ const zoned = zonedSources.get(event);
152
+ if (!zoned) return { start, end };
153
+ const source = zoned.event as CalendarEvent<T>;
154
+ const startMoved = start.getTime() !== event.start.getTime();
155
+ const endMoved = end.getTime() !== event.end.getTime();
156
+ const realStart = startMoved ? fromZonedTime(start, zoned.timeZone) : source.start;
157
+ if (keepDuration && startMoved && endMoved) {
158
+ const durationMs = source.end.getTime() - source.start.getTime();
159
+ return { start: realStart, end: new Date(realStart.getTime() + durationMs) };
160
+ }
161
+ const realEnd = endMoved ? fromZonedTime(end, zoned.timeZone) : source.end;
162
+ return orderedLike(start, end, realStart, realEnd);
163
+ }
164
+
165
+ /**
166
+ * Convert a wall-clock range a view reports in `timeZone` (a created event, for
167
+ * example) to real instants. Returns `null` when the span doesn't survive the
168
+ * conversion: a time in the hour a spring-forward change skips moves to after
169
+ * it, which can leave the range ending at or before its start.
170
+ */
171
+ export function fromZonedRange(
172
+ start: Date,
173
+ end: Date,
174
+ timeZone: string,
175
+ ): { start: Date; end: Date } | null {
176
+ return orderedLike(start, end, fromZonedTime(start, timeZone), fromZonedTime(end, timeZone));
177
+ }
178
+
179
+ // The real bounds, unless a reported span collapsed: it ran forwards on the
180
+ // clock and the real one doesn't. The reverse is fine. In the hour a fall-back
181
+ // change repeats, two instants read the same, so a real span can show as empty.
182
+ function orderedLike(
183
+ start: Date,
184
+ end: Date,
185
+ realStart: Date,
186
+ realEnd: Date,
187
+ ): { start: Date; end: Date } | null {
188
+ const collapsed = end.getTime() > start.getTime() && realEnd.getTime() <= realStart.getTime();
189
+ return collapsed ? null : { start: realStart, end: realEnd };
87
190
  }
@@ -1,3 +1,4 @@
1
+ import { startOfDay } from "date-fns";
1
2
  import { useMemo } from "react";
2
3
  import { buildMonthGrid, type MonthGrid, type UseMonthGridOptions } from "./monthGrid";
3
4
 
@@ -22,7 +23,10 @@ export function useMonthGrid(month: Date, options: UseMonthGridOptions = {}): Mo
22
23
  maxDate,
23
24
  isDateDisabled,
24
25
  locale,
26
+ today,
25
27
  } = options;
28
+ // The day, not the instant, so a ticking clock rebuilds the grid once a day.
29
+ const todayKey = today ? startOfDay(today).getTime() : undefined;
26
30
  return useMemo(
27
31
  () => buildMonthGrid(month, options),
28
32
  // Deps are the destructured option fields, not the (unstable) options object.
@@ -37,6 +41,7 @@ export function useMonthGrid(month: Date, options: UseMonthGridOptions = {}): Mo
37
41
  maxDate,
38
42
  isDateDisabled,
39
43
  locale,
44
+ todayKey,
40
45
  ],
41
46
  );
42
47
  }