@super-calendar/core 2.6.0 → 2.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -19,7 +19,8 @@ const lightColors = {
19
19
  textMuted: "#6B7280",
20
20
  textDisabled: "#B5B9C0",
21
21
  eventBackground: "#DCE7FF",
22
- eventText: "#1A1B1E"
22
+ eventText: "#1A1B1E",
23
+ backgroundEvent: "#E3F4E4"
23
24
  };
24
25
  /** The default dark-theme colour palette. */
25
26
  const darkColors = {
@@ -38,7 +39,8 @@ const darkColors = {
38
39
  textMuted: "#9BA1A6",
39
40
  textDisabled: "#4B4F58",
40
41
  eventBackground: "#243B53",
41
- eventText: "#EAF2FF"
42
+ eventText: "#EAF2FF",
43
+ backgroundEvent: "#17301F"
42
44
  };
43
45
  //#endregion
44
46
  //#region src/presentation.ts
@@ -106,14 +108,23 @@ const weekDaysCount = (weekStartsOn, weekEndsOn) => {
106
108
  * from `weekStartsOn` to `weekEndsOn` (anchored to `date`'s week, paging by week);
107
109
  * otherwise every mode shows `viewDayCount` consecutive days starting at `date`.
108
110
  */
109
- const getViewDays = (mode, date, weekStartsOn, numberOfDays = 1, isRTL = false, weekEndsOn) => {
111
+ const getViewDays = (mode, date, weekStartsOn, numberOfDays = 1, isRTL = false, weekEndsOn, hiddenDays) => {
112
+ const hidden = hiddenDays && hiddenDays.length > 0 && hiddenDays.length < 7 ? hiddenDays : [];
110
113
  let days;
111
- if (mode === "week") days = getWeekDays(date, weekStartsOn);
114
+ if (mode === "week") days = filterHiddenDays(getWeekDays(date, weekStartsOn), hidden);
112
115
  else if (mode === "custom" && weekEndsOn != null) {
113
116
  const subject = (0, date_fns.startOfDay)(date);
114
117
  const offset = weekStartsOn - subject.getDay();
115
- days = Array.from({ length: weekDaysCount(weekStartsOn, weekEndsOn) }, (_, index) => (0, date_fns.addDays)(subject, index + offset));
116
- } else days = Array.from({ length: viewDayCount(mode, numberOfDays) }, (_, index) => (0, date_fns.addDays)((0, date_fns.startOfDay)(date), index));
118
+ days = filterHiddenDays(Array.from({ length: weekDaysCount(weekStartsOn, weekEndsOn) }, (_, index) => (0, date_fns.addDays)(subject, index + offset)), hidden);
119
+ } else {
120
+ const count = viewDayCount(mode, numberOfDays);
121
+ days = [];
122
+ let cursor = (0, date_fns.startOfDay)(date);
123
+ while (days.length < count) {
124
+ if (!hidden.includes(cursor.getDay())) days.push(cursor);
125
+ cursor = (0, date_fns.addDays)(cursor, 1);
126
+ }
127
+ }
117
128
  return isRTL ? days.reverse() : days;
118
129
  };
119
130
  /**
@@ -121,7 +132,7 @@ const getViewDays = (mode, date, weekStartsOn, numberOfDays = 1, isRTL = false,
121
132
  * `weekStartsOn`. `showSixWeeks` always returns six rows (42 days) for a
122
133
  * fixed-height grid; `isRTL` reverses each week's day order.
123
134
  */
124
- const buildMonthWeeks = (month, weekStartsOn, { showSixWeeks = false, isRTL = false } = {}) => {
135
+ const buildMonthWeeks = (month, weekStartsOn, { showSixWeeks = false, isRTL = false, hiddenDays } = {}) => {
125
136
  const start = (0, date_fns.startOfWeek)((0, date_fns.startOfMonth)(month), { weekStartsOn });
126
137
  const days = (0, date_fns.eachDayOfInterval)({
127
138
  start,
@@ -129,11 +140,17 @@ const buildMonthWeeks = (month, weekStartsOn, { showSixWeeks = false, isRTL = fa
129
140
  });
130
141
  const weeks = [];
131
142
  for (let index = 0; index < days.length; index += 7) {
132
- const week = days.slice(index, index + 7);
133
- weeks.push(isRTL ? week.reverse() : week);
143
+ const week = filterHiddenDays(days.slice(index, index + 7), hiddenDays);
144
+ if (week.length > 0) weeks.push(isRTL ? week.reverse() : week);
134
145
  }
135
146
  return weeks;
136
147
  };
148
+ /**
149
+ * Drop the days whose weekday (0=Sunday…6=Saturday) is listed in `hiddenDays`.
150
+ * Hiding all seven weekdays is treated as hiding nothing (matching
151
+ * `getViewDays`), so a misconfiguration degrades to the full grid, not a blank.
152
+ */
153
+ const filterHiddenDays = (days, hiddenDays) => hiddenDays && hiddenDays.length > 0 && new Set(hiddenDays).size < 7 ? days.filter((day) => !hiddenDays.includes(day.getDay())) : days;
137
154
  /** True when `date` is a Saturday or Sunday. */
138
155
  const isWeekend = (date) => {
139
156
  const day = date.getDay();
@@ -261,6 +278,15 @@ function useDateRange(options = {}) {
261
278
  //#endregion
262
279
  //#region src/utils/drag.ts
263
280
  /**
281
+ * How many calendar days one time-grid page spans, used to advance the view by a
282
+ * whole page (e.g. when dragging an event past the edge into the next week).
283
+ * Deliberately ignores `hiddenDays` so a week always steps 7, matching the
284
+ * keyboard PageUp/PageDown paging and `Calendar`'s own page step.
285
+ */
286
+ function pageStepDays(mode, date, weekStartsOn, numberOfDays = 1) {
287
+ return getViewDays(mode, date, weekStartsOn, numberOfDays).length;
288
+ }
289
+ /**
264
290
  * Minutes to shift an event, snapping a vertical pixel drag to the nearest
265
291
  * `stepMinutes`. Runs on the UI thread inside the drag gesture. Returns 0 for a
266
292
  * degenerate grid (non-positive height/step).
@@ -806,6 +832,128 @@ function toICalendar(events, options = {}) {
806
832
  return out.join("\r\n");
807
833
  }
808
834
  //#endregion
835
+ //#region src/utils/useNow.ts
836
+ const MINUTE_MS = 6e4;
837
+ const resolveNow = (now, timeZone) => {
838
+ const instant = now ?? /* @__PURE__ */ new Date();
839
+ return timeZone ? toZonedTime(instant, timeZone) : instant;
840
+ };
841
+ /**
842
+ * The current wall-clock time, re-read every `tickMs` while `enabled`, shifted
843
+ * into `timeZone` when given, or pinned to a fixed `now` override. Drives the
844
+ * now indicator on both renderers so it can't disagree with zone-shifted events.
845
+ */
846
+ function useNow(enabled, { now, timeZone, tickMs = MINUTE_MS } = {}) {
847
+ const [value, setValue] = (0, react.useState)(() => resolveNow(now, timeZone));
848
+ const nowMs = now?.getTime();
849
+ (0, react.useEffect)(() => {
850
+ if (!enabled) return;
851
+ setValue(resolveNow(nowMs != null ? new Date(nowMs) : void 0, timeZone));
852
+ if (nowMs != null) return;
853
+ const id = setInterval(() => setValue(resolveNow(void 0, timeZone)), tickMs);
854
+ return () => clearInterval(id);
855
+ }, [
856
+ enabled,
857
+ nowMs,
858
+ timeZone,
859
+ tickMs
860
+ ]);
861
+ return value;
862
+ }
863
+ //#endregion
864
+ //#region src/utils/useEventSource.ts
865
+ const defaultMap = (items) => items.map((raw) => {
866
+ const item = raw;
867
+ return {
868
+ ...item,
869
+ start: new Date(item.start),
870
+ end: new Date(item.end)
871
+ };
872
+ });
873
+ /**
874
+ * Load events from a refreshable source: a JSON feed URL, an iCalendar feed
875
+ * URL, or your own async function. The hook owns fetching, optional interval
876
+ * refetching, and loading/error state; hand the returned `events` to any view.
877
+ *
878
+ * @example
879
+ * ```tsx
880
+ * const { events, loading, refetch } = useEventSource(
881
+ * "https://example.com/feed.ics",
882
+ * { refetchIntervalMs: 5 * 60_000 },
883
+ * );
884
+ * <Calendar mode="week" date={date} events={events} onChangeDate={setDate} />;
885
+ * ```
886
+ */
887
+ function useEventSource(source, { format, map, refetchIntervalMs } = {}) {
888
+ const [events, setEvents] = (0, react.useState)([]);
889
+ const [loading, setLoading] = (0, react.useState)(true);
890
+ const [error, setError] = (0, react.useState)(null);
891
+ const generation = (0, react.useRef)(0);
892
+ const abortRef = (0, react.useRef)(null);
893
+ const latest = (0, react.useRef)({
894
+ source,
895
+ format,
896
+ map
897
+ });
898
+ latest.current = {
899
+ source,
900
+ format,
901
+ map
902
+ };
903
+ const load = (0, react.useCallback)(async (isManual) => {
904
+ const gen = ++generation.current;
905
+ abortRef.current?.abort();
906
+ const controller = typeof AbortController === "undefined" ? null : new AbortController();
907
+ abortRef.current = controller;
908
+ const { source: src, format: fmt, map: mapper } = latest.current;
909
+ if (isManual) setLoading(true);
910
+ try {
911
+ let next;
912
+ if (typeof src === "function") next = await src();
913
+ else {
914
+ const response = await fetch(src, controller ? { signal: controller.signal } : void 0);
915
+ if (!response.ok) throw new Error(`Event source responded ${response.status}`);
916
+ if (fmt === "ics" || fmt == null && /\.ics(\?|$)/.test(src)) next = parseICalendar(await response.text());
917
+ else {
918
+ const body = await response.json();
919
+ next = (mapper ?? defaultMap)(body);
920
+ }
921
+ }
922
+ if (gen !== generation.current) return;
923
+ setEvents(next);
924
+ setError(null);
925
+ } catch (cause) {
926
+ if (gen !== generation.current) return;
927
+ setError(cause instanceof Error ? cause : new Error(String(cause)));
928
+ } finally {
929
+ if (gen === generation.current) setLoading(false);
930
+ }
931
+ }, []);
932
+ (0, react.useEffect)(() => {
933
+ load(true);
934
+ if (!refetchIntervalMs) return () => {
935
+ generation.current++;
936
+ abortRef.current?.abort();
937
+ };
938
+ const id = setInterval(() => void load(false), refetchIntervalMs);
939
+ return () => {
940
+ clearInterval(id);
941
+ generation.current++;
942
+ abortRef.current?.abort();
943
+ };
944
+ }, [
945
+ load,
946
+ typeof source === "string" ? source : "fn",
947
+ refetchIntervalMs
948
+ ]);
949
+ return {
950
+ events,
951
+ loading,
952
+ error,
953
+ refetch: (0, react.useCallback)(() => load(true), [load])
954
+ };
955
+ }
956
+ //#endregion
809
957
  //#region src/utils/layout.ts
810
958
  const MINUTES_PER_HOUR = 60;
811
959
  const MIN_DURATION_HOURS = .25;
@@ -818,7 +966,7 @@ const MIN_DURATION_HOURS = .25;
818
966
  function layoutDayEvents(events, day) {
819
967
  const dayStart = (0, date_fns.startOfDay)(day);
820
968
  const nextDayStart = (0, date_fns.addDays)(dayStart, 1);
821
- const segments = events.filter((event) => !isAllDayEvent(event)).filter((event) => event.start < nextDayStart && event.end > dayStart).map((event) => {
969
+ const segments = events.filter((event) => !isAllDayEvent(event) && !isBackgroundEvent(event)).filter((event) => event.start < nextDayStart && event.end > dayStart).map((event) => {
822
970
  const segStart = (0, date_fns.max)([event.start, dayStart]);
823
971
  const segEnd = (0, date_fns.min)([event.end, nextDayStart]);
824
972
  return {
@@ -924,23 +1072,63 @@ function closedHourBands(day, businessHours, minHour = 0, maxHour = 24) {
924
1072
  start: minHour,
925
1073
  end: maxHour
926
1074
  }];
927
- const start = Math.max(minHour, Math.min(maxHour, open.start));
928
- const end = Math.max(minHour, Math.min(maxHour, open.end));
929
- if (start >= end) return [{
1075
+ const windows = (Array.isArray(open) ? open : [open]).map((w) => ({
1076
+ start: Math.max(minHour, Math.min(maxHour, w.start)),
1077
+ end: Math.max(minHour, Math.min(maxHour, w.end))
1078
+ })).filter((w) => w.end > w.start).sort((a, b) => a.start - b.start);
1079
+ if (windows.length === 0) return [{
930
1080
  start: minHour,
931
1081
  end: maxHour
932
1082
  }];
1083
+ const merged = [];
1084
+ for (const w of windows) {
1085
+ const last = merged[merged.length - 1];
1086
+ if (last && w.start <= last.end) last.end = Math.max(last.end, w.end);
1087
+ else merged.push({ ...w });
1088
+ }
933
1089
  const bands = [];
934
- if (start > minHour) bands.push({
935
- start: minHour,
936
- end: start
937
- });
938
- if (end < maxHour) bands.push({
939
- start: end,
1090
+ let cursor = minHour;
1091
+ for (const w of merged) {
1092
+ if (w.start > cursor) bands.push({
1093
+ start: cursor,
1094
+ end: w.start
1095
+ });
1096
+ cursor = w.end;
1097
+ }
1098
+ if (cursor < maxHour) bands.push({
1099
+ start: cursor,
940
1100
  end: maxHour
941
1101
  });
942
1102
  return bands;
943
1103
  }
1104
+ /** True when the event paints as a shaded background band, not an event box. */
1105
+ function isBackgroundEvent(event) {
1106
+ return event.display === "background";
1107
+ }
1108
+ /**
1109
+ * The background events of `events` sliced to `day`, as fractional-hour bands
1110
+ * (an all-day or multi-day background covers the day's full window). Shared by
1111
+ * both renderers so the shading can't disagree.
1112
+ */
1113
+ function backgroundBandsForDay(events, day) {
1114
+ const dayStart = (0, date_fns.startOfDay)(day);
1115
+ const nextDayStart = (0, date_fns.addDays)(dayStart, 1);
1116
+ const out = [];
1117
+ for (const event of events) {
1118
+ if (!isBackgroundEvent(event)) continue;
1119
+ if (event.start >= nextDayStart || event.end <= dayStart) continue;
1120
+ const from = event.start > dayStart ? event.start : dayStart;
1121
+ const to = event.end < nextDayStart ? event.end : nextDayStart;
1122
+ const startHours = (from.getTime() - dayStart.getTime()) / 36e5;
1123
+ const endHours = (to.getTime() - dayStart.getTime()) / 36e5;
1124
+ if (endHours > startHours) out.push({
1125
+ event,
1126
+ startHours,
1127
+ endHours
1128
+ });
1129
+ }
1130
+ return out;
1131
+ }
944
1132
  //#endregion
945
1133
  //#region src/utils/monthGrid.ts
946
1134
  /** date-fns tokens for each {@link WeekdayFormat}. */
@@ -963,31 +1151,37 @@ function weekdayFormatToken(format) {
963
1151
  * data outside React; inside a component prefer {@link useMonthGrid}.
964
1152
  */
965
1153
  function buildMonthGrid(month, options = {}) {
966
- const { weekStartsOn = 0, weekdayFormat = "short", showSixWeeks = false, isRTL = false, selectedDates, selectedRange, minDate, maxDate, isDateDisabled, locale } = options;
1154
+ const { weekStartsOn = 0, weekdayFormat = "short", showSixWeeks = false, isRTL = false, hiddenDays, selectedDates, selectedRange, minDate, maxDate, isDateDisabled, locale } = options;
967
1155
  const rows = buildMonthWeeks(month, weekStartsOn, {
968
1156
  showSixWeeks,
969
- isRTL
1157
+ isRTL,
1158
+ hiddenDays
970
1159
  });
1160
+ const weeks = rows.map((days) => ({
1161
+ id: days[0].toISOString(),
1162
+ days: days.map((date) => ({
1163
+ date,
1164
+ id: (0, date_fns.format)(date, "yyyy-MM-dd"),
1165
+ label: (0, date_fns.format)(date, "d"),
1166
+ isCurrentMonth: (0, date_fns.isSameMonth)(date, month),
1167
+ isToday: getIsToday(date),
1168
+ isWeekend: isWeekend(date),
1169
+ ...daySelectionState(date, {
1170
+ selectedDates,
1171
+ selectedRange
1172
+ }, {
1173
+ minDate,
1174
+ maxDate,
1175
+ isDateDisabled
1176
+ })
1177
+ }))
1178
+ }));
1179
+ if (rows.length === 0) return {
1180
+ weeks: [],
1181
+ weekdays: []
1182
+ };
971
1183
  return {
972
- weeks: rows.map((days) => ({
973
- id: days[0].toISOString(),
974
- days: days.map((date) => ({
975
- date,
976
- id: (0, date_fns.format)(date, "yyyy-MM-dd"),
977
- label: (0, date_fns.format)(date, "d"),
978
- isCurrentMonth: (0, date_fns.isSameMonth)(date, month),
979
- isToday: getIsToday(date),
980
- isWeekend: isWeekend(date),
981
- ...daySelectionState(date, {
982
- selectedDates,
983
- selectedRange
984
- }, {
985
- minDate,
986
- maxDate,
987
- isDateDisabled
988
- })
989
- }))
990
- })),
1184
+ weeks,
991
1185
  weekdays: rows[0].map((date) => ({
992
1186
  date,
993
1187
  label: (0, date_fns.format)(date, WEEKDAY_TOKENS[weekdayFormat], { locale })
@@ -1181,7 +1375,10 @@ function expandRecurringEvents(events, rangeStart, rangeEnd) {
1181
1375
  }
1182
1376
  const durationMs = event.end.getTime() - event.start.getTime();
1183
1377
  const dayKey = (d) => `${d.getFullYear()}-${d.getMonth()}-${d.getDate()}`;
1184
- const excluded = new Set((event.recurrence.exdates ?? []).map(dayKey));
1378
+ const excludedDays = /* @__PURE__ */ new Set();
1379
+ const excludedInstants = /* @__PURE__ */ new Set();
1380
+ for (const exdate of event.recurrence.exdates ?? []) if (exdate.getHours() === 0 && exdate.getMinutes() === 0 && exdate.getSeconds() === 0 && exdate.getMilliseconds() === 0) excludedDays.add(dayKey(exdate));
1381
+ else excludedInstants.add(exdate.getTime());
1185
1382
  const starts = /* @__PURE__ */ new Map();
1186
1383
  const earliestStart = new Date(rangeStart.getTime() - durationMs);
1187
1384
  for (const start of occurrenceStarts(event.start, event.recurrence, earliestStart, rangeEnd)) starts.set(start.getTime(), start);
@@ -1189,7 +1386,7 @@ function expandRecurringEvents(events, rangeStart, rangeEnd) {
1189
1386
  const ordered = [...starts.values()].sort((a, b) => a.getTime() - b.getTime());
1190
1387
  for (const start of ordered) {
1191
1388
  if (start.getTime() + durationMs < rangeStart.getTime()) continue;
1192
- if (excluded.has(dayKey(start))) continue;
1389
+ if (excludedDays.has(dayKey(start)) || excludedInstants.has(start.getTime())) continue;
1193
1390
  out.push(instanceAt(event, start, durationMs));
1194
1391
  }
1195
1392
  }
@@ -1198,6 +1395,7 @@ function expandRecurringEvents(events, rangeStart, rangeEnd) {
1198
1395
  //#endregion
1199
1396
  exports.CalendarSelectionProvider = CalendarSelectionProvider;
1200
1397
  exports.MIN_BOX_HEIGHT_FOR_TIME = MIN_BOX_HEIGHT_FOR_TIME;
1398
+ exports.backgroundBandsForDay = backgroundBandsForDay;
1201
1399
  exports.bandRounding = bandRounding;
1202
1400
  exports.buildMonthGrid = buildMonthGrid;
1203
1401
  exports.buildMonthWeeks = buildMonthWeeks;
@@ -1213,6 +1411,7 @@ exports.eventDayKeys = eventDayKeys;
1213
1411
  exports.eventTimeLabel = eventTimeLabel;
1214
1412
  exports.eventsInTimeZone = eventsInTimeZone;
1215
1413
  exports.expandRecurringEvents = expandRecurringEvents;
1414
+ exports.filterHiddenDays = filterHiddenDays;
1216
1415
  exports.formatHour = formatHour;
1217
1416
  exports.getIsToday = getIsToday;
1218
1417
  exports.getViewDays = getViewDays;
@@ -1220,6 +1419,7 @@ exports.getWeekDays = getWeekDays;
1220
1419
  exports.getYearMonths = getYearMonths;
1221
1420
  exports.groupEventsByDay = groupEventsByDay;
1222
1421
  exports.isAllDayEvent = isAllDayEvent;
1422
+ exports.isBackgroundEvent = isBackgroundEvent;
1223
1423
  exports.isDateSelectable = isDateSelectable;
1224
1424
  exports.isRangeEndpoint = isRangeEndpoint;
1225
1425
  exports.isSameCalendarDay = isSameCalendarDay;
@@ -1232,6 +1432,7 @@ exports.minutesIntoDay = minutesIntoDay;
1232
1432
  exports.monthEventCapacity = monthEventCapacity;
1233
1433
  exports.monthVisibleCount = monthVisibleCount;
1234
1434
  exports.nextDateRange = nextDateRange;
1435
+ exports.pageStepDays = pageStepDays;
1235
1436
  exports.parseICalendar = parseICalendar;
1236
1437
  exports.rangeBandKind = rangeBandKind;
1237
1438
  exports.resolveDraggedBounds = resolveDraggedBounds;
@@ -1243,7 +1444,9 @@ exports.toICalendar = toICalendar;
1243
1444
  exports.toZonedTime = toZonedTime;
1244
1445
  exports.useCalendarSelection = useCalendarSelection;
1245
1446
  exports.useDateRange = useDateRange;
1447
+ exports.useEventSource = useEventSource;
1246
1448
  exports.useMonthGrid = useMonthGrid;
1449
+ exports.useNow = useNow;
1247
1450
  exports.viewDayCount = viewDayCount;
1248
1451
  exports.weekDaysCount = weekDaysCount;
1249
1452
  exports.weekdayFormatToken = weekdayFormatToken;