@super-calendar/core 2.16.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.
@@ -71,12 +71,17 @@ const getWeekDays = (date, weekStartsOn) => {
71
71
  const start = (0, date_fns.startOfWeek)(date, { weekStartsOn });
72
72
  return Array.from({ length: 7 }, (_, index) => (0, date_fns.addDays)(start, index));
73
73
  };
74
- /** How many day columns a time-grid mode shows. `custom` uses `numberOfDays`. */
74
+ /**
75
+ * How many day columns a time-grid mode shows. `custom` uses `numberOfDays`.
76
+ * Throws a `RangeError` for `multiweek`, which has week rows instead of day
77
+ * columns; use `buildMultiWeekGrid` for it.
78
+ */
75
79
  const viewDayCount = (mode, numberOfDays = 1) => {
76
80
  switch (mode) {
77
81
  case "week": return 7;
78
82
  case "3days": return 3;
79
83
  case "custom": return Math.max(1, Math.floor(numberOfDays));
84
+ case "multiweek": throw new RangeError("The multiweek mode has week rows, not day columns. Use buildMultiWeekGrid for its days.");
80
85
  default: return 1;
81
86
  }
82
87
  };
@@ -103,6 +108,7 @@ const weekDaysCount = (weekStartsOn, weekEndsOn) => {
103
108
  * (honouring `weekStartsOn`). `custom` with a `weekEndsOn` spans the partial week
104
109
  * from `weekStartsOn` to `weekEndsOn` (anchored to `date`'s week, paging by week);
105
110
  * otherwise every mode shows `viewDayCount` consecutive days starting at `date`.
111
+ * Throws a `RangeError` for `multiweek` (see `viewDayCount`).
106
112
  */
107
113
  const getViewDays = (mode, date, weekStartsOn, numberOfDays = 1, isRTL = false, weekEndsOn, hiddenDays) => {
108
114
  const hidden = hiddenDays && hiddenDays.length > 0 && hiddenDays.length < 7 ? hiddenDays : [];
@@ -153,8 +159,12 @@ const isWeekend = (date) => {
153
159
  const day = date.getDay();
154
160
  return day === 0 || day === 6;
155
161
  };
156
- /** True when `date` falls on the current calendar day. */
157
- const getIsToday = (date) => (0, date_fns.isToday)(date);
162
+ /**
163
+ * True when `date` falls on the current calendar day. Pass `today` to compare
164
+ * against that day instead of the device clock, e.g. the result of
165
+ * `nowInTimeZone` for a calendar displayed in another time zone.
166
+ */
167
+ const getIsToday = (date, today) => today ? (0, date_fns.isSameDay)(date, today) : (0, date_fns.isToday)(date);
158
168
  /** True when `a` and `b` are the same calendar day (ignoring the time of day). */
159
169
  const isSameCalendarDay = (a, b) => (0, date_fns.isSameDay)(a, b);
160
170
  /** Minutes elapsed since midnight (0–1439). */
@@ -285,7 +295,7 @@ const clockSpan = (from, to, dayStart, nextDayStart) => {
285
295
  function layoutDayEvents(events, day) {
286
296
  const dayStart = (0, date_fns.startOfDay)(day);
287
297
  const nextDayStart = (0, date_fns.addDays)(dayStart, 1);
288
- const segments = events.filter((event) => !isAllDayEvent(event) && !isBackgroundEvent(event)).filter((event) => event.start < nextDayStart && event.end > dayStart).map((event) => {
298
+ const segments = events.filter((event) => !isAllDayEvent(event) && !isBackgroundEvent(event)).filter((event) => event.start < nextDayStart && (event.end > dayStart || event.end.getTime() === event.start.getTime() && event.start >= dayStart)).map((event) => {
289
299
  const segStart = (0, date_fns.max)([event.start, dayStart]);
290
300
  const segEnd = (0, date_fns.min)([event.end, nextDayStart]);
291
301
  return {
@@ -298,6 +308,7 @@ function layoutDayEvents(events, day) {
298
308
  const positioned = [];
299
309
  let cluster = [];
300
310
  let clusterEnd = Number.NEGATIVE_INFINITY;
311
+ const drawnEndOf = (seg) => Math.max(seg.end, seg.start + MIN_DURATION_HOURS);
301
312
  const flushCluster = () => {
302
313
  const columnEnds = [];
303
314
  const columnOf = /* @__PURE__ */ new Map();
@@ -305,8 +316,8 @@ function layoutDayEvents(events, day) {
305
316
  let column = columnEnds.findIndex((end) => end <= seg.start);
306
317
  if (column === -1) {
307
318
  column = columnEnds.length;
308
- columnEnds.push(seg.end);
309
- } else columnEnds[column] = seg.end;
319
+ columnEnds.push(drawnEndOf(seg));
320
+ } else columnEnds[column] = drawnEndOf(seg);
310
321
  columnOf.set(seg, column);
311
322
  }
312
323
  for (const seg of cluster) positioned.push({
@@ -323,7 +334,7 @@ function layoutDayEvents(events, day) {
323
334
  for (const seg of segments) {
324
335
  if (cluster.length > 0 && seg.start >= clusterEnd) flushCluster();
325
336
  cluster.push(seg);
326
- clusterEnd = Math.max(clusterEnd, seg.end);
337
+ clusterEnd = Math.max(clusterEnd, drawnEndOf(seg));
327
338
  }
328
339
  if (cluster.length > 0) flushCluster();
329
340
  return positioned;
@@ -348,7 +359,7 @@ function eventDayKeys(event) {
348
359
  const lastInstant = event.end > event.start ? /* @__PURE__ */ new Date(event.end.getTime() - 1) : event.start;
349
360
  const last = (0, date_fns.startOfDay)(lastInstant);
350
361
  const keys = [];
351
- for (let cursor = first; cursor <= last; cursor = (0, date_fns.addDays)(cursor, 1)) keys.push(cursor.toISOString());
362
+ for (let cursor = first; cursor <= last; cursor = (0, date_fns.startOfDay)((0, date_fns.addDays)(cursor, 1))) keys.push(cursor.toISOString());
352
363
  return keys;
353
364
  }
354
365
  /**
@@ -450,11 +461,19 @@ function backgroundBandsForDay(events, day) {
450
461
  // src/utils/drag.ts
451
462
  /**
452
463
  * True when two time ranges overlap. Edges touching (one ends exactly when the
453
- * next begins) do not count as an overlap. Compares absolute instants, so events
454
- * at the same wall-clock time on different days do not overlap.
464
+ * next begins) do not count as an overlap. A zero-length range occupies its own
465
+ * instant: it overlaps a range that contains that instant or starts at it, and
466
+ * another zero-length range at the same instant. Compares absolute instants, so
467
+ * events at the same wall-clock time on different days do not overlap.
455
468
  */
456
469
  function eventsOverlap(aStart, aEnd, bStart, bEnd) {
457
- return aStart.getTime() < bEnd.getTime() && bStart.getTime() < aEnd.getTime();
470
+ const a0 = aStart.getTime();
471
+ const a1 = aEnd.getTime();
472
+ const b0 = bStart.getTime();
473
+ const b1 = bEnd.getTime();
474
+ if (a0 === a1) return b0 === b1 ? a0 === b0 : b0 <= a0 && a0 < b1;
475
+ if (b0 === b1) return a0 <= b0 && b0 < a1;
476
+ return a0 < b1 && b0 < a1;
458
477
  }
459
478
  /**
460
479
  * True when the range `[start, end)` would overlap any event in `events` other
@@ -573,8 +592,8 @@ function resolveDraggedBounds(start, end, deltaStartMinutes, deltaEndMinutes, sn
573
592
  }
574
593
  /**
575
594
  * The all-day range swept out between two day cells of the month grid, ordered
576
- * whichever way the sweep ran: `start` is midnight of the first day and `end` is
577
- * midnight after the last, so a one-day sweep still yields a usable event. Shared
595
+ * whichever way the sweep ran: `start` is the first local day's start and `end` is
596
+ * the next day's start after the last, so a one-day sweep yields a usable event. Shared
578
597
  * by both renderers so a month drag-to-create means the same thing on each.
579
598
  */
580
599
  function monthCreateRange(anchor, hover) {
@@ -584,7 +603,7 @@ function monthCreateRange(anchor, hover) {
584
603
  const last = a.getTime() <= b.getTime() ? b : a;
585
604
  return {
586
605
  start: first,
587
- end: (0, date_fns.addDays)(last, 1)
606
+ end: (0, date_fns.startOfDay)((0, date_fns.addDays)(last, 1))
588
607
  };
589
608
  }
590
609
  /**
@@ -700,21 +719,21 @@ function eventAccessibilityLabel(args) {
700
719
  return [args.title, time].filter(Boolean).join(", ");
701
720
  }
702
721
  /**
703
- * Month cells and the all-day lane show a single clipped line; timed-grid titles
704
- * (`undefined`) wrap to fill the box.
722
+ * Month and multi-week cells and the all-day lane show a single clipped line;
723
+ * timed-grid titles (`undefined`) wrap to fill the box.
705
724
  */
706
725
  function titleNumberOfLines(mode, isAllDay) {
707
- return mode === "month" || isAllDay ? 1 : void 0;
726
+ return mode === "month" || mode === "multiweek" || isAllDay ? 1 : void 0;
708
727
  }
709
728
  /**
710
729
  * The secondary line under the title in the built-in renderer, or `null` when
711
730
  * none should show. Timed events get their `start - end` range. An all-day event
712
731
  * gets the literal "All day" in the schedule (which has no all-day lane to
713
732
  * signal it positionally) and nothing on the day/week grid (the lane already
714
- * does). Month cells and `showTime={false}` always return `null`.
733
+ * does). Month and multi-week cells and `showTime={false}` always return `null`.
715
734
  */
716
735
  function eventTimeLabel(args) {
717
- if (!args.showTime || args.mode === "month") return null;
736
+ if (!args.showTime || args.mode === "month" || args.mode === "multiweek") return null;
718
737
  if (args.isAllDay) return args.mode === "schedule" ? args.allDayLabel ?? "All day" : null;
719
738
  const timeFormat = args.ampm ? "h:mm a" : "HH:mm";
720
739
  return `${(0, date_fns.format)(args.start, timeFormat)} - ${(0, date_fns.format)(args.end, timeFormat)}`;
@@ -794,6 +813,56 @@ function monthVisibleCount(total, capacity) {
794
813
  if (total <= capacity.full) return total;
795
814
  return Math.max(1, capacity.withMore);
796
815
  }
816
+ // src/utils/zoneFields.ts
817
+ const MAX_ZONE_FORMATTERS = 32;
818
+ const zoneFormatters = /* @__PURE__ */ new Map();
819
+ function zoneFormatter(timeZone) {
820
+ let formatter = zoneFormatters.get(timeZone);
821
+ if (!formatter) {
822
+ formatter = new Intl.DateTimeFormat("en-US", {
823
+ timeZone,
824
+ hourCycle: "h23",
825
+ year: "numeric",
826
+ month: "2-digit",
827
+ day: "2-digit",
828
+ hour: "2-digit",
829
+ minute: "2-digit",
830
+ second: "2-digit"
831
+ });
832
+ if (zoneFormatters.size >= MAX_ZONE_FORMATTERS) zoneFormatters.clear();
833
+ zoneFormatters.set(timeZone, formatter);
834
+ }
835
+ return formatter;
836
+ }
837
+ /**
838
+ * The wall-clock fields `date` reads in `timeZone`, as plain numbers. Unlike a
839
+ * device-local `Date` holding those fields, the result can't be bent by the
840
+ * device's own DST changes.
841
+ */
842
+ function zoneFields(date, timeZone) {
843
+ const parts = zoneFormatter(timeZone).formatToParts(date);
844
+ const field = (type) => {
845
+ const part = parts.find((p) => p.type === type);
846
+ return part ? Number(part.value) : 0;
847
+ };
848
+ return [
849
+ field("year"),
850
+ field("month") - 1,
851
+ field("day"),
852
+ field("hour") % 24,
853
+ field("minute"),
854
+ field("second")
855
+ ];
856
+ }
857
+ /**
858
+ * A calendar reading as a UTC time value. Fields may overflow and roll over.
859
+ * Setters, not `Date.UTC`, which reads a year below 100 as 19xx.
860
+ */
861
+ function utcTime(year, month, day, hour = 0, minute = 0, second = 0, ms = 0) {
862
+ const date = /* @__PURE__ */ new Date(0);
863
+ date.setUTCFullYear(year, month, day);
864
+ return date.setUTCHours(hour, minute, second, ms);
865
+ }
797
866
  // src/utils/timezone.ts
798
867
  /**
799
868
  * Reinterpret an instant as its wall-clock time in `timeZone`, returned as a
@@ -806,51 +875,125 @@ function monthVisibleCount(total, capacity) {
806
875
  * original UTC instant, so don't round-trip it back to a real time.
807
876
  */
808
877
  function toZonedTime(date, timeZone) {
809
- const parts = new Intl.DateTimeFormat("en-US", {
810
- timeZone,
811
- hourCycle: "h23",
812
- year: "numeric",
813
- month: "2-digit",
814
- day: "2-digit",
815
- hour: "2-digit",
816
- minute: "2-digit",
817
- second: "2-digit"
818
- }).formatToParts(date);
819
- const field = (type) => {
820
- const part = parts.find((p) => p.type === type);
821
- return part ? Number(part.value) : 0;
822
- };
823
- const hour = field("hour") % 24;
824
- return new Date(field("year"), field("month") - 1, field("day"), hour, field("minute"), field("second"), date.getMilliseconds());
878
+ const [year, month, day, hour, minute, second] = zoneFields(date, timeZone);
879
+ return new Date(year, month, day, hour, minute, second, date.getMilliseconds());
880
+ }
881
+ /**
882
+ * The current instant, or the fixed `now` when given, as the wall clock of
883
+ * `timeZone` (see {@link toZonedTime}). Without a `timeZone` it is the instant
884
+ * itself, read on the device clock. Compare calendar days against it to find
885
+ * "today" for a calendar displayed in another time zone.
886
+ */
887
+ function nowInTimeZone(now, timeZone) {
888
+ const instant = now ?? /* @__PURE__ */ new Date();
889
+ return timeZone ? toZonedTime(instant, timeZone) : instant;
825
890
  }
826
891
  function zoneOffsetMs(instant, timeZone) {
827
- const z = toZonedTime(instant, timeZone);
828
- return Date.UTC(z.getFullYear(), z.getMonth(), z.getDate(), z.getHours(), z.getMinutes(), z.getSeconds(), z.getMilliseconds()) - instant.getTime();
892
+ const [year, month, day, hour, minute, second] = zoneFields(instant, timeZone);
893
+ return utcTime(year, month, day, hour, minute, second, instant.getUTCMilliseconds()) - instant.getTime();
829
894
  }
830
895
  /**
831
896
  * The inverse of {@link toZonedTime}: given a wall-clock time in `timeZone`,
832
897
  * return the absolute UTC instant. Pass the wall clock as a `Date` whose **UTC**
833
898
  * fields hold the components (e.g. `new Date(Date.UTC(y, m, d, h, min))`). Used to
834
- * resolve iCal `TZID` times; DST-correct via a two-pass offset (ambiguous
835
- * fall-back times resolve to the post-transition offset).
899
+ * resolve iCal `TZID` times; DST-correct via a two-pass offset. A time in the
900
+ * hour a spring-forward change skips names no instant; it resolves the same
901
+ * distance after the skipped hour (02:30 becomes 03:30), as a device clock does.
836
902
  */
837
903
  function zonedTimeToUtc(wallClock, timeZone) {
838
904
  const guess = wallClock.getTime();
839
905
  const firstPass = zoneOffsetMs(new Date(guess), timeZone);
840
906
  const secondPass = zoneOffsetMs(new Date(guess - firstPass), timeZone);
841
- return new Date(guess - secondPass);
907
+ const instant = new Date(guess - secondPass);
908
+ if (firstPass !== secondPass && zoneOffsetMs(instant, timeZone) !== secondPass) return new Date(guess - Math.min(firstPass, secondPass));
909
+ return instant;
910
+ }
911
+ /**
912
+ * The inverse of {@link toZonedTime}: the real instant for a date whose
913
+ * device-local fields hold a wall-clock time in `timeZone`, such as a date a
914
+ * calendar displaying that zone reports. DST-correct via {@link zonedTimeToUtc}.
915
+ */
916
+ function fromZonedTime(date, timeZone) {
917
+ return zonedTimeToUtc(new Date(utcTime(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds(), date.getMilliseconds())), timeZone);
842
918
  }
919
+ const zonedSources = /* @__PURE__ */ new WeakMap();
843
920
  /**
844
- * Map every event's `start`/`end` through {@link toZonedTime} so the calendar
845
- * displays them in `timeZone`. Other fields are preserved. Memoize the result
846
- * (e.g. with `useMemo`) since it allocates new dates.
921
+ * Shift every timed event's `start`/`end` through {@link toZonedTime} so the
922
+ * calendar displays them in `timeZone`. Other fields are preserved. All-day
923
+ * events (see `isAllDayEvent`) name calendar days, not instants, so they are
924
+ * returned as they are and stay on their days. Memoize the result (e.g. with
925
+ * `useMemo`) since it allocates new dates.
847
926
  */
848
927
  function eventsInTimeZone(events, timeZone) {
849
- return events.map((event) => ({
850
- ...event,
851
- start: toZonedTime(event.start, timeZone),
852
- end: toZonedTime(event.end, timeZone)
853
- }));
928
+ return events.map((event) => {
929
+ if (isAllDayEvent(event)) return event;
930
+ const zoned = {
931
+ ...event,
932
+ start: toZonedTime(event.start, timeZone),
933
+ end: toZonedTime(event.end, timeZone)
934
+ };
935
+ zonedSources.set(zoned, {
936
+ event,
937
+ timeZone
938
+ });
939
+ return zoned;
940
+ });
941
+ }
942
+ /**
943
+ * The event a display copy made by {@link eventsInTimeZone} stands for, with its
944
+ * real `start` and `end`. Any other event is returned as it is. Use it in the
945
+ * callbacks of a view that displays zoned events, to get back the event you
946
+ * passed in.
947
+ */
948
+ function zonedEventSource(event) {
949
+ return zonedSources.get(event)?.event ?? event;
950
+ }
951
+ /**
952
+ * Convert the bounds a view reports for a dragged event back to real instants.
953
+ * `event` is the displayed event the view passed to `onDragEvent`, and `start`
954
+ * / `end` the bounds it reported. For a display copy made by
955
+ * {@link eventsInTimeZone}, each bound is read as a wall-clock time in that
956
+ * zone, following the zone's own DST changes; an edge the drag left alone keeps
957
+ * the source event's exact instant. Bounds of any other event (an all-day
958
+ * event, or one that was never shifted) are returned unchanged.
959
+ *
960
+ * Returns `null` when the reported span doesn't survive the conversion: an edge
961
+ * dropped into the hour a spring-forward change skips moves to after it, which
962
+ * can leave the event ending at or before its start. Reject such a drop.
963
+ */
964
+ function zonedDragBounds(event, start, end, { keepDuration = false } = {}) {
965
+ const zoned = zonedSources.get(event);
966
+ if (!zoned) return {
967
+ start,
968
+ end
969
+ };
970
+ const source = zoned.event;
971
+ const startMoved = start.getTime() !== event.start.getTime();
972
+ const endMoved = end.getTime() !== event.end.getTime();
973
+ const realStart = startMoved ? fromZonedTime(start, zoned.timeZone) : source.start;
974
+ if (keepDuration && startMoved && endMoved) {
975
+ const durationMs = source.end.getTime() - source.start.getTime();
976
+ return {
977
+ start: realStart,
978
+ end: new Date(realStart.getTime() + durationMs)
979
+ };
980
+ }
981
+ return orderedLike(start, end, realStart, endMoved ? fromZonedTime(end, zoned.timeZone) : source.end);
982
+ }
983
+ /**
984
+ * Convert a wall-clock range a view reports in `timeZone` (a created event, for
985
+ * example) to real instants. Returns `null` when the span doesn't survive the
986
+ * conversion: a time in the hour a spring-forward change skips moves to after
987
+ * it, which can leave the range ending at or before its start.
988
+ */
989
+ function fromZonedRange(start, end, timeZone) {
990
+ return orderedLike(start, end, fromZonedTime(start, timeZone), fromZonedTime(end, timeZone));
991
+ }
992
+ function orderedLike(start, end, realStart, realEnd) {
993
+ return end.getTime() > start.getTime() && realEnd.getTime() <= realStart.getTime() ? null : {
994
+ start: realStart,
995
+ end: realEnd
996
+ };
854
997
  }
855
998
  // src/utils/ical.ts
856
999
  const RRULE_FREQ = {
@@ -984,6 +1127,8 @@ function parseRRule(value) {
984
1127
  }
985
1128
  if (plain.length) rule.weekdays = plain;
986
1129
  }
1130
+ const wkst = BYDAY.indexOf(parts.get("WKST")?.trim().toUpperCase());
1131
+ if (wkst >= 0) rule.weekStartsOn = wkst;
987
1132
  const bymonthday = parts.get("BYMONTHDAY");
988
1133
  if (bymonthday) {
989
1134
  const days = bymonthday.split(",").map((d) => Number(d.trim())).filter((d) => Number.isInteger(d) && d !== 0);
@@ -1003,6 +1148,7 @@ function formatRRule(rule) {
1003
1148
  if (rule.until) parts.push(`UNTIL=${formatUtc(rule.until)}`);
1004
1149
  if (rule.nthWeekday) parts.push(`BYDAY=${rule.nthWeekday.week}${BYDAY[rule.nthWeekday.weekday]}`);
1005
1150
  else if (rule.weekdays?.length) parts.push(`BYDAY=${rule.weekdays.map((d) => BYDAY[d]).join(",")}`);
1151
+ if (rule.weekStartsOn != null && BYDAY[rule.weekStartsOn]) parts.push(`WKST=${BYDAY[rule.weekStartsOn]}`);
1006
1152
  if (rule.monthDays?.length) parts.push(`BYMONTHDAY=${rule.monthDays.join(",")}`);
1007
1153
  if (rule.months?.length) parts.push(`BYMONTH=${rule.months.join(",")}`);
1008
1154
  return parts.join(";");
@@ -1196,6 +1342,7 @@ function recurrenceFromJSON(value, field) {
1196
1342
  if (input.until !== void 0) rule.until = dateFromJSON(input.until, `${field}.until`);
1197
1343
  for (const key of ["exdates", "rdates"]) if (input[key] !== void 0) rule[key] = arrayFromJSON(input[key], `${field}.${key}`).map((date, index) => dateFromJSON(date, `${field}.${key}[${index}]`));
1198
1344
  if (input.weekdays !== void 0) rule.weekdays = arrayFromJSON(input.weekdays, `${field}.weekdays`).map((day) => weekdayFromJSON(day, `${field}.weekdays`));
1345
+ if (input.weekStartsOn !== void 0) rule.weekStartsOn = weekdayFromJSON(input.weekStartsOn, `${field}.weekStartsOn`);
1199
1346
  if (input.months !== void 0) rule.months = arrayFromJSON(input.months, `${field}.months`).map((month) => integerFromJSON(month, `${field}.months`, 1, 12));
1200
1347
  if (input.monthDays !== void 0) rule.monthDays = arrayFromJSON(input.monthDays, `${field}.monthDays`).map((day) => {
1201
1348
  const parsed = integerFromJSON(day, `${field}.monthDays`, -31, 31);
@@ -1331,7 +1478,7 @@ function weekdayFormatToken(format) {
1331
1478
  * data outside React; inside a component prefer {@link useMonthGrid}.
1332
1479
  */
1333
1480
  function buildMonthGrid(month, options = {}) {
1334
- const { weekStartsOn = 0, weekdayFormat = "short", showSixWeeks = false, isRTL = false, hiddenDays, selectedDates, selectedRange, minDate, maxDate, isDateDisabled, locale } = options;
1481
+ const { weekStartsOn = 0, weekdayFormat = "short", showSixWeeks = false, isRTL = false, hiddenDays, selectedDates, selectedRange, minDate, maxDate, isDateDisabled, locale, today } = options;
1335
1482
  const rows = buildMonthWeeks(month, weekStartsOn, {
1336
1483
  showSixWeeks,
1337
1484
  isRTL,
@@ -1344,7 +1491,7 @@ function buildMonthGrid(month, options = {}) {
1344
1491
  id: (0, date_fns.format)(date, "yyyy-MM-dd"),
1345
1492
  label: (0, date_fns.format)(date, "d"),
1346
1493
  isCurrentMonth: (0, date_fns.isSameMonth)(date, month),
1347
- isToday: getIsToday(date),
1494
+ isToday: getIsToday(date, today),
1348
1495
  isWeekend: isWeekend(date),
1349
1496
  ...daySelectionState(date, {
1350
1497
  selectedDates,
@@ -1368,13 +1515,78 @@ function buildMonthGrid(month, options = {}) {
1368
1515
  }))
1369
1516
  };
1370
1517
  }
1518
+ // src/utils/multiWeekGrid.ts
1519
+ /**
1520
+ * Pure multi-week builder: `numberOfWeeks` consecutive full calendar weeks,
1521
+ * starting with the week that contains `date` (aligned back to `weekStartsOn`).
1522
+ * Each day carries the same selection, disabled, today, and weekend state as
1523
+ * {@link buildMonthGrid}. Hidden weekdays shrink the rows without changing the
1524
+ * period; `isRTL` reverses each row's display order.
1525
+ *
1526
+ * The result is fully materialized, so its size grows with `numberOfWeeks`.
1527
+ *
1528
+ * @throws RangeError when `date` is invalid, `numberOfWeeks` is not a positive
1529
+ * safe integer, or the last week falls outside the range `Date` can represent.
1530
+ */
1531
+ function buildMultiWeekGrid(date, options = {}) {
1532
+ const { numberOfWeeks = 2, weekStartsOn = 0, weekdayFormat = "short", isRTL = false, hiddenDays, selectedDates, selectedRange, minDate, maxDate, isDateDisabled, locale, today } = options;
1533
+ if (!(date instanceof Date) || Number.isNaN(date.getTime())) throw new RangeError("buildMultiWeekGrid: date must be a valid Date.");
1534
+ if (!Number.isSafeInteger(numberOfWeeks) || numberOfWeeks < 1) throw new RangeError(`buildMultiWeekGrid: numberOfWeeks must be a positive whole number, received ${String(numberOfWeeks)}.`);
1535
+ const start = (0, date_fns.startOfWeek)(date, { weekStartsOn });
1536
+ const endExclusive = (0, date_fns.addDays)(start, numberOfWeeks * 7);
1537
+ if (Number.isNaN(endExclusive.getTime())) throw new RangeError(`buildMultiWeekGrid: ${numberOfWeeks} weeks from ${(0, date_fns.format)(start, "yyyy-MM-dd")} cannot be represented as a Date.`);
1538
+ const constraints = {
1539
+ minDate,
1540
+ maxDate,
1541
+ isDateDisabled
1542
+ };
1543
+ const selection = {
1544
+ selectedDates,
1545
+ selectedRange
1546
+ };
1547
+ let first = null;
1548
+ let last = null;
1549
+ const weeks = [];
1550
+ for (let row = 0; row < numberOfWeeks; row++) {
1551
+ const weekStart = (0, date_fns.addDays)(start, row * 7);
1552
+ const all = Array.from({ length: 7 }, (_, index) => (0, date_fns.addDays)(weekStart, index));
1553
+ const visible = filterHiddenDays(all, hiddenDays);
1554
+ if (visible.length > 0) {
1555
+ if (first === null) first = visible[0];
1556
+ last = visible[visible.length - 1];
1557
+ }
1558
+ const ordered = isRTL ? [...visible].reverse() : visible;
1559
+ weeks.push({
1560
+ id: (0, date_fns.format)(weekStart, "yyyy-MM-dd"),
1561
+ days: ordered.map((day) => ({
1562
+ date: day,
1563
+ id: (0, date_fns.format)(day, "yyyy-MM-dd"),
1564
+ label: (0, date_fns.format)(day, "d"),
1565
+ isToday: getIsToday(day, today),
1566
+ isWeekend: isWeekend(day),
1567
+ ...daySelectionState(day, selection, constraints)
1568
+ }))
1569
+ });
1570
+ }
1571
+ const token = weekdayFormatToken(weekdayFormat);
1572
+ const weekdays = weeks[0].days.map((day) => ({
1573
+ date: day.date,
1574
+ label: (0, date_fns.format)(day.date, token, { locale })
1575
+ }));
1576
+ return {
1577
+ period: {
1578
+ start,
1579
+ endExclusive
1580
+ },
1581
+ visibleRange: {
1582
+ start: first ?? start,
1583
+ endExclusive: last ? (0, date_fns.addDays)(last, 1) : endExclusive
1584
+ },
1585
+ weeks,
1586
+ weekdays
1587
+ };
1588
+ }
1371
1589
  // src/utils/recurrence.ts
1372
- const STEP = {
1373
- daily: date_fns.addDays,
1374
- weekly: date_fns.addWeeks,
1375
- monthly: date_fns.addMonths,
1376
- yearly: date_fns.addYears
1377
- };
1378
1590
  const MAX_OCCURRENCES = 5e3;
1379
1591
  const APPROX_STEP_MS = {
1380
1592
  daily: 864e5,
@@ -1382,23 +1594,58 @@ const APPROX_STEP_MS = {
1382
1594
  monthly: 2629746e3,
1383
1595
  yearly: 31556952e3
1384
1596
  };
1385
- function withTimeOf(date, source) {
1386
- const next = new Date(date);
1387
- next.setHours(source.getHours(), source.getMinutes(), source.getSeconds(), source.getMilliseconds());
1388
- return next;
1597
+ const WEEKDAYS = /* @__PURE__ */ new Set([
1598
+ 0,
1599
+ 1,
1600
+ 2,
1601
+ 3,
1602
+ 4,
1603
+ 5,
1604
+ 6
1605
+ ]);
1606
+ const DEVICE_CLOCK = {
1607
+ fields: (instant) => [
1608
+ instant.getFullYear(),
1609
+ instant.getMonth(),
1610
+ instant.getDate(),
1611
+ instant.getHours(),
1612
+ instant.getMinutes(),
1613
+ instant.getSeconds(),
1614
+ instant.getMilliseconds()
1615
+ ],
1616
+ at(year, month, day, hour, minute, second, ms) {
1617
+ const date = new Date(2e3, 0, 1);
1618
+ date.setFullYear(year, month, day);
1619
+ date.setHours(hour, minute, second, ms);
1620
+ return date;
1621
+ }
1622
+ };
1623
+ function zoneClock(timeZone, start) {
1624
+ const fields = (instant) => [...zoneFields(instant, timeZone), instant.getUTCMilliseconds()];
1625
+ const origin = fields(start);
1626
+ return {
1627
+ fields,
1628
+ at(...reading) {
1629
+ if (reading.every((value, index) => value === origin[index])) return new Date(start);
1630
+ const wallClock = utcTime(...reading);
1631
+ if (!(Math.abs(wallClock) <= 86399999136e5)) return /* @__PURE__ */ new Date(NaN);
1632
+ return zonedTimeToUtc(new Date(wallClock), timeZone);
1633
+ }
1634
+ };
1389
1635
  }
1636
+ const weekdayOf = (year, month, day) => new Date(utcTime(year, month, day)).getUTCDay();
1637
+ const daysInMonth = (year, month) => new Date(utcTime(year, month + 1, 0)).getUTCDate();
1390
1638
  function nthWeekdayOfMonth(year, month, week, weekday) {
1391
- if (week === -1) {
1392
- const lastDay = new Date(year, month + 1, 0);
1393
- const back = (lastDay.getDay() - weekday + 7) % 7;
1394
- return new Date(year, month, lastDay.getDate() - back);
1395
- }
1396
- const day = 1 + (weekday - new Date(year, month, 1).getDay() + 7) % 7 + (week - 1) * 7;
1397
- const date = new Date(year, month, day);
1398
- return date.getMonth() === month ? date : null;
1639
+ const lastDay = daysInMonth(year, month);
1640
+ if (week === -1) return lastDay - (weekdayOf(year, month, lastDay) - weekday + 7) % 7;
1641
+ const day = 1 + (weekday - weekdayOf(year, month, 1) + 7) % 7 + (week - 1) * 7;
1642
+ return day <= lastDay ? day : null;
1399
1643
  }
1400
- function* occurrenceStarts(start, rule, earliestStart, rangeEnd) {
1644
+ function* occurrenceStarts(start, rule, earliestStart, rangeEnd, clock) {
1401
1645
  const interval = Math.max(1, Math.trunc(rule.interval ?? 1));
1646
+ const [startYear, startMonth, startDay, hour, minute, second, ms] = clock.fields(start);
1647
+ const onDay = (year, month, day) => clock.at(year, month, day, hour, minute, second, ms);
1648
+ const dayStart = (year, month, day) => clock.at(year, month, day, 0, 0, 0, 0);
1402
1649
  let produced = 0;
1403
1650
  let emitted = 0;
1404
1651
  const consider = (date) => {
@@ -1413,29 +1660,29 @@ function* occurrenceStarts(start, rule, earliestStart, rangeEnd) {
1413
1660
  return "emit";
1414
1661
  };
1415
1662
  if (rule.freq === "weekly" && rule.weekdays?.length) {
1416
- const weekdays = [...new Set(rule.weekdays)].sort((a, b) => a - b);
1417
- let weekStart = (0, date_fns.startOfWeek)(start, { weekStartsOn: 0 });
1663
+ const weekStartsOn = WEEKDAYS.has(rule.weekStartsOn) ? rule.weekStartsOn : 1;
1664
+ const offsets = [...new Set(rule.weekdays.map((day) => (day - weekStartsOn + 7) % 7))].sort((a, b) => a - b);
1665
+ let weekStart = startDay - (weekdayOf(startYear, startMonth, startDay) - weekStartsOn + 7) % 7;
1418
1666
  while (true) {
1419
- for (const weekday of weekdays) {
1420
- const date = withTimeOf((0, date_fns.addDays)(weekStart, weekday), start);
1667
+ for (const offset of offsets) {
1668
+ const date = onDay(startYear, startMonth, weekStart + offset);
1421
1669
  const verdict = consider(date);
1422
1670
  if (verdict === "stop") return;
1423
1671
  if (verdict === "skip") continue;
1424
1672
  yield date;
1425
1673
  }
1426
- const nextWeek = (0, date_fns.addWeeks)(weekStart, interval);
1427
- if (!(nextWeek.getTime() <= rangeEnd.getTime())) return;
1428
- weekStart = nextWeek;
1674
+ weekStart += 7 * interval;
1675
+ if (!(dayStart(startYear, startMonth, weekStart).getTime() <= rangeEnd.getTime())) return;
1429
1676
  }
1430
1677
  }
1431
1678
  if (rule.freq === "monthly" && rule.monthDays?.length) {
1432
- let year = start.getFullYear();
1433
- let month = start.getMonth();
1679
+ let year = startYear;
1680
+ let month = startMonth;
1434
1681
  while (true) {
1435
- const daysInMonth = new Date(year, month + 1, 0).getDate();
1436
- 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);
1682
+ const lastDay = daysInMonth(year, month);
1683
+ const days = [...new Set(rule.monthDays.map((d) => d < 0 ? lastDay + d + 1 : d))].filter((d) => d >= 1 && d <= lastDay).sort((a, b) => a - b);
1437
1684
  for (const d of days) {
1438
- const date = withTimeOf(new Date(year, month, d), start);
1685
+ const date = onDay(year, month, d);
1439
1686
  const verdict = consider(date);
1440
1687
  if (verdict === "stop") return;
1441
1688
  if (verdict === "skip") continue;
@@ -1444,18 +1691,18 @@ function* occurrenceStarts(start, rule, earliestStart, rangeEnd) {
1444
1691
  month += interval;
1445
1692
  year += Math.floor(month / 12);
1446
1693
  month = (month % 12 + 12) % 12;
1447
- if (!(new Date(year, month, 1).getTime() <= rangeEnd.getTime())) return;
1694
+ if (!(dayStart(year, month, 1).getTime() <= rangeEnd.getTime())) return;
1448
1695
  }
1449
1696
  }
1450
1697
  if ((rule.freq === "monthly" || rule.freq === "yearly") && rule.nthWeekday) {
1451
1698
  const { week, weekday } = rule.nthWeekday;
1452
1699
  const stepMonths = rule.freq === "monthly" ? interval : 12 * interval;
1453
- let year = start.getFullYear();
1454
- let month = start.getMonth();
1700
+ let year = startYear;
1701
+ let month = startMonth;
1455
1702
  while (true) {
1456
1703
  const day = nthWeekdayOfMonth(year, month, week, weekday);
1457
- if (day) {
1458
- const date = withTimeOf(day, start);
1704
+ if (day !== null) {
1705
+ const date = onDay(year, month, day);
1459
1706
  const verdict = consider(date);
1460
1707
  if (verdict === "stop") return;
1461
1708
  if (verdict === "emit") yield date;
@@ -1463,28 +1710,34 @@ function* occurrenceStarts(start, rule, earliestStart, rangeEnd) {
1463
1710
  month += stepMonths;
1464
1711
  year += Math.floor(month / 12);
1465
1712
  month = (month % 12 + 12) % 12;
1466
- if (!(new Date(year, month, 1).getTime() <= rangeEnd.getTime())) return;
1713
+ if (!(dayStart(year, month, 1).getTime() <= rangeEnd.getTime())) return;
1467
1714
  }
1468
1715
  }
1469
1716
  if (rule.freq === "yearly" && rule.months?.length) {
1470
- const day = start.getDate();
1471
1717
  const months = [...new Set(rule.months)].filter((m) => m >= 1 && m <= 12).sort((a, b) => a - b);
1472
- let year = start.getFullYear();
1718
+ let year = startYear;
1473
1719
  while (true) {
1474
1720
  for (const m of months) {
1475
1721
  const month = m - 1;
1476
- if (day > new Date(year, month + 1, 0).getDate()) continue;
1477
- const date = withTimeOf(new Date(year, month, day), start);
1722
+ if (startDay > daysInMonth(year, month)) continue;
1723
+ const date = onDay(year, month, startDay);
1478
1724
  const verdict = consider(date);
1479
1725
  if (verdict === "stop") return;
1480
1726
  if (verdict === "skip") continue;
1481
1727
  yield date;
1482
1728
  }
1483
1729
  year += interval;
1484
- if (!(new Date(year, 0, 1).getTime() <= rangeEnd.getTime())) return;
1730
+ if (!(dayStart(year, 0, 1).getTime() <= rangeEnd.getTime())) return;
1485
1731
  }
1486
1732
  }
1487
- const occAt = (n) => STEP[rule.freq](start, n * interval);
1733
+ const occAt = (n) => {
1734
+ if (n === 0) return new Date(start.getTime());
1735
+ const steps = n * interval;
1736
+ if (rule.freq === "daily") return onDay(startYear, startMonth, startDay + steps);
1737
+ if (rule.freq === "weekly") return onDay(startYear, startMonth, startDay + 7 * steps);
1738
+ const month = startMonth + (rule.freq === "monthly" ? steps : 12 * steps);
1739
+ return onDay(startYear, month, Math.min(startDay, daysInMonth(startYear, month)));
1740
+ };
1488
1741
  const lowerBound = earliestStart.getTime();
1489
1742
  let n = 0;
1490
1743
  if (occAt(0).getTime() < lowerBound) {
@@ -1512,13 +1765,18 @@ function instanceAt(event, start, durationMs) {
1512
1765
  delete instance.recurrence;
1513
1766
  return instance;
1514
1767
  }
1768
+ const zonedOrInvalid = (date, timeZone) => Number.isNaN(date.getTime()) ? date : toZonedTime(date, timeZone);
1769
+ const isMidnight = (fields) => fields[3] === 0 && fields[4] === 0 && fields[5] === 0 && fields[6] === 0;
1515
1770
  /**
1516
1771
  * Materialise recurring events into concrete occurrences overlapping
1517
1772
  * `[rangeStart, rangeEnd]`. Non-recurring events pass through untouched, so the
1518
1773
  * result is ready to hand to `<Calendar events={...} />`. Each occurrence keeps
1519
1774
  * the original event's duration and fields (minus `recurrence`).
1775
+ *
1776
+ * Pass `timeZone` to repeat timed events on that zone's wall clock instead of
1777
+ * the device's. `rangeStart` and `rangeEnd` are real instants either way.
1520
1778
  */
1521
- function expandRecurringEvents(events, rangeStart, rangeEnd) {
1779
+ function expandRecurringEvents(events, rangeStart, rangeEnd, { timeZone } = {}) {
1522
1780
  const out = [];
1523
1781
  for (const event of events) {
1524
1782
  if (!event.recurrence) {
@@ -1526,19 +1784,43 @@ function expandRecurringEvents(events, rangeStart, rangeEnd) {
1526
1784
  continue;
1527
1785
  }
1528
1786
  const durationMs = event.end.getTime() - event.start.getTime();
1529
- const dayKey = (d) => `${d.getFullYear()}-${d.getMonth()}-${d.getDate()}`;
1787
+ const zoned = timeZone != null && !isAllDayEvent(event) && !Number.isNaN(event.start.getTime());
1788
+ const clock = zoned ? zoneClock(timeZone, event.start) : DEVICE_CLOCK;
1789
+ const [from, to] = timeZone != null && isAllDayEvent(event) ? [zonedOrInvalid(rangeStart, timeZone), zonedOrInvalid(rangeEnd, timeZone)] : [rangeStart, rangeEnd];
1790
+ const starts = /* @__PURE__ */ new Map();
1791
+ const earliestStart = new Date(from.getTime() - durationMs);
1792
+ for (const start of occurrenceStarts(event.start, event.recurrence, earliestStart, to, clock)) starts.set(start.getTime(), start);
1793
+ for (const rdate of event.recurrence.rdates ?? []) if (rdate.getTime() <= to.getTime()) starts.set(rdate.getTime(), rdate);
1794
+ const dayKey = (fields) => `${fields[0]}-${fields[1]}-${fields[2]}`;
1530
1795
  const excludedDays = /* @__PURE__ */ new Set();
1531
1796
  const excludedInstants = /* @__PURE__ */ new Set();
1532
- for (const exdate of event.recurrence.exdates ?? []) if (exdate.getHours() === 0 && exdate.getMinutes() === 0 && exdate.getSeconds() === 0 && exdate.getMilliseconds() === 0) excludedDays.add(dayKey(exdate));
1533
- else excludedInstants.add(exdate.getTime());
1534
- const starts = /* @__PURE__ */ new Map();
1535
- const earliestStart = new Date(rangeStart.getTime() - durationMs);
1536
- for (const start of occurrenceStarts(event.start, event.recurrence, earliestStart, rangeEnd)) starts.set(start.getTime(), start);
1537
- for (const rdate of event.recurrence.rdates ?? []) if (rdate.getTime() <= rangeEnd.getTime()) starts.set(rdate.getTime(), rdate);
1797
+ const startFields = clock.fields(event.start);
1798
+ const rdateTimes = new Set((event.recurrence.rdates ?? []).map((rdate) => rdate.getTime()));
1799
+ for (const exdate of event.recurrence.exdates ?? []) {
1800
+ if (Number.isNaN(exdate.getTime())) continue;
1801
+ const onDevice = DEVICE_CLOCK.fields(exdate);
1802
+ if (!zoned) {
1803
+ if (isMidnight(onDevice)) excludedDays.add(dayKey(onDevice));
1804
+ else excludedInstants.add(exdate.getTime());
1805
+ continue;
1806
+ }
1807
+ const inZone = clock.fields(exdate);
1808
+ excludedInstants.add(exdate.getTime());
1809
+ if (rdateTimes.has(exdate.getTime())) continue;
1810
+ if ([
1811
+ 3,
1812
+ 4,
1813
+ 5,
1814
+ 6
1815
+ ].every((index) => inZone[index] === startFields[index])) continue;
1816
+ if (isMidnight(onDevice)) excludedDays.add(dayKey(onDevice));
1817
+ else if (isMidnight(inZone)) excludedDays.add(dayKey(inZone));
1818
+ }
1538
1819
  const ordered = [...starts.values()].sort((a, b) => a.getTime() - b.getTime());
1539
1820
  for (const start of ordered) {
1540
- if (start.getTime() + durationMs < rangeStart.getTime()) continue;
1541
- if (excludedDays.has(dayKey(start)) || excludedInstants.has(start.getTime())) continue;
1821
+ if (start.getTime() + durationMs < from.getTime()) continue;
1822
+ if (excludedInstants.has(start.getTime())) continue;
1823
+ if (excludedDays.size > 0 && excludedDays.has(dayKey(clock.fields(start)))) continue;
1542
1824
  const instance = instanceAt(event, start, durationMs);
1543
1825
  if (Number.isFinite(instance.end.getTime())) out.push(instance);
1544
1826
  }
@@ -1575,6 +1857,12 @@ Object.defineProperty(exports, "buildMonthWeeks", {
1575
1857
  return buildMonthWeeks;
1576
1858
  }
1577
1859
  });
1860
+ Object.defineProperty(exports, "buildMultiWeekGrid", {
1861
+ enumerable: true,
1862
+ get: function() {
1863
+ return buildMultiWeekGrid;
1864
+ }
1865
+ });
1578
1866
  Object.defineProperty(exports, "cellRangeFromDrag", {
1579
1867
  enumerable: true,
1580
1868
  get: function() {
@@ -1695,6 +1983,18 @@ Object.defineProperty(exports, "formatHour", {
1695
1983
  return formatHour;
1696
1984
  }
1697
1985
  });
1986
+ Object.defineProperty(exports, "fromZonedRange", {
1987
+ enumerable: true,
1988
+ get: function() {
1989
+ return fromZonedRange;
1990
+ }
1991
+ });
1992
+ Object.defineProperty(exports, "fromZonedTime", {
1993
+ enumerable: true,
1994
+ get: function() {
1995
+ return fromZonedTime;
1996
+ }
1997
+ });
1698
1998
  Object.defineProperty(exports, "getIsToday", {
1699
1999
  enumerable: true,
1700
2000
  get: function() {
@@ -1839,6 +2139,12 @@ Object.defineProperty(exports, "nextDateRange", {
1839
2139
  return nextDateRange;
1840
2140
  }
1841
2141
  });
2142
+ Object.defineProperty(exports, "nowInTimeZone", {
2143
+ enumerable: true,
2144
+ get: function() {
2145
+ return nowInTimeZone;
2146
+ }
2147
+ });
1842
2148
  Object.defineProperty(exports, "overlapsOtherEvents", {
1843
2149
  enumerable: true,
1844
2150
  get: function() {
@@ -1935,6 +2241,18 @@ Object.defineProperty(exports, "weekdayFormatToken", {
1935
2241
  return weekdayFormatToken;
1936
2242
  }
1937
2243
  });
2244
+ Object.defineProperty(exports, "zonedDragBounds", {
2245
+ enumerable: true,
2246
+ get: function() {
2247
+ return zonedDragBounds;
2248
+ }
2249
+ });
2250
+ Object.defineProperty(exports, "zonedEventSource", {
2251
+ enumerable: true,
2252
+ get: function() {
2253
+ return zonedEventSource;
2254
+ }
2255
+ });
1938
2256
  Object.defineProperty(exports, "zonedTimeToUtc", {
1939
2257
  enumerable: true,
1940
2258
  get: function() {