@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.
@@ -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
  }
@@ -1,5 +1,5 @@
1
1
  import { useEffect, useState } from "react";
2
- import { toZonedTime } from "./timezone";
2
+ import { nowInTimeZone } from "./timezone";
3
3
 
4
4
  /** Options for {@link useNow}. */
5
5
  export interface UseNowOptions {
@@ -20,11 +20,6 @@ export interface UseNowOptions {
20
20
 
21
21
  const MINUTE_MS = 60_000;
22
22
 
23
- const resolveNow = (now?: Date, timeZone?: string): Date => {
24
- const instant = now ?? new Date();
25
- return timeZone ? toZonedTime(instant, timeZone) : instant;
26
- };
27
-
28
23
  /**
29
24
  * The current wall-clock time, re-read every `tickMs` while `enabled`, shifted
30
25
  * into `timeZone` when given, or pinned to a fixed `now` override. Drives the
@@ -34,13 +29,13 @@ export function useNow(
34
29
  enabled: boolean,
35
30
  { now, timeZone, tickMs = MINUTE_MS }: UseNowOptions = {},
36
31
  ): Date {
37
- const [value, setValue] = useState(() => resolveNow(now, timeZone));
32
+ const [value, setValue] = useState(() => nowInTimeZone(now, timeZone));
38
33
  const nowMs = now?.getTime();
39
34
  useEffect(() => {
40
35
  if (!enabled) return;
41
- setValue(resolveNow(nowMs != null ? new Date(nowMs) : undefined, timeZone));
36
+ setValue(nowInTimeZone(nowMs != null ? new Date(nowMs) : undefined, timeZone));
42
37
  if (nowMs != null) return; // a fixed instant doesn't tick
43
- const id = setInterval(() => setValue(resolveNow(undefined, timeZone)), tickMs);
38
+ const id = setInterval(() => setValue(nowInTimeZone(undefined, timeZone)), tickMs);
44
39
  return () => clearInterval(id);
45
40
  }, [enabled, nowMs, timeZone, tickMs]);
46
41
  return value;
@@ -0,0 +1,71 @@
1
+ // Internal: read an instant's calendar fields in an IANA time zone. Kept apart
2
+ // from `timezone.ts`, whose exports are public API.
3
+
4
+ /** Calendar fields: year, month (0 = January), day, hour, minute, second. */
5
+ export type ZoneFields = [number, number, number, number, number, number];
6
+
7
+ // Building a formatter costs far more than formatting with it, and the views
8
+ // convert once per event and per rendered day, so keep one per zone. Zone names
9
+ // can come from untrusted input (an iCal `TZID`) and match in any letter case,
10
+ // so the cache is bounded: an app uses a handful of zones.
11
+ const MAX_ZONE_FORMATTERS = 32;
12
+ const zoneFormatters = new Map<string, Intl.DateTimeFormat>();
13
+
14
+ function zoneFormatter(timeZone: string): Intl.DateTimeFormat {
15
+ let formatter = zoneFormatters.get(timeZone);
16
+ if (!formatter) {
17
+ formatter = new Intl.DateTimeFormat("en-US", {
18
+ timeZone,
19
+ hourCycle: "h23",
20
+ year: "numeric",
21
+ month: "2-digit",
22
+ day: "2-digit",
23
+ hour: "2-digit",
24
+ minute: "2-digit",
25
+ second: "2-digit",
26
+ });
27
+ if (zoneFormatters.size >= MAX_ZONE_FORMATTERS) zoneFormatters.clear();
28
+ zoneFormatters.set(timeZone, formatter);
29
+ }
30
+ return formatter;
31
+ }
32
+
33
+ /**
34
+ * The wall-clock fields `date` reads in `timeZone`, as plain numbers. Unlike a
35
+ * device-local `Date` holding those fields, the result can't be bent by the
36
+ * device's own DST changes.
37
+ */
38
+ export function zoneFields(date: Date, timeZone: string): ZoneFields {
39
+ const parts = zoneFormatter(timeZone).formatToParts(date);
40
+ const field = (type: Intl.DateTimeFormatPartTypes): number => {
41
+ const part = parts.find((p) => p.type === type);
42
+ return part ? Number(part.value) : 0;
43
+ };
44
+ // `h23` can report midnight as 24; normalise to 0.
45
+ return [
46
+ field("year"),
47
+ field("month") - 1,
48
+ field("day"),
49
+ field("hour") % 24,
50
+ field("minute"),
51
+ field("second"),
52
+ ];
53
+ }
54
+
55
+ /**
56
+ * A calendar reading as a UTC time value. Fields may overflow and roll over.
57
+ * Setters, not `Date.UTC`, which reads a year below 100 as 19xx.
58
+ */
59
+ export function utcTime(
60
+ year: number,
61
+ month: number,
62
+ day: number,
63
+ hour = 0,
64
+ minute = 0,
65
+ second = 0,
66
+ ms = 0,
67
+ ): number {
68
+ const date = new Date(0);
69
+ date.setUTCFullYear(year, month, day);
70
+ return date.setUTCHours(hour, minute, second, ms);
71
+ }