@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.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  import { addDays, addMonths, addWeeks, addYears, differenceInMinutes, eachDayOfInterval, endOfMonth, endOfWeek, format, getHours, getMinutes, isAfter, isBefore, isSameDay, isSameMonth, isToday, max, min, startOfDay, startOfMonth, startOfWeek } from "date-fns";
2
- import { createContext, useCallback, useContext, useMemo, useState } from "react";
2
+ import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState } from "react";
3
3
  //#region src/tokens.ts
4
4
  /** The default light-theme colour palette. */
5
5
  const lightColors = {
@@ -18,7 +18,8 @@ const lightColors = {
18
18
  textMuted: "#6B7280",
19
19
  textDisabled: "#B5B9C0",
20
20
  eventBackground: "#DCE7FF",
21
- eventText: "#1A1B1E"
21
+ eventText: "#1A1B1E",
22
+ backgroundEvent: "#E3F4E4"
22
23
  };
23
24
  /** The default dark-theme colour palette. */
24
25
  const darkColors = {
@@ -37,7 +38,8 @@ const darkColors = {
37
38
  textMuted: "#9BA1A6",
38
39
  textDisabled: "#4B4F58",
39
40
  eventBackground: "#243B53",
40
- eventText: "#EAF2FF"
41
+ eventText: "#EAF2FF",
42
+ backgroundEvent: "#17301F"
41
43
  };
42
44
  //#endregion
43
45
  //#region src/presentation.ts
@@ -105,14 +107,23 @@ const weekDaysCount = (weekStartsOn, weekEndsOn) => {
105
107
  * from `weekStartsOn` to `weekEndsOn` (anchored to `date`'s week, paging by week);
106
108
  * otherwise every mode shows `viewDayCount` consecutive days starting at `date`.
107
109
  */
108
- const getViewDays = (mode, date, weekStartsOn, numberOfDays = 1, isRTL = false, weekEndsOn) => {
110
+ const getViewDays = (mode, date, weekStartsOn, numberOfDays = 1, isRTL = false, weekEndsOn, hiddenDays) => {
111
+ const hidden = hiddenDays && hiddenDays.length > 0 && hiddenDays.length < 7 ? hiddenDays : [];
109
112
  let days;
110
- if (mode === "week") days = getWeekDays(date, weekStartsOn);
113
+ if (mode === "week") days = filterHiddenDays(getWeekDays(date, weekStartsOn), hidden);
111
114
  else if (mode === "custom" && weekEndsOn != null) {
112
115
  const subject = startOfDay(date);
113
116
  const offset = weekStartsOn - subject.getDay();
114
- days = Array.from({ length: weekDaysCount(weekStartsOn, weekEndsOn) }, (_, index) => addDays(subject, index + offset));
115
- } else days = Array.from({ length: viewDayCount(mode, numberOfDays) }, (_, index) => addDays(startOfDay(date), index));
117
+ days = filterHiddenDays(Array.from({ length: weekDaysCount(weekStartsOn, weekEndsOn) }, (_, index) => addDays(subject, index + offset)), hidden);
118
+ } else {
119
+ const count = viewDayCount(mode, numberOfDays);
120
+ days = [];
121
+ let cursor = startOfDay(date);
122
+ while (days.length < count) {
123
+ if (!hidden.includes(cursor.getDay())) days.push(cursor);
124
+ cursor = addDays(cursor, 1);
125
+ }
126
+ }
116
127
  return isRTL ? days.reverse() : days;
117
128
  };
118
129
  /**
@@ -120,7 +131,7 @@ const getViewDays = (mode, date, weekStartsOn, numberOfDays = 1, isRTL = false,
120
131
  * `weekStartsOn`. `showSixWeeks` always returns six rows (42 days) for a
121
132
  * fixed-height grid; `isRTL` reverses each week's day order.
122
133
  */
123
- const buildMonthWeeks = (month, weekStartsOn, { showSixWeeks = false, isRTL = false } = {}) => {
134
+ const buildMonthWeeks = (month, weekStartsOn, { showSixWeeks = false, isRTL = false, hiddenDays } = {}) => {
124
135
  const start = startOfWeek(startOfMonth(month), { weekStartsOn });
125
136
  const days = eachDayOfInterval({
126
137
  start,
@@ -128,11 +139,17 @@ const buildMonthWeeks = (month, weekStartsOn, { showSixWeeks = false, isRTL = fa
128
139
  });
129
140
  const weeks = [];
130
141
  for (let index = 0; index < days.length; index += 7) {
131
- const week = days.slice(index, index + 7);
132
- weeks.push(isRTL ? week.reverse() : week);
142
+ const week = filterHiddenDays(days.slice(index, index + 7), hiddenDays);
143
+ if (week.length > 0) weeks.push(isRTL ? week.reverse() : week);
133
144
  }
134
145
  return weeks;
135
146
  };
147
+ /**
148
+ * Drop the days whose weekday (0=Sunday…6=Saturday) is listed in `hiddenDays`.
149
+ * Hiding all seven weekdays is treated as hiding nothing (matching
150
+ * `getViewDays`), so a misconfiguration degrades to the full grid, not a blank.
151
+ */
152
+ const filterHiddenDays = (days, hiddenDays) => hiddenDays && hiddenDays.length > 0 && new Set(hiddenDays).size < 7 ? days.filter((day) => !hiddenDays.includes(day.getDay())) : days;
136
153
  /** True when `date` is a Saturday or Sunday. */
137
154
  const isWeekend = (date) => {
138
155
  const day = date.getDay();
@@ -260,6 +277,15 @@ function useDateRange(options = {}) {
260
277
  //#endregion
261
278
  //#region src/utils/drag.ts
262
279
  /**
280
+ * How many calendar days one time-grid page spans, used to advance the view by a
281
+ * whole page (e.g. when dragging an event past the edge into the next week).
282
+ * Deliberately ignores `hiddenDays` so a week always steps 7, matching the
283
+ * keyboard PageUp/PageDown paging and `Calendar`'s own page step.
284
+ */
285
+ function pageStepDays(mode, date, weekStartsOn, numberOfDays = 1) {
286
+ return getViewDays(mode, date, weekStartsOn, numberOfDays).length;
287
+ }
288
+ /**
263
289
  * Minutes to shift an event, snapping a vertical pixel drag to the nearest
264
290
  * `stepMinutes`. Runs on the UI thread inside the drag gesture. Returns 0 for a
265
291
  * degenerate grid (non-positive height/step).
@@ -805,6 +831,128 @@ function toICalendar(events, options = {}) {
805
831
  return out.join("\r\n");
806
832
  }
807
833
  //#endregion
834
+ //#region src/utils/useNow.ts
835
+ const MINUTE_MS = 6e4;
836
+ const resolveNow = (now, timeZone) => {
837
+ const instant = now ?? /* @__PURE__ */ new Date();
838
+ return timeZone ? toZonedTime(instant, timeZone) : instant;
839
+ };
840
+ /**
841
+ * The current wall-clock time, re-read every `tickMs` while `enabled`, shifted
842
+ * into `timeZone` when given, or pinned to a fixed `now` override. Drives the
843
+ * now indicator on both renderers so it can't disagree with zone-shifted events.
844
+ */
845
+ function useNow(enabled, { now, timeZone, tickMs = MINUTE_MS } = {}) {
846
+ const [value, setValue] = useState(() => resolveNow(now, timeZone));
847
+ const nowMs = now?.getTime();
848
+ useEffect(() => {
849
+ if (!enabled) return;
850
+ setValue(resolveNow(nowMs != null ? new Date(nowMs) : void 0, timeZone));
851
+ if (nowMs != null) return;
852
+ const id = setInterval(() => setValue(resolveNow(void 0, timeZone)), tickMs);
853
+ return () => clearInterval(id);
854
+ }, [
855
+ enabled,
856
+ nowMs,
857
+ timeZone,
858
+ tickMs
859
+ ]);
860
+ return value;
861
+ }
862
+ //#endregion
863
+ //#region src/utils/useEventSource.ts
864
+ const defaultMap = (items) => items.map((raw) => {
865
+ const item = raw;
866
+ return {
867
+ ...item,
868
+ start: new Date(item.start),
869
+ end: new Date(item.end)
870
+ };
871
+ });
872
+ /**
873
+ * Load events from a refreshable source: a JSON feed URL, an iCalendar feed
874
+ * URL, or your own async function. The hook owns fetching, optional interval
875
+ * refetching, and loading/error state; hand the returned `events` to any view.
876
+ *
877
+ * @example
878
+ * ```tsx
879
+ * const { events, loading, refetch } = useEventSource(
880
+ * "https://example.com/feed.ics",
881
+ * { refetchIntervalMs: 5 * 60_000 },
882
+ * );
883
+ * <Calendar mode="week" date={date} events={events} onChangeDate={setDate} />;
884
+ * ```
885
+ */
886
+ function useEventSource(source, { format, map, refetchIntervalMs } = {}) {
887
+ const [events, setEvents] = useState([]);
888
+ const [loading, setLoading] = useState(true);
889
+ const [error, setError] = useState(null);
890
+ const generation = useRef(0);
891
+ const abortRef = useRef(null);
892
+ const latest = useRef({
893
+ source,
894
+ format,
895
+ map
896
+ });
897
+ latest.current = {
898
+ source,
899
+ format,
900
+ map
901
+ };
902
+ const load = useCallback(async (isManual) => {
903
+ const gen = ++generation.current;
904
+ abortRef.current?.abort();
905
+ const controller = typeof AbortController === "undefined" ? null : new AbortController();
906
+ abortRef.current = controller;
907
+ const { source: src, format: fmt, map: mapper } = latest.current;
908
+ if (isManual) setLoading(true);
909
+ try {
910
+ let next;
911
+ if (typeof src === "function") next = await src();
912
+ else {
913
+ const response = await fetch(src, controller ? { signal: controller.signal } : void 0);
914
+ if (!response.ok) throw new Error(`Event source responded ${response.status}`);
915
+ if (fmt === "ics" || fmt == null && /\.ics(\?|$)/.test(src)) next = parseICalendar(await response.text());
916
+ else {
917
+ const body = await response.json();
918
+ next = (mapper ?? defaultMap)(body);
919
+ }
920
+ }
921
+ if (gen !== generation.current) return;
922
+ setEvents(next);
923
+ setError(null);
924
+ } catch (cause) {
925
+ if (gen !== generation.current) return;
926
+ setError(cause instanceof Error ? cause : new Error(String(cause)));
927
+ } finally {
928
+ if (gen === generation.current) setLoading(false);
929
+ }
930
+ }, []);
931
+ useEffect(() => {
932
+ load(true);
933
+ if (!refetchIntervalMs) return () => {
934
+ generation.current++;
935
+ abortRef.current?.abort();
936
+ };
937
+ const id = setInterval(() => void load(false), refetchIntervalMs);
938
+ return () => {
939
+ clearInterval(id);
940
+ generation.current++;
941
+ abortRef.current?.abort();
942
+ };
943
+ }, [
944
+ load,
945
+ typeof source === "string" ? source : "fn",
946
+ refetchIntervalMs
947
+ ]);
948
+ return {
949
+ events,
950
+ loading,
951
+ error,
952
+ refetch: useCallback(() => load(true), [load])
953
+ };
954
+ }
955
+ //#endregion
808
956
  //#region src/utils/layout.ts
809
957
  const MINUTES_PER_HOUR = 60;
810
958
  const MIN_DURATION_HOURS = .25;
@@ -817,7 +965,7 @@ const MIN_DURATION_HOURS = .25;
817
965
  function layoutDayEvents(events, day) {
818
966
  const dayStart = startOfDay(day);
819
967
  const nextDayStart = addDays(dayStart, 1);
820
- const segments = events.filter((event) => !isAllDayEvent(event)).filter((event) => event.start < nextDayStart && event.end > dayStart).map((event) => {
968
+ const segments = events.filter((event) => !isAllDayEvent(event) && !isBackgroundEvent(event)).filter((event) => event.start < nextDayStart && event.end > dayStart).map((event) => {
821
969
  const segStart = max([event.start, dayStart]);
822
970
  const segEnd = min([event.end, nextDayStart]);
823
971
  return {
@@ -923,23 +1071,63 @@ function closedHourBands(day, businessHours, minHour = 0, maxHour = 24) {
923
1071
  start: minHour,
924
1072
  end: maxHour
925
1073
  }];
926
- const start = Math.max(minHour, Math.min(maxHour, open.start));
927
- const end = Math.max(minHour, Math.min(maxHour, open.end));
928
- if (start >= end) return [{
1074
+ const windows = (Array.isArray(open) ? open : [open]).map((w) => ({
1075
+ start: Math.max(minHour, Math.min(maxHour, w.start)),
1076
+ end: Math.max(minHour, Math.min(maxHour, w.end))
1077
+ })).filter((w) => w.end > w.start).sort((a, b) => a.start - b.start);
1078
+ if (windows.length === 0) return [{
929
1079
  start: minHour,
930
1080
  end: maxHour
931
1081
  }];
1082
+ const merged = [];
1083
+ for (const w of windows) {
1084
+ const last = merged[merged.length - 1];
1085
+ if (last && w.start <= last.end) last.end = Math.max(last.end, w.end);
1086
+ else merged.push({ ...w });
1087
+ }
932
1088
  const bands = [];
933
- if (start > minHour) bands.push({
934
- start: minHour,
935
- end: start
936
- });
937
- if (end < maxHour) bands.push({
938
- start: end,
1089
+ let cursor = minHour;
1090
+ for (const w of merged) {
1091
+ if (w.start > cursor) bands.push({
1092
+ start: cursor,
1093
+ end: w.start
1094
+ });
1095
+ cursor = w.end;
1096
+ }
1097
+ if (cursor < maxHour) bands.push({
1098
+ start: cursor,
939
1099
  end: maxHour
940
1100
  });
941
1101
  return bands;
942
1102
  }
1103
+ /** True when the event paints as a shaded background band, not an event box. */
1104
+ function isBackgroundEvent(event) {
1105
+ return event.display === "background";
1106
+ }
1107
+ /**
1108
+ * The background events of `events` sliced to `day`, as fractional-hour bands
1109
+ * (an all-day or multi-day background covers the day's full window). Shared by
1110
+ * both renderers so the shading can't disagree.
1111
+ */
1112
+ function backgroundBandsForDay(events, day) {
1113
+ const dayStart = startOfDay(day);
1114
+ const nextDayStart = addDays(dayStart, 1);
1115
+ const out = [];
1116
+ for (const event of events) {
1117
+ if (!isBackgroundEvent(event)) continue;
1118
+ if (event.start >= nextDayStart || event.end <= dayStart) continue;
1119
+ const from = event.start > dayStart ? event.start : dayStart;
1120
+ const to = event.end < nextDayStart ? event.end : nextDayStart;
1121
+ const startHours = (from.getTime() - dayStart.getTime()) / 36e5;
1122
+ const endHours = (to.getTime() - dayStart.getTime()) / 36e5;
1123
+ if (endHours > startHours) out.push({
1124
+ event,
1125
+ startHours,
1126
+ endHours
1127
+ });
1128
+ }
1129
+ return out;
1130
+ }
943
1131
  //#endregion
944
1132
  //#region src/utils/monthGrid.ts
945
1133
  /** date-fns tokens for each {@link WeekdayFormat}. */
@@ -962,31 +1150,37 @@ function weekdayFormatToken(format) {
962
1150
  * data outside React; inside a component prefer {@link useMonthGrid}.
963
1151
  */
964
1152
  function buildMonthGrid(month, options = {}) {
965
- const { weekStartsOn = 0, weekdayFormat = "short", showSixWeeks = false, isRTL = false, selectedDates, selectedRange, minDate, maxDate, isDateDisabled, locale } = options;
1153
+ const { weekStartsOn = 0, weekdayFormat = "short", showSixWeeks = false, isRTL = false, hiddenDays, selectedDates, selectedRange, minDate, maxDate, isDateDisabled, locale } = options;
966
1154
  const rows = buildMonthWeeks(month, weekStartsOn, {
967
1155
  showSixWeeks,
968
- isRTL
1156
+ isRTL,
1157
+ hiddenDays
969
1158
  });
1159
+ const weeks = rows.map((days) => ({
1160
+ id: days[0].toISOString(),
1161
+ days: days.map((date) => ({
1162
+ date,
1163
+ id: format(date, "yyyy-MM-dd"),
1164
+ label: format(date, "d"),
1165
+ isCurrentMonth: isSameMonth(date, month),
1166
+ isToday: getIsToday(date),
1167
+ isWeekend: isWeekend(date),
1168
+ ...daySelectionState(date, {
1169
+ selectedDates,
1170
+ selectedRange
1171
+ }, {
1172
+ minDate,
1173
+ maxDate,
1174
+ isDateDisabled
1175
+ })
1176
+ }))
1177
+ }));
1178
+ if (rows.length === 0) return {
1179
+ weeks: [],
1180
+ weekdays: []
1181
+ };
970
1182
  return {
971
- weeks: rows.map((days) => ({
972
- id: days[0].toISOString(),
973
- days: days.map((date) => ({
974
- date,
975
- id: format(date, "yyyy-MM-dd"),
976
- label: format(date, "d"),
977
- isCurrentMonth: isSameMonth(date, month),
978
- isToday: getIsToday(date),
979
- isWeekend: isWeekend(date),
980
- ...daySelectionState(date, {
981
- selectedDates,
982
- selectedRange
983
- }, {
984
- minDate,
985
- maxDate,
986
- isDateDisabled
987
- })
988
- }))
989
- })),
1183
+ weeks,
990
1184
  weekdays: rows[0].map((date) => ({
991
1185
  date,
992
1186
  label: format(date, WEEKDAY_TOKENS[weekdayFormat], { locale })
@@ -1180,7 +1374,10 @@ function expandRecurringEvents(events, rangeStart, rangeEnd) {
1180
1374
  }
1181
1375
  const durationMs = event.end.getTime() - event.start.getTime();
1182
1376
  const dayKey = (d) => `${d.getFullYear()}-${d.getMonth()}-${d.getDate()}`;
1183
- const excluded = new Set((event.recurrence.exdates ?? []).map(dayKey));
1377
+ const excludedDays = /* @__PURE__ */ new Set();
1378
+ const excludedInstants = /* @__PURE__ */ new Set();
1379
+ for (const exdate of event.recurrence.exdates ?? []) if (exdate.getHours() === 0 && exdate.getMinutes() === 0 && exdate.getSeconds() === 0 && exdate.getMilliseconds() === 0) excludedDays.add(dayKey(exdate));
1380
+ else excludedInstants.add(exdate.getTime());
1184
1381
  const starts = /* @__PURE__ */ new Map();
1185
1382
  const earliestStart = new Date(rangeStart.getTime() - durationMs);
1186
1383
  for (const start of occurrenceStarts(event.start, event.recurrence, earliestStart, rangeEnd)) starts.set(start.getTime(), start);
@@ -1188,11 +1385,11 @@ function expandRecurringEvents(events, rangeStart, rangeEnd) {
1188
1385
  const ordered = [...starts.values()].sort((a, b) => a.getTime() - b.getTime());
1189
1386
  for (const start of ordered) {
1190
1387
  if (start.getTime() + durationMs < rangeStart.getTime()) continue;
1191
- if (excluded.has(dayKey(start))) continue;
1388
+ if (excludedDays.has(dayKey(start)) || excludedInstants.has(start.getTime())) continue;
1192
1389
  out.push(instanceAt(event, start, durationMs));
1193
1390
  }
1194
1391
  }
1195
1392
  return out;
1196
1393
  }
1197
1394
  //#endregion
1198
- export { CalendarSelectionProvider, MIN_BOX_HEIGHT_FOR_TIME, bandRounding, buildMonthGrid, buildMonthWeeks, cellRangeFromDrag, closedHourBands, compareDayEvents, darkColors, dayBadgeKind, daySelectionState, eventAccessibilityLabel, eventChipLayout, eventDayKeys, eventTimeLabel, eventsInTimeZone, expandRecurringEvents, formatHour, getIsToday, getViewDays, getWeekDays, getYearMonths, groupEventsByDay, isAllDayEvent, isDateSelectable, isRangeEndpoint, isSameCalendarDay, isTimeVisibleAtHeight, isWeekend, isWithinDateRange, layoutDayEvents, lightColors, minutesIntoDay, monthEventCapacity, monthVisibleCount, nextDateRange, parseICalendar, rangeBandKind, resolveDraggedBounds, shiftMinutes, snapDeltaMinutes, titleEllipsizeMode, titleNumberOfLines, toICalendar, toZonedTime, useCalendarSelection, useDateRange, useMonthGrid, viewDayCount, weekDaysCount, weekdayFormatToken, zonedTimeToUtc };
1395
+ export { CalendarSelectionProvider, MIN_BOX_HEIGHT_FOR_TIME, backgroundBandsForDay, bandRounding, buildMonthGrid, buildMonthWeeks, cellRangeFromDrag, closedHourBands, compareDayEvents, darkColors, dayBadgeKind, daySelectionState, eventAccessibilityLabel, eventChipLayout, eventDayKeys, eventTimeLabel, eventsInTimeZone, expandRecurringEvents, filterHiddenDays, formatHour, getIsToday, getViewDays, getWeekDays, getYearMonths, groupEventsByDay, isAllDayEvent, isBackgroundEvent, isDateSelectable, isRangeEndpoint, isSameCalendarDay, isTimeVisibleAtHeight, isWeekend, isWithinDateRange, layoutDayEvents, lightColors, minutesIntoDay, monthEventCapacity, monthVisibleCount, nextDateRange, pageStepDays, parseICalendar, rangeBandKind, resolveDraggedBounds, shiftMinutes, snapDeltaMinutes, titleEllipsizeMode, titleNumberOfLines, toICalendar, toZonedTime, useCalendarSelection, useDateRange, useEventSource, useMonthGrid, useNow, viewDayCount, weekDaysCount, weekdayFormatToken, zonedTimeToUtc };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@super-calendar/core",
3
- "version": "2.6.0",
3
+ "version": "2.7.0",
4
4
  "description": "Render-agnostic core for super-calendar: date math, selection model, event layout, the month-grid builder, headless hooks, and neutral theme tokens. No renderer.",
5
5
  "keywords": [
6
6
  "calendar",
package/src/index.ts CHANGED
@@ -24,6 +24,8 @@ export * from "./utils/dates";
24
24
  export * from "./utils/drag";
25
25
  export * from "./utils/eventDisplay";
26
26
  export * from "./utils/ical";
27
+ export * from "./utils/useNow";
28
+ export * from "./utils/useEventSource";
27
29
  export * from "./utils/layout";
28
30
  export * from "./utils/monthGrid";
29
31
  export * from "./utils/recurrence";
package/src/tokens.ts CHANGED
@@ -37,6 +37,8 @@ export interface CalendarColors {
37
37
  eventBackground: string;
38
38
  /** Default event chip text. */
39
39
  eventText: string;
40
+ /** Shaded band behind a `display: "background"` event. */
41
+ backgroundEvent: string;
40
42
  }
41
43
 
42
44
  /** The default light-theme colour palette. */
@@ -57,6 +59,7 @@ export const lightColors: CalendarColors = {
57
59
  textDisabled: "#B5B9C0",
58
60
  eventBackground: "#DCE7FF",
59
61
  eventText: "#1A1B1E",
62
+ backgroundEvent: "#E3F4E4",
60
63
  };
61
64
 
62
65
  /** The default dark-theme colour palette. */
@@ -77,4 +80,5 @@ export const darkColors: CalendarColors = {
77
80
  textDisabled: "#4B4F58",
78
81
  eventBackground: "#243B53",
79
82
  eventText: "#EAF2FF",
83
+ backgroundEvent: "#17301F",
80
84
  };
package/src/types.ts CHANGED
@@ -25,6 +25,23 @@ export interface ICalendarEvent {
25
25
  allDay?: boolean;
26
26
  /** Ignore taps/long-presses on this event (the built-in renderer also dims it). */
27
27
  disabled?: boolean;
28
+ /**
29
+ * Whether this event can be dragged to move or resize. Defaults to `true`, so
30
+ * enabling drag with `onDragEvent` makes every event movable. Set `false` to
31
+ * lock a specific event (a confirmed booking, someone else's event): it keeps
32
+ * its normal look and still responds to taps, it just can't be picked up. Use
33
+ * this for events that can *never* move; to reject a move only for certain
34
+ * targets (an overlap, an out-of-bounds slot), return `false` from `onDragEvent`
35
+ * instead so the event drags and snaps back.
36
+ */
37
+ draggable?: boolean;
38
+ /**
39
+ * How the event renders. `"auto"` (default) is a normal event box/chip;
40
+ * `"background"` paints the event's time range as a non-interactive shaded
41
+ * band behind the grid instead (blocked time, holidays). Background events
42
+ * are excluded from chips, the agenda, and year-view dots.
43
+ */
44
+ display?: "auto" | "background";
28
45
  /**
29
46
  * Repeat rule. Pass the event to `expandRecurringEvents(events, start, end)` to
30
47
  * materialise its occurrences within a range; the calendar itself doesn't
@@ -73,8 +90,11 @@ export interface RecurrenceRule {
73
90
  */
74
91
  months?: number[];
75
92
  /**
76
- * Dates to skip (exceptions). An occurrence whose day matches one of these is
77
- * dropped by `expandRecurringEvents`. Maps to iCal `EXDATE`.
93
+ * Dates to skip (exceptions), dropped by `expandRecurringEvents`. A date at
94
+ * local midnight drops every occurrence on that calendar day (iCal
95
+ * `EXDATE;VALUE=DATE`); a date with a time drops only the occurrence starting
96
+ * at that exact instant. Corollary: an occurrence that itself starts at
97
+ * midnight can only be excluded day-wide. Maps to iCal `EXDATE`.
78
98
  */
79
99
  exdates?: Date[];
80
100
  /**
@@ -99,9 +119,30 @@ export type EventKeyExtractor<T = unknown> = (event: CalendarEvent<T>, index: nu
99
119
  export type WeekStartsOn = 0 | 1 | 2 | 3 | 4 | 5 | 6;
100
120
 
101
121
  /**
102
- * A day's open hours for `businessHours` shading on the time grid: `{ start, end }`
103
- * in hours (fractions allowed, e.g. 9.5), or `null` when the day is closed (fully
104
- * shaded). `undefined` from the callback means "no business-hours shading". Shared
105
- * by both renderers; pair with `closedHourBands` to get the spans to shade.
122
+ * A day's open hours for `businessHours` shading, as hours (fractions allowed,
123
+ * e.g. `9.5`): a single window `{ start, end }`, or an array of windows to leave
124
+ * a closed gap between them (a lunch break: `[{ start: 9, end: 12 }, { start: 13,
125
+ * end: 17 }]`). Everything outside the window(s) is shaded closed.
126
+ */
127
+ export type BusinessHoursValue =
128
+ | { start: number; end: number }
129
+ | { start: number; end: number }[]
130
+ | null;
131
+ /**
132
+ * The `businessHours` callback: return the open hours for `date` (see
133
+ * {@link BusinessHoursValue}), `null` when the day is fully closed (all shaded),
134
+ * or `undefined` for no business-hours shading. Shared by both renderers; pair
135
+ * with `closedHourBands` to get the spans to shade.
136
+ */
137
+ export type BusinessHours = (date: Date) => BusinessHoursValue;
138
+
139
+ /**
140
+ * One closed-hours band handed to a `renderBusinessHours` override: the day it
141
+ * belongs to and its span as fractional hours, already clamped to the visible
142
+ * window. `ResourceTimeline` extends it with the lane's resource.
106
143
  */
107
- export type BusinessHours = (date: Date) => { start: number; end: number } | null;
144
+ export interface BusinessHoursBand {
145
+ date: Date;
146
+ start: number;
147
+ end: number;
148
+ }
@@ -65,21 +65,33 @@ export const getViewDays = (
65
65
  numberOfDays = 1,
66
66
  isRTL = false,
67
67
  weekEndsOn?: WeekStartsOn,
68
+ hiddenDays?: number[],
68
69
  ): Date[] => {
70
+ // A full hidden week would loop forever below; treat it as "hide nothing".
71
+ const hidden = hiddenDays && hiddenDays.length > 0 && hiddenDays.length < 7 ? hiddenDays : [];
69
72
  let days: Date[];
70
73
  if (mode === "week") {
71
- days = getWeekDays(date, weekStartsOn);
74
+ days = filterHiddenDays(getWeekDays(date, weekStartsOn), hidden);
72
75
  } else if (mode === "custom" && weekEndsOn != null) {
73
76
  // Mirror big-calendar: anchor to `date`'s week and take the partial-week span.
74
77
  const subject = startOfDay(date);
75
78
  const offset = weekStartsOn - subject.getDay();
76
- days = Array.from({ length: weekDaysCount(weekStartsOn, weekEndsOn) }, (_, index) =>
77
- addDays(subject, index + offset),
79
+ days = filterHiddenDays(
80
+ Array.from({ length: weekDaysCount(weekStartsOn, weekEndsOn) }, (_, index) =>
81
+ addDays(subject, index + offset),
82
+ ),
83
+ hidden,
78
84
  );
79
85
  } else {
80
- days = Array.from({ length: viewDayCount(mode, numberOfDays) }, (_, index) =>
81
- addDays(startOfDay(date), index),
82
- );
86
+ // Count-based views keep their column count by walking forward over hidden
87
+ // days (an anchor on a hidden day starts at the next visible one).
88
+ const count = viewDayCount(mode, numberOfDays);
89
+ days = [];
90
+ let cursor = startOfDay(date);
91
+ while (days.length < count) {
92
+ if (!hidden.includes(cursor.getDay())) days.push(cursor);
93
+ cursor = addDays(cursor, 1);
94
+ }
83
95
  }
84
96
  return isRTL ? days.reverse() : days;
85
97
  };
@@ -92,19 +104,33 @@ export const getViewDays = (
92
104
  export const buildMonthWeeks = (
93
105
  month: Date,
94
106
  weekStartsOn: WeekStartsOn,
95
- { showSixWeeks = false, isRTL = false }: { showSixWeeks?: boolean; isRTL?: boolean } = {},
107
+ {
108
+ showSixWeeks = false,
109
+ isRTL = false,
110
+ hiddenDays,
111
+ }: { showSixWeeks?: boolean; isRTL?: boolean; hiddenDays?: number[] } = {},
96
112
  ): Date[][] => {
97
113
  const start = startOfWeek(startOfMonth(month), { weekStartsOn });
98
114
  const end = showSixWeeks ? addDays(start, 41) : endOfWeek(endOfMonth(month), { weekStartsOn });
99
115
  const days = eachDayOfInterval({ start, end });
100
116
  const weeks: Date[][] = [];
101
117
  for (let index = 0; index < days.length; index += 7) {
102
- const week = days.slice(index, index + 7);
103
- weeks.push(isRTL ? week.reverse() : week);
118
+ const week = filterHiddenDays(days.slice(index, index + 7), hiddenDays);
119
+ if (week.length > 0) weeks.push(isRTL ? week.reverse() : week);
104
120
  }
105
121
  return weeks;
106
122
  };
107
123
 
124
+ /**
125
+ * Drop the days whose weekday (0=Sunday…6=Saturday) is listed in `hiddenDays`.
126
+ * Hiding all seven weekdays is treated as hiding nothing (matching
127
+ * `getViewDays`), so a misconfiguration degrades to the full grid, not a blank.
128
+ */
129
+ export const filterHiddenDays = (days: Date[], hiddenDays?: number[]): Date[] =>
130
+ hiddenDays && hiddenDays.length > 0 && new Set(hiddenDays).size < 7
131
+ ? days.filter((day) => !hiddenDays.includes(day.getDay()))
132
+ : days;
133
+
108
134
  /** True when `date` is a Saturday or Sunday. */
109
135
  export const isWeekend = (date: Date): boolean => {
110
136
  const day = date.getDay();
package/src/utils/drag.ts CHANGED
@@ -1,3 +1,21 @@
1
+ import type { CalendarMode, WeekStartsOn } from "../types";
2
+ import { getViewDays } from "./dates";
3
+
4
+ /**
5
+ * How many calendar days one time-grid page spans, used to advance the view by a
6
+ * whole page (e.g. when dragging an event past the edge into the next week).
7
+ * Deliberately ignores `hiddenDays` so a week always steps 7, matching the
8
+ * keyboard PageUp/PageDown paging and `Calendar`'s own page step.
9
+ */
10
+ export function pageStepDays(
11
+ mode: CalendarMode,
12
+ date: Date,
13
+ weekStartsOn: WeekStartsOn,
14
+ numberOfDays = 1,
15
+ ): number {
16
+ return getViewDays(mode, date, weekStartsOn, numberOfDays).length;
17
+ }
18
+
1
19
  /**
2
20
  * Minutes to shift an event, snapping a vertical pixel drag to the nearest
3
21
  * `stepMinutes`. Runs on the UI thread inside the drag gesture. Returns 0 for a