@super-calendar/core 2.5.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();
@@ -145,6 +162,8 @@ const getIsToday = (date) => (0, date_fns.isToday)(date);
145
162
  const isSameCalendarDay = (a, b) => (0, date_fns.isSameDay)(a, b);
146
163
  /** Minutes elapsed since midnight (0–1439). */
147
164
  const minutesIntoDay = (date) => (0, date_fns.getHours)(date) * 60 + (0, date_fns.getMinutes)(date);
165
+ /** The twelve month anchors (first-of-month) of `date`'s year, January first. */
166
+ const getYearMonths = (date) => Array.from({ length: 12 }, (_, i) => new Date(date.getFullYear(), i, 1));
148
167
  //#endregion
149
168
  //#region src/utils/dateRange.ts
150
169
  /** Whether `date` passes the min/max/disabled constraints (compared by calendar day). */
@@ -259,6 +278,15 @@ function useDateRange(options = {}) {
259
278
  //#endregion
260
279
  //#region src/utils/drag.ts
261
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
+ /**
262
290
  * Minutes to shift an event, snapping a vertical pixel drag to the nearest
263
291
  * `stepMinutes`. Runs on the UI thread inside the drag gesture. Returns 0 for a
264
292
  * degenerate grid (non-positive height/step).
@@ -804,6 +832,128 @@ function toICalendar(events, options = {}) {
804
832
  return out.join("\r\n");
805
833
  }
806
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
807
957
  //#region src/utils/layout.ts
808
958
  const MINUTES_PER_HOUR = 60;
809
959
  const MIN_DURATION_HOURS = .25;
@@ -816,7 +966,7 @@ const MIN_DURATION_HOURS = .25;
816
966
  function layoutDayEvents(events, day) {
817
967
  const dayStart = (0, date_fns.startOfDay)(day);
818
968
  const nextDayStart = (0, date_fns.addDays)(dayStart, 1);
819
- 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) => {
820
970
  const segStart = (0, date_fns.max)([event.start, dayStart]);
821
971
  const segEnd = (0, date_fns.min)([event.end, nextDayStart]);
822
972
  return {
@@ -922,23 +1072,63 @@ function closedHourBands(day, businessHours, minHour = 0, maxHour = 24) {
922
1072
  start: minHour,
923
1073
  end: maxHour
924
1074
  }];
925
- const start = Math.max(minHour, Math.min(maxHour, open.start));
926
- const end = Math.max(minHour, Math.min(maxHour, open.end));
927
- 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 [{
928
1080
  start: minHour,
929
1081
  end: maxHour
930
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
+ }
931
1089
  const bands = [];
932
- if (start > minHour) bands.push({
933
- start: minHour,
934
- end: start
935
- });
936
- if (end < maxHour) bands.push({
937
- 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,
938
1100
  end: maxHour
939
1101
  });
940
1102
  return bands;
941
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
+ }
942
1132
  //#endregion
943
1133
  //#region src/utils/monthGrid.ts
944
1134
  /** date-fns tokens for each {@link WeekdayFormat}. */
@@ -961,31 +1151,37 @@ function weekdayFormatToken(format) {
961
1151
  * data outside React; inside a component prefer {@link useMonthGrid}.
962
1152
  */
963
1153
  function buildMonthGrid(month, options = {}) {
964
- 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;
965
1155
  const rows = buildMonthWeeks(month, weekStartsOn, {
966
1156
  showSixWeeks,
967
- isRTL
1157
+ isRTL,
1158
+ hiddenDays
968
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
+ };
969
1183
  return {
970
- weeks: rows.map((days) => ({
971
- id: days[0].toISOString(),
972
- days: days.map((date) => ({
973
- date,
974
- id: (0, date_fns.format)(date, "yyyy-MM-dd"),
975
- label: (0, date_fns.format)(date, "d"),
976
- isCurrentMonth: (0, date_fns.isSameMonth)(date, month),
977
- isToday: getIsToday(date),
978
- isWeekend: isWeekend(date),
979
- ...daySelectionState(date, {
980
- selectedDates,
981
- selectedRange
982
- }, {
983
- minDate,
984
- maxDate,
985
- isDateDisabled
986
- })
987
- }))
988
- })),
1184
+ weeks,
989
1185
  weekdays: rows[0].map((date) => ({
990
1186
  date,
991
1187
  label: (0, date_fns.format)(date, WEEKDAY_TOKENS[weekdayFormat], { locale })
@@ -1179,7 +1375,10 @@ function expandRecurringEvents(events, rangeStart, rangeEnd) {
1179
1375
  }
1180
1376
  const durationMs = event.end.getTime() - event.start.getTime();
1181
1377
  const dayKey = (d) => `${d.getFullYear()}-${d.getMonth()}-${d.getDate()}`;
1182
- 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());
1183
1382
  const starts = /* @__PURE__ */ new Map();
1184
1383
  const earliestStart = new Date(rangeStart.getTime() - durationMs);
1185
1384
  for (const start of occurrenceStarts(event.start, event.recurrence, earliestStart, rangeEnd)) starts.set(start.getTime(), start);
@@ -1187,7 +1386,7 @@ function expandRecurringEvents(events, rangeStart, rangeEnd) {
1187
1386
  const ordered = [...starts.values()].sort((a, b) => a.getTime() - b.getTime());
1188
1387
  for (const start of ordered) {
1189
1388
  if (start.getTime() + durationMs < rangeStart.getTime()) continue;
1190
- if (excluded.has(dayKey(start))) continue;
1389
+ if (excludedDays.has(dayKey(start)) || excludedInstants.has(start.getTime())) continue;
1191
1390
  out.push(instanceAt(event, start, durationMs));
1192
1391
  }
1193
1392
  }
@@ -1196,6 +1395,7 @@ function expandRecurringEvents(events, rangeStart, rangeEnd) {
1196
1395
  //#endregion
1197
1396
  exports.CalendarSelectionProvider = CalendarSelectionProvider;
1198
1397
  exports.MIN_BOX_HEIGHT_FOR_TIME = MIN_BOX_HEIGHT_FOR_TIME;
1398
+ exports.backgroundBandsForDay = backgroundBandsForDay;
1199
1399
  exports.bandRounding = bandRounding;
1200
1400
  exports.buildMonthGrid = buildMonthGrid;
1201
1401
  exports.buildMonthWeeks = buildMonthWeeks;
@@ -1211,12 +1411,15 @@ exports.eventDayKeys = eventDayKeys;
1211
1411
  exports.eventTimeLabel = eventTimeLabel;
1212
1412
  exports.eventsInTimeZone = eventsInTimeZone;
1213
1413
  exports.expandRecurringEvents = expandRecurringEvents;
1414
+ exports.filterHiddenDays = filterHiddenDays;
1214
1415
  exports.formatHour = formatHour;
1215
1416
  exports.getIsToday = getIsToday;
1216
1417
  exports.getViewDays = getViewDays;
1217
1418
  exports.getWeekDays = getWeekDays;
1419
+ exports.getYearMonths = getYearMonths;
1218
1420
  exports.groupEventsByDay = groupEventsByDay;
1219
1421
  exports.isAllDayEvent = isAllDayEvent;
1422
+ exports.isBackgroundEvent = isBackgroundEvent;
1220
1423
  exports.isDateSelectable = isDateSelectable;
1221
1424
  exports.isRangeEndpoint = isRangeEndpoint;
1222
1425
  exports.isSameCalendarDay = isSameCalendarDay;
@@ -1229,6 +1432,7 @@ exports.minutesIntoDay = minutesIntoDay;
1229
1432
  exports.monthEventCapacity = monthEventCapacity;
1230
1433
  exports.monthVisibleCount = monthVisibleCount;
1231
1434
  exports.nextDateRange = nextDateRange;
1435
+ exports.pageStepDays = pageStepDays;
1232
1436
  exports.parseICalendar = parseICalendar;
1233
1437
  exports.rangeBandKind = rangeBandKind;
1234
1438
  exports.resolveDraggedBounds = resolveDraggedBounds;
@@ -1240,7 +1444,9 @@ exports.toICalendar = toICalendar;
1240
1444
  exports.toZonedTime = toZonedTime;
1241
1445
  exports.useCalendarSelection = useCalendarSelection;
1242
1446
  exports.useDateRange = useDateRange;
1447
+ exports.useEventSource = useEventSource;
1243
1448
  exports.useMonthGrid = useMonthGrid;
1449
+ exports.useNow = useNow;
1244
1450
  exports.viewDayCount = viewDayCount;
1245
1451
  exports.weekDaysCount = weekDaysCount;
1246
1452
  exports.weekdayFormatToken = weekdayFormatToken;