@super-calendar/core 2.6.0 → 2.8.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.
@@ -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,44 @@
1
+ import type { CalendarEvent, CalendarMode, WeekStartsOn } from "../types";
2
+ import { getViewDays } from "./dates";
3
+
4
+ /**
5
+ * True when two time ranges overlap. Edges touching (one ends exactly when the
6
+ * next begins) do not count as an overlap. Compares absolute instants, so events
7
+ * at the same wall-clock time on different days do not overlap.
8
+ */
9
+ export function eventsOverlap(aStart: Date, aEnd: Date, bStart: Date, bEnd: Date): boolean {
10
+ return aStart.getTime() < bEnd.getTime() && bStart.getTime() < aEnd.getTime();
11
+ }
12
+
13
+ /**
14
+ * True when the range `[start, end)` would overlap any event in `events` other
15
+ * than `moved` (compared by reference). Used by the `eventOverlap` guard to reject
16
+ * a drag/resize that would land an event on top of another.
17
+ */
18
+ export function overlapsOtherEvents<T>(
19
+ events: readonly CalendarEvent<T>[],
20
+ moved: CalendarEvent<T>,
21
+ start: Date,
22
+ end: Date,
23
+ ): boolean {
24
+ return events.some((e) => e !== moved && eventsOverlap(e.start, e.end, start, end));
25
+ }
26
+
27
+ /**
28
+ * How many calendar days one time-grid page spans, used to advance the view by a
29
+ * whole page (e.g. when dragging an event past the edge into the next week).
30
+ * Deliberately ignores `hiddenDays` so a week always steps 7, matching the
31
+ * keyboard PageUp/PageDown paging and `Calendar`'s own page step.
32
+ */
33
+ export function pageStepDays(
34
+ mode: CalendarMode,
35
+ date: Date,
36
+ weekStartsOn: WeekStartsOn,
37
+ numberOfDays = 1,
38
+ ): number {
39
+ return getViewDays(mode, date, weekStartsOn, numberOfDays).length;
40
+ }
41
+
1
42
  /**
2
43
  * Minutes to shift an event, snapping a vertical pixel drag to the nearest
3
44
  * `stepMinutes`. Runs on the UI thread inside the drag gesture. Returns 0 for a
@@ -42,8 +42,9 @@ export function layoutDayEvents<T>(events: CalendarEvent<T>[], day: Date): Posit
42
42
  const nextDayStart = addDays(dayStart, 1);
43
43
 
44
44
  const segments: Segment<T>[] = events
45
- // All-day events live in the lane, not the timed columns.
46
- .filter((event) => !isAllDayEvent(event))
45
+ // All-day events live in the lane, not the timed columns; background events
46
+ // paint as bands (see `backgroundBandsForDay`), not boxes.
47
+ .filter((event) => !isAllDayEvent(event) && !isBackgroundEvent(event))
47
48
  // Overlaps this day if it starts before the day ends and ends after it begins.
48
49
  .filter((event) => event.start < nextDayStart && event.end > dayStart)
49
50
  .map((event) => {
@@ -184,12 +185,59 @@ export function closedHourBands(
184
185
  const open = businessHours?.(day);
185
186
  if (open === undefined) return [];
186
187
  if (open === null) return [{ start: minHour, end: maxHour }];
187
- const start = Math.max(minHour, Math.min(maxHour, open.start));
188
- const end = Math.max(minHour, Math.min(maxHour, open.end));
189
- // Inverted or empty open hours mean nothing is open: shade the whole window.
190
- if (start >= end) return [{ start: minHour, end: maxHour }];
188
+ // Clamp every open window to the visible range and drop empty/inverted ones.
189
+ const windows = (Array.isArray(open) ? open : [open])
190
+ .map((w) => ({
191
+ start: Math.max(minHour, Math.min(maxHour, w.start)),
192
+ end: Math.max(minHour, Math.min(maxHour, w.end)),
193
+ }))
194
+ .filter((w) => w.end > w.start)
195
+ .sort((a, b) => a.start - b.start);
196
+ // Nothing open: shade the whole window.
197
+ if (windows.length === 0) return [{ start: minHour, end: maxHour }];
198
+ // Merge overlapping/touching windows so the closed bands are the gaps between
199
+ // (and around) them: before the first, between windows (e.g. lunch), after the last.
200
+ const merged: { start: number; end: number }[] = [];
201
+ for (const w of windows) {
202
+ const last = merged[merged.length - 1];
203
+ if (last && w.start <= last.end) last.end = Math.max(last.end, w.end);
204
+ else merged.push({ ...w });
205
+ }
191
206
  const bands: { start: number; end: number }[] = [];
192
- if (start > minHour) bands.push({ start: minHour, end: start });
193
- if (end < maxHour) bands.push({ start: end, end: maxHour });
207
+ let cursor = minHour;
208
+ for (const w of merged) {
209
+ if (w.start > cursor) bands.push({ start: cursor, end: w.start });
210
+ cursor = w.end;
211
+ }
212
+ if (cursor < maxHour) bands.push({ start: cursor, end: maxHour });
194
213
  return bands;
195
214
  }
215
+
216
+ /** True when the event paints as a shaded background band, not an event box. */
217
+ export function isBackgroundEvent<T>(event: CalendarEvent<T>): boolean {
218
+ return event.display === "background";
219
+ }
220
+
221
+ /**
222
+ * The background events of `events` sliced to `day`, as fractional-hour bands
223
+ * (an all-day or multi-day background covers the day's full window). Shared by
224
+ * both renderers so the shading can't disagree.
225
+ */
226
+ export function backgroundBandsForDay<T>(
227
+ events: CalendarEvent<T>[],
228
+ day: Date,
229
+ ): { event: CalendarEvent<T>; startHours: number; endHours: number }[] {
230
+ const dayStart = startOfDay(day);
231
+ const nextDayStart = addDays(dayStart, 1);
232
+ const out: { event: CalendarEvent<T>; startHours: number; endHours: number }[] = [];
233
+ for (const event of events) {
234
+ if (!isBackgroundEvent(event)) continue;
235
+ if (event.start >= nextDayStart || event.end <= dayStart) continue;
236
+ const from = event.start > dayStart ? event.start : dayStart;
237
+ const to = event.end < nextDayStart ? event.end : nextDayStart;
238
+ const startHours = (from.getTime() - dayStart.getTime()) / 3_600_000;
239
+ const endHours = (to.getTime() - dayStart.getTime()) / 3_600_000;
240
+ if (endHours > startHours) out.push({ event, startHours, endHours });
241
+ }
242
+ return out;
243
+ }
@@ -1,9 +1,118 @@
1
- import { format, type Locale, isSameMonth } from "date-fns";
1
+ import { format, type Locale, isSameMonth, startOfDay } from "date-fns";
2
2
  import { useMemo } from "react";
3
- import type { WeekStartsOn } from "../types";
3
+ import type { CalendarEvent, WeekStartsOn } from "../types";
4
4
  import { type DateRange, type DateSelectionConstraints, daySelectionState } from "./dateRange";
5
5
  import { buildMonthWeeks, getIsToday, isWeekend } from "./dates";
6
6
 
7
+ /**
8
+ * One event's placement within a single week row of the month grid: the column
9
+ * span it covers and the lane (stacked row) it sits in, plus whether it continues
10
+ * past this row's edges (so the renderer can draw a "continues" affordance and
11
+ * square off the clipped end). Columns index into the row's `days` array, so with
12
+ * `hiddenDays` a bar spans the visible columns it touches.
13
+ */
14
+ export interface MonthEventSegment<T = unknown> {
15
+ event: CalendarEvent<T>;
16
+ /** First covered column in the row (0-based, inclusive). */
17
+ startCol: number;
18
+ /** Last covered column in the row (inclusive). */
19
+ endCol: number;
20
+ /** Stacking row within the day cells; 0 is the topmost. */
21
+ lane: number;
22
+ /** The event started before this row's first day. */
23
+ continuesBefore: boolean;
24
+ /** The event ends after this row's last day. */
25
+ continuesAfter: boolean;
26
+ }
27
+
28
+ /** The laid-out event segments for one week row, with the number of lanes used. */
29
+ export interface MonthWeekEvents<T = unknown> {
30
+ segments: MonthEventSegment<T>[];
31
+ /** Highest lane index used + 1 (0 when the row has no events). */
32
+ laneCount: number;
33
+ }
34
+
35
+ /** The last calendar day an event visibly covers (a midnight end ends the day before). */
36
+ function lastCoveredDay(event: CalendarEvent<unknown>): number {
37
+ const endMs = event.end.getTime();
38
+ // Clamp to the start so a zero/negative-length event still covers its start day.
39
+ return startOfDay(new Date(Math.max(event.start.getTime(), endMs - 1))).getTime();
40
+ }
41
+
42
+ /**
43
+ * Lay out one week row's events as continuous horizontal bars: each event becomes
44
+ * a single segment spanning the columns it covers (not a chip repeated per day),
45
+ * stacked into lanes so overlapping events sit on separate rows. Multi-day events
46
+ * that cross the row edges are marked `continuesBefore`/`continuesAfter`. Shared by
47
+ * both renderers so the month grid draws identical spanning bars.
48
+ *
49
+ * Column indices map into the given `days` array in whatever display order it uses,
50
+ * so this is order-independent: a right-to-left (reversed) week lays out correctly,
51
+ * and `continuesBefore`/`continuesAfter` track the array's first/last column edge
52
+ * (not chronology), so the clipped end is squared on the right visual side.
53
+ *
54
+ * Lanes are packed greedily after sorting by start column then longest span first,
55
+ * matching how calendars keep long events on the upper lanes.
56
+ */
57
+ export function layoutMonthWeek<T>(
58
+ days: Date[],
59
+ events: readonly CalendarEvent<T>[],
60
+ ): MonthWeekEvents<T> {
61
+ if (days.length === 0) return { segments: [], laneCount: 0 };
62
+ const dayStarts = days.map((d) => startOfDay(d).getTime());
63
+ // Chronological bounds, independent of the array's direction (RTL reverses it).
64
+ const rowStart = Math.min(...dayStarts);
65
+ const rowEnd = Math.max(...dayStarts);
66
+ const ascending = dayStarts[0] <= dayStarts[dayStarts.length - 1];
67
+
68
+ const placed: MonthEventSegment<T>[] = [];
69
+ for (const event of events) {
70
+ const evStart = startOfDay(event.start).getTime();
71
+ const evLast = lastCoveredDay(event);
72
+ // Skip events entirely outside this row.
73
+ if (evLast < rowStart || evStart > rowEnd) continue;
74
+ // Columns this event covers, found by membership so it works in any day order.
75
+ let startCol = -1;
76
+ let endCol = -1;
77
+ for (let i = 0; i < dayStarts.length; i++) {
78
+ if (dayStarts[i] >= evStart && dayStarts[i] <= evLast) {
79
+ if (startCol === -1) startCol = i;
80
+ endCol = i;
81
+ }
82
+ }
83
+ // No column in this row covers the event (e.g. it only falls on a hidden
84
+ // interior day), so it draws no bar here.
85
+ if (startCol === -1) continue;
86
+ const startsBefore = evStart < rowStart;
87
+ const endsAfter = evLast > rowEnd;
88
+ placed.push({
89
+ event,
90
+ startCol,
91
+ endCol,
92
+ lane: 0,
93
+ // Map the chronological overflow to the array's first/last column edge.
94
+ continuesBefore: ascending ? startsBefore : endsAfter,
95
+ continuesAfter: ascending ? endsAfter : startsBefore,
96
+ });
97
+ }
98
+
99
+ // Longest, earliest segments claim the upper lanes first.
100
+ placed.sort((a, b) => a.startCol - b.startCol || b.endCol - b.startCol - (a.endCol - a.startCol));
101
+ const laneEnds: number[] = [];
102
+ for (const seg of placed) {
103
+ let lane = laneEnds.findIndex((end) => end < seg.startCol);
104
+ if (lane === -1) {
105
+ lane = laneEnds.length;
106
+ laneEnds.push(seg.endCol);
107
+ } else {
108
+ laneEnds[lane] = seg.endCol;
109
+ }
110
+ seg.lane = lane;
111
+ }
112
+
113
+ return { segments: placed, laneCount: laneEnds.length };
114
+ }
115
+
7
116
  /** A single day in the grid, with all the state a custom cell needs to render. */
8
117
  export interface MonthGridDay {
9
118
  /** The day this cell represents. */
@@ -80,6 +189,8 @@ export function weekdayFormatToken(format: WeekdayFormat): string {
80
189
  export interface UseMonthGridOptions extends DateSelectionConstraints {
81
190
  /** First day of the week. Sunday = 0 (default) … Saturday = 6. */
82
191
  weekStartsOn?: WeekStartsOn;
192
+ /** Weekdays (0=Sunday…6=Saturday) to drop from the grid and header. */
193
+ hiddenDays?: number[];
83
194
  /** Weekday header label width. Default `short` ("Mon"). */
84
195
  weekdayFormat?: WeekdayFormat;
85
196
  /** Always return six week rows for a fixed-height grid. Default false. */
@@ -105,6 +216,7 @@ export function buildMonthGrid(month: Date, options: UseMonthGridOptions = {}):
105
216
  weekdayFormat = "short",
106
217
  showSixWeeks = false,
107
218
  isRTL = false,
219
+ hiddenDays,
108
220
  selectedDates,
109
221
  selectedRange,
110
222
  minDate,
@@ -113,7 +225,7 @@ export function buildMonthGrid(month: Date, options: UseMonthGridOptions = {}):
113
225
  locale,
114
226
  } = options;
115
227
 
116
- const rows = buildMonthWeeks(month, weekStartsOn, { showSixWeeks, isRTL });
228
+ const rows = buildMonthWeeks(month, weekStartsOn, { showSixWeeks, isRTL, hiddenDays });
117
229
 
118
230
  const weeks: MonthGridWeek[] = rows.map((days) => ({
119
231
  id: days[0].toISOString(),
@@ -136,6 +248,9 @@ export function buildMonthGrid(month: Date, options: UseMonthGridOptions = {}):
136
248
  }));
137
249
 
138
250
  // Weekday labels depend only on the first row's dates (already ordered).
251
+ // `hiddenDays` covering every weekday leaves no rows; return an empty grid
252
+ // rather than dereferencing a missing first row.
253
+ if (rows.length === 0) return { weeks: [], weekdays: [] };
139
254
  const weekdays: MonthGridWeekday[] = rows[0].map((date) => ({
140
255
  date,
141
256
  label: format(date, WEEKDAY_TOKENS[weekdayFormat], { locale }),
@@ -221,9 +221,22 @@ export function expandRecurringEvents<T>(
221
221
  continue;
222
222
  }
223
223
  const durationMs = event.end.getTime() - event.start.getTime();
224
- // Exception days (EXDATE): an occurrence landing on one of these is dropped.
224
+ // Exceptions (EXDATE): a date-only exception (local midnight) drops every
225
+ // occurrence on that calendar day (RFC 5545 VALUE=DATE); a timed exception
226
+ // drops only the occurrence starting at that exact instant, so two
227
+ // same-day occurrences can be cancelled independently.
225
228
  const dayKey = (d: Date) => `${d.getFullYear()}-${d.getMonth()}-${d.getDate()}`;
226
- const excluded = new Set((event.recurrence.exdates ?? []).map(dayKey));
229
+ const excludedDays = new Set<string>();
230
+ const excludedInstants = new Set<number>();
231
+ for (const exdate of event.recurrence.exdates ?? []) {
232
+ const isMidnight =
233
+ exdate.getHours() === 0 &&
234
+ exdate.getMinutes() === 0 &&
235
+ exdate.getSeconds() === 0 &&
236
+ exdate.getMilliseconds() === 0;
237
+ if (isMidnight) excludedDays.add(dayKey(exdate));
238
+ else excludedInstants.add(exdate.getTime());
239
+ }
227
240
  // Union the rule's occurrences with any explicit RDATE additions, keyed by
228
241
  // exact start time so a date the rule already produces isn't duplicated.
229
242
  const starts = new Map<number, Date>();
@@ -239,7 +252,7 @@ export function expandRecurringEvents<T>(
239
252
  for (const start of ordered) {
240
253
  // Skip occurrences that end before the range opens, but keep iterating.
241
254
  if (start.getTime() + durationMs < rangeStart.getTime()) continue;
242
- if (excluded.has(dayKey(start))) continue;
255
+ if (excludedDays.has(dayKey(start)) || excludedInstants.has(start.getTime())) continue;
243
256
  out.push(instanceAt(event, start, durationMs));
244
257
  }
245
258
  }
@@ -0,0 +1,125 @@
1
+ import { useCallback, useEffect, useRef, useState } from "react";
2
+ import type { CalendarEvent } from "../types";
3
+ import { parseICalendar } from "./ical";
4
+
5
+ /** Options for {@link useEventSource}. */
6
+ export interface EventSourceOptions<T> {
7
+ /**
8
+ * Feed format for URL sources: `"json"` (default) expects an array of event
9
+ * objects with ISO `start`/`end` strings; `"ics"` parses an iCalendar feed.
10
+ * URLs ending in `.ics` default to `"ics"`.
11
+ */
12
+ format?: "json" | "ics";
13
+ /**
14
+ * Map the parsed JSON array into events, for feeds whose shape doesn't match
15
+ * `CalendarEvent` (rename fields, attach `resourceId`, filter). The default
16
+ * revives `start`/`end` ISO strings on each item.
17
+ */
18
+ map?: (items: unknown[]) => CalendarEvent<T>[];
19
+ /** Re-fetch every N ms (a live feed). Omit to fetch once. */
20
+ refetchIntervalMs?: number;
21
+ }
22
+
23
+ /** What {@link useEventSource} returns. */
24
+ export interface EventSourceState<T> {
25
+ /** The fetched events; the previous batch is kept while a refetch runs or fails. */
26
+ events: CalendarEvent<T>[];
27
+ /** True while the first fetch (or a manual refetch) is in flight. */
28
+ loading: boolean;
29
+ /** The last fetch error, or null. Events keep their previous value on error. */
30
+ error: Error | null;
31
+ /** Fetch the source again now. */
32
+ refetch: () => Promise<void>;
33
+ }
34
+
35
+ const defaultMap = <T>(items: unknown[]): CalendarEvent<T>[] =>
36
+ items.map((raw) => {
37
+ const item = raw as Record<string, unknown> & { start: string; end: string };
38
+ return { ...item, start: new Date(item.start), end: new Date(item.end) } as CalendarEvent<T>;
39
+ });
40
+
41
+ /**
42
+ * Load events from a refreshable source: a JSON feed URL, an iCalendar feed
43
+ * URL, or your own async function. The hook owns fetching, optional interval
44
+ * refetching, and loading/error state; hand the returned `events` to any view.
45
+ *
46
+ * @example
47
+ * ```tsx
48
+ * const { events, loading, refetch } = useEventSource(
49
+ * "https://example.com/feed.ics",
50
+ * { refetchIntervalMs: 5 * 60_000 },
51
+ * );
52
+ * <Calendar mode="week" date={date} events={events} onChangeDate={setDate} />;
53
+ * ```
54
+ */
55
+ export function useEventSource<T = unknown>(
56
+ source: string | (() => Promise<CalendarEvent<T>[]>),
57
+ { format, map, refetchIntervalMs }: EventSourceOptions<T> = {},
58
+ ): EventSourceState<T> {
59
+ const [events, setEvents] = useState<CalendarEvent<T>[]>([]);
60
+ const [loading, setLoading] = useState(true);
61
+ const [error, setError] = useState<Error | null>(null);
62
+ // Ignore responses from superseded fetches (unmount, source change, races).
63
+ const generation = useRef(0);
64
+ // Abort the superseded URL request too, so it stops consuming the network
65
+ // instead of just being ignored when it lands.
66
+ const abortRef = useRef<AbortController | null>(null);
67
+
68
+ // The latest source/options without re-subscribing the interval on every
69
+ // render (inline functions and option literals are expected).
70
+ const latest = useRef({ source, format, map });
71
+ latest.current = { source, format, map };
72
+
73
+ const load = useCallback(async (isManual: boolean) => {
74
+ const gen = ++generation.current;
75
+ abortRef.current?.abort();
76
+ const controller = typeof AbortController === "undefined" ? null : new AbortController();
77
+ abortRef.current = controller;
78
+ const { source: src, format: fmt, map: mapper } = latest.current;
79
+ if (isManual) setLoading(true);
80
+ try {
81
+ let next: CalendarEvent<T>[];
82
+ if (typeof src === "function") {
83
+ next = await src();
84
+ } else {
85
+ const response = await fetch(src, controller ? { signal: controller.signal } : undefined);
86
+ if (!response.ok) throw new Error(`Event source responded ${response.status}`);
87
+ const isIcs = fmt === "ics" || (fmt == null && /\.ics(\?|$)/.test(src));
88
+ if (isIcs) {
89
+ next = parseICalendar(await response.text()) as CalendarEvent<T>[];
90
+ } else {
91
+ const body = (await response.json()) as unknown[];
92
+ next = (mapper ?? defaultMap<T>)(body);
93
+ }
94
+ }
95
+ if (gen !== generation.current) return;
96
+ setEvents(next);
97
+ setError(null);
98
+ } catch (cause) {
99
+ if (gen !== generation.current) return;
100
+ setError(cause instanceof Error ? cause : new Error(String(cause)));
101
+ } finally {
102
+ if (gen === generation.current) setLoading(false);
103
+ }
104
+ }, []);
105
+
106
+ const sourceKey = typeof source === "string" ? source : "fn";
107
+ useEffect(() => {
108
+ void load(true);
109
+ if (!refetchIntervalMs) {
110
+ return () => {
111
+ generation.current++;
112
+ abortRef.current?.abort();
113
+ };
114
+ }
115
+ const id = setInterval(() => void load(false), refetchIntervalMs);
116
+ return () => {
117
+ clearInterval(id);
118
+ generation.current++;
119
+ abortRef.current?.abort();
120
+ };
121
+ }, [load, sourceKey, refetchIntervalMs]);
122
+
123
+ const refetch = useCallback(() => load(true), [load]);
124
+ return { events, loading, error, refetch };
125
+ }
@@ -0,0 +1,47 @@
1
+ import { useEffect, useState } from "react";
2
+ import { toZonedTime } from "./timezone";
3
+
4
+ /** Options for {@link useNow}. */
5
+ export interface UseNowOptions {
6
+ /**
7
+ * A fixed instant to use instead of the device clock (a server-synced clock,
8
+ * or a stable value for tests). A fixed instant doesn't tick.
9
+ */
10
+ now?: Date;
11
+ /**
12
+ * Shift the instant into this IANA time zone's wall-clock (the same shift
13
+ * `eventsInTimeZone` applies), so the now indicator lines up with events
14
+ * displayed in that zone rather than the device's.
15
+ */
16
+ timeZone?: string;
17
+ /** Tick interval in ms (default one minute). */
18
+ tickMs?: number;
19
+ }
20
+
21
+ const MINUTE_MS = 60_000;
22
+
23
+ const resolveNow = (now?: Date, timeZone?: string): Date => {
24
+ const instant = now ?? new Date();
25
+ return timeZone ? toZonedTime(instant, timeZone) : instant;
26
+ };
27
+
28
+ /**
29
+ * The current wall-clock time, re-read every `tickMs` while `enabled`, shifted
30
+ * into `timeZone` when given, or pinned to a fixed `now` override. Drives the
31
+ * now indicator on both renderers so it can't disagree with zone-shifted events.
32
+ */
33
+ export function useNow(
34
+ enabled: boolean,
35
+ { now, timeZone, tickMs = MINUTE_MS }: UseNowOptions = {},
36
+ ): Date {
37
+ const [value, setValue] = useState(() => resolveNow(now, timeZone));
38
+ const nowMs = now?.getTime();
39
+ useEffect(() => {
40
+ if (!enabled) return;
41
+ setValue(resolveNow(nowMs != null ? new Date(nowMs) : undefined, timeZone));
42
+ if (nowMs != null) return; // a fixed instant doesn't tick
43
+ const id = setInterval(() => setValue(resolveNow(undefined, timeZone)), tickMs);
44
+ return () => clearInterval(id);
45
+ }, [enabled, nowMs, timeZone, tickMs]);
46
+ return value;
47
+ }