@super-calendar/core 2.15.0 → 2.17.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.
@@ -0,0 +1,139 @@
1
+ import { addDays, format, startOfWeek } from "date-fns";
2
+ import { daySelectionState } from "./dateRange";
3
+ import { filterHiddenDays, getIsToday, isWeekend } from "./dates";
4
+ import {
5
+ type MonthGridDay,
6
+ type MonthGridWeekday,
7
+ type UseMonthGridOptions,
8
+ weekdayFormatToken,
9
+ } from "./monthGrid";
10
+
11
+ /** Options for {@link buildMultiWeekGrid}. */
12
+ export interface MultiWeekGridOptions extends Omit<UseMonthGridOptions, "showSixWeeks"> {
13
+ /**
14
+ * How many consecutive full weeks to show. A positive whole number; default 2.
15
+ * Other values throw a `RangeError`.
16
+ */
17
+ numberOfWeeks?: number;
18
+ }
19
+
20
+ /**
21
+ * A day in a multi-week grid. Every day of the grid belongs to the requested
22
+ * period, so it carries no month-membership flag.
23
+ */
24
+ export type MultiWeekGridDay = Omit<MonthGridDay, "isCurrentMonth">;
25
+
26
+ /** One week row of a {@link MultiWeekGrid}. */
27
+ export interface MultiWeekGridWeek {
28
+ /** The week's first calendar day as `yyyy-MM-dd`, before hidden days are removed. */
29
+ id: string;
30
+ /** The row's days in display order, without hidden weekdays. */
31
+ days: MultiWeekGridDay[];
32
+ }
33
+
34
+ /** A half-open local calendar interval, `[start, endExclusive)`. */
35
+ export interface MultiWeekGridInterval {
36
+ /** Midnight of the first day. */
37
+ start: Date;
38
+ /** Midnight after the last day. */
39
+ endExclusive: Date;
40
+ }
41
+
42
+ /** The rows, weekday headers, and date bounds of a multi-week grid. */
43
+ export interface MultiWeekGrid {
44
+ /** Every calendar day of the requested weeks, independent of hidden weekdays and RTL. */
45
+ period: MultiWeekGridInterval;
46
+ /** From the earliest to the latest displayed day; hidden days inside it stay hidden. */
47
+ visibleRange: MultiWeekGridInterval;
48
+ /** The week rows, oldest first. */
49
+ weeks: MultiWeekGridWeek[];
50
+ /** The weekday header cells, in display order. */
51
+ weekdays: MonthGridWeekday[];
52
+ }
53
+
54
+ /**
55
+ * Pure multi-week builder: `numberOfWeeks` consecutive full calendar weeks,
56
+ * starting with the week that contains `date` (aligned back to `weekStartsOn`).
57
+ * Each day carries the same selection, disabled, today, and weekend state as
58
+ * {@link buildMonthGrid}. Hidden weekdays shrink the rows without changing the
59
+ * period; `isRTL` reverses each row's display order.
60
+ *
61
+ * The result is fully materialized, so its size grows with `numberOfWeeks`.
62
+ *
63
+ * @throws RangeError when `date` is invalid, `numberOfWeeks` is not a positive
64
+ * safe integer, or the last week falls outside the range `Date` can represent.
65
+ */
66
+ export function buildMultiWeekGrid(date: Date, options: MultiWeekGridOptions = {}): MultiWeekGrid {
67
+ const {
68
+ numberOfWeeks = 2,
69
+ weekStartsOn = 0,
70
+ weekdayFormat = "short",
71
+ isRTL = false,
72
+ hiddenDays,
73
+ selectedDates,
74
+ selectedRange,
75
+ minDate,
76
+ maxDate,
77
+ isDateDisabled,
78
+ locale,
79
+ } = options;
80
+
81
+ if (!(date instanceof Date) || Number.isNaN(date.getTime())) {
82
+ throw new RangeError("buildMultiWeekGrid: date must be a valid Date.");
83
+ }
84
+ if (!Number.isSafeInteger(numberOfWeeks) || numberOfWeeks < 1) {
85
+ throw new RangeError(
86
+ `buildMultiWeekGrid: numberOfWeeks must be a positive whole number, received ${String(numberOfWeeks)}.`,
87
+ );
88
+ }
89
+ const start = startOfWeek(date, { weekStartsOn });
90
+ const endExclusive = addDays(start, numberOfWeeks * 7);
91
+ if (Number.isNaN(endExclusive.getTime())) {
92
+ throw new RangeError(
93
+ `buildMultiWeekGrid: ${numberOfWeeks} weeks from ${format(start, "yyyy-MM-dd")} cannot be represented as a Date.`,
94
+ );
95
+ }
96
+
97
+ const constraints = { minDate, maxDate, isDateDisabled };
98
+ const selection = { selectedDates, selectedRange };
99
+ let first: Date | null = null;
100
+ let last: Date | null = null;
101
+ const weeks: MultiWeekGridWeek[] = [];
102
+ for (let row = 0; row < numberOfWeeks; row++) {
103
+ const weekStart = addDays(start, row * 7);
104
+ const all = Array.from({ length: 7 }, (_, index) => addDays(weekStart, index));
105
+ const visible = filterHiddenDays(all, hiddenDays);
106
+ if (visible.length > 0) {
107
+ if (first === null) first = visible[0];
108
+ last = visible[visible.length - 1];
109
+ }
110
+ const ordered = isRTL ? [...visible].reverse() : visible;
111
+ weeks.push({
112
+ id: format(weekStart, "yyyy-MM-dd"),
113
+ days: ordered.map((day): MultiWeekGridDay => ({
114
+ date: day,
115
+ id: format(day, "yyyy-MM-dd"),
116
+ label: format(day, "d"),
117
+ isToday: getIsToday(day),
118
+ isWeekend: isWeekend(day),
119
+ ...daySelectionState(day, selection, constraints),
120
+ })),
121
+ });
122
+ }
123
+
124
+ const token = weekdayFormatToken(weekdayFormat);
125
+ const weekdays: MonthGridWeekday[] = weeks[0].days.map((day) => ({
126
+ date: day.date,
127
+ label: format(day.date, token, { locale }),
128
+ }));
129
+
130
+ return {
131
+ period: { start, endExclusive },
132
+ visibleRange: {
133
+ start: first ?? start,
134
+ endExclusive: last ? addDays(last, 1) : endExclusive,
135
+ },
136
+ weeks,
137
+ weekdays,
138
+ };
139
+ }
@@ -71,7 +71,8 @@ function* occurrenceStarts(
71
71
  let emitted = 0;
72
72
  const consider = (date: Date): "skip" | "stop" | "emit" => {
73
73
  if (date.getTime() < start.getTime()) return "skip"; // before the first occurrence
74
- if (date.getTime() > rangeEnd.getTime()) return "stop";
74
+ // A large interval can advance beyond Date's representable range (NaN).
75
+ if (!(date.getTime() <= rangeEnd.getTime())) return "stop";
75
76
  if (rule.until != null && date.getTime() > rule.until.getTime()) return "stop";
76
77
  if (rule.count != null && produced >= rule.count) return "stop";
77
78
  produced += 1;
@@ -85,18 +86,15 @@ function* occurrenceStarts(
85
86
  const weekdays = [...new Set(rule.weekdays)].sort((a, b) => a - b);
86
87
  let weekStart = startOfWeek(start, { weekStartsOn: 0 });
87
88
  while (true) {
88
- let advanced = false;
89
89
  for (const weekday of weekdays) {
90
90
  const date = withTimeOf(addDays(weekStart, weekday), start);
91
91
  const verdict = consider(date);
92
92
  if (verdict === "stop") return;
93
93
  if (verdict === "skip") continue;
94
- advanced = true;
95
94
  yield date;
96
95
  }
97
96
  const nextWeek = addWeeks(weekStart, interval);
98
- // Guard against a week that yielded nothing yet hasn't reached the range.
99
- if (!advanced && nextWeek.getTime() > rangeEnd.getTime()) return;
97
+ if (!(nextWeek.getTime() <= rangeEnd.getTime())) return;
100
98
  weekStart = nextWeek;
101
99
  }
102
100
  }
@@ -122,7 +120,7 @@ function* occurrenceStarts(
122
120
  year += Math.floor(month / 12);
123
121
  month = ((month % 12) + 12) % 12;
124
122
  // No occurrence yielded yet but we've run past the range: stop.
125
- if (new Date(year, month, 1).getTime() > rangeEnd.getTime()) return;
123
+ if (!(new Date(year, month, 1).getTime() <= rangeEnd.getTime())) return;
126
124
  }
127
125
  }
128
126
 
@@ -143,7 +141,7 @@ function* occurrenceStarts(
143
141
  year += Math.floor(month / 12);
144
142
  month = ((month % 12) + 12) % 12;
145
143
  // No occurrence yielded yet but we've run past the range: stop.
146
- if (new Date(year, month, 1).getTime() > rangeEnd.getTime()) return;
144
+ if (!(new Date(year, month, 1).getTime() <= rangeEnd.getTime())) return;
147
145
  }
148
146
  }
149
147
 
@@ -163,7 +161,7 @@ function* occurrenceStarts(
163
161
  yield date;
164
162
  }
165
163
  year += interval;
166
- if (new Date(year, 0, 1).getTime() > rangeEnd.getTime()) return;
164
+ if (!(new Date(year, 0, 1).getTime() <= rangeEnd.getTime())) return;
167
165
  }
168
166
  }
169
167
 
@@ -188,7 +186,7 @@ function* occurrenceStarts(
188
186
  if (rule.count != null && n >= rule.count) return;
189
187
  if (emitted >= MAX_OCCURRENCES) return;
190
188
  const date = occAt(n);
191
- if (date.getTime() > rangeEnd.getTime()) return;
189
+ if (!(date.getTime() <= rangeEnd.getTime())) return;
192
190
  if (rule.until != null && date.getTime() > rule.until.getTime()) return;
193
191
  emitted += 1;
194
192
  n += 1;
@@ -253,7 +251,8 @@ export function expandRecurringEvents<T>(
253
251
  // Skip occurrences that end before the range opens, but keep iterating.
254
252
  if (start.getTime() + durationMs < rangeStart.getTime()) continue;
255
253
  if (excludedDays.has(dayKey(start)) || excludedInstants.has(start.getTime())) continue;
256
- out.push(instanceAt(event, start, durationMs));
254
+ const instance = instanceAt(event, start, durationMs);
255
+ if (Number.isFinite(instance.end.getTime())) out.push(instance);
257
256
  }
258
257
  }
259
258
  return out;
@@ -0,0 +1,80 @@
1
+ import { startOfDay } from "date-fns";
2
+ import {
3
+ type Context,
4
+ createContext,
5
+ type Dispatch,
6
+ type SetStateAction,
7
+ useCallback,
8
+ useContext,
9
+ useMemo,
10
+ useState,
11
+ } from "react";
12
+ import {
13
+ type CalendarSelection,
14
+ type DateRange,
15
+ type DateSelectionConstraints,
16
+ type UseDateRangeOptions,
17
+ isDateSelectable,
18
+ nextDateRange,
19
+ } from "./dateRange";
20
+
21
+ const CalendarSelectionContext: Context<CalendarSelection> = createContext<CalendarSelection>({});
22
+
23
+ /**
24
+ * Provides the active selection to the month grid. Day cells read it via
25
+ * {@link useCalendarSelection} so they repaint on selection changes even when
26
+ * the virtualized list has cached (and so won't re-render) their page.
27
+ */
28
+ export const CalendarSelectionProvider = CalendarSelectionContext.Provider;
29
+
30
+ /** Reads the active selection provided by {@link CalendarSelectionProvider}. */
31
+ export const useCalendarSelection = (): CalendarSelection => useContext(CalendarSelectionContext);
32
+
33
+ /** The state and handlers returned by {@link useDateRange}. */
34
+ export interface UseDateRangeResult {
35
+ /** The current selection; `null` until the first endpoint is picked. */
36
+ range: DateRange | null;
37
+ /** Wire to `onPressDay`: advances the range (start, then end, then restarts). */
38
+ onPressDate: (date: Date) => void;
39
+ /** Set both endpoints at once (ordered); ignored if either isn't selectable. */
40
+ selectRange: (a: Date, b: Date) => void;
41
+ /** Clear the selection. */
42
+ reset: () => void;
43
+ /** The raw state setter, for full control. */
44
+ setRange: Dispatch<SetStateAction<DateRange | null>>;
45
+ }
46
+
47
+ /**
48
+ * Controlled-ish range selection state for the month view. Returns the current
49
+ * `range` plus an `onPressDate` handler to wire to `Calendar`'s `onPressDay`, a
50
+ * `reset`, and the raw `setRange` for full control.
51
+ *
52
+ * ```tsx
53
+ * const { range, onPressDate } = useDateRange({ minDate: new Date() });
54
+ * <Calendar mode="month" selectedRange={range ?? undefined} onPressDay={onPressDate} … />
55
+ * ```
56
+ */
57
+ export function useDateRange(options: UseDateRangeOptions = {}): UseDateRangeResult {
58
+ const { initialRange = null, minDate, maxDate, isDateDisabled } = options;
59
+ const [range, setRange] = useState<DateRange | null>(initialRange);
60
+ const constraints = useMemo<DateSelectionConstraints>(
61
+ () => ({ minDate, maxDate, isDateDisabled }),
62
+ [minDate, maxDate, isDateDisabled],
63
+ );
64
+ const onPressDate = useCallback(
65
+ (date: Date) => setRange((previous) => nextDateRange(previous, date, constraints)),
66
+ [constraints],
67
+ );
68
+ // Set both endpoints at once (ordered), for drag-to-select. Ignores the update
69
+ // if either endpoint isn't selectable.
70
+ const selectRange = useCallback(
71
+ (a: Date, b: Date) => {
72
+ if (!isDateSelectable(a, constraints) || !isDateSelectable(b, constraints)) return;
73
+ const [start, end] = a.getTime() <= b.getTime() ? [a, b] : [b, a];
74
+ setRange({ start: startOfDay(start), end: startOfDay(end) });
75
+ },
76
+ [constraints],
77
+ );
78
+ const reset = useCallback(() => setRange(null), []);
79
+ return { range, onPressDate, selectRange, reset, setRange };
80
+ }
@@ -1,24 +1,7 @@
1
1
  import { useCallback, useEffect, useRef, useState } from "react";
2
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
- }
3
+ import { loadEventSource, type EventSource, type EventSourceOptions } from "./eventSource";
4
+ export type { EventSourceOptions } from "./eventSource";
22
5
 
23
6
  /** What {@link useEventSource} returns. */
24
7
  export interface EventSourceState<T> {
@@ -32,12 +15,6 @@ export interface EventSourceState<T> {
32
15
  refetch: () => Promise<void>;
33
16
  }
34
17
 
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
18
  /**
42
19
  * Load events from a refreshable source: a JSON feed URL, an iCalendar feed
43
20
  * URL, or your own async function. The hook owns fetching, optional interval
@@ -53,7 +30,7 @@ const defaultMap = <T>(items: unknown[]): CalendarEvent<T>[] =>
53
30
  * ```
54
31
  */
55
32
  export function useEventSource<T = unknown>(
56
- source: string | (() => Promise<CalendarEvent<T>[]>),
33
+ source: EventSource<T>,
57
34
  { format, map, refetchIntervalMs }: EventSourceOptions<T> = {},
58
35
  ): EventSourceState<T> {
59
36
  const [events, setEvents] = useState<CalendarEvent<T>[]>([]);
@@ -64,6 +41,7 @@ export function useEventSource<T = unknown>(
64
41
  // Abort the superseded URL request too, so it stops consuming the network
65
42
  // instead of just being ignored when it lands.
66
43
  const abortRef = useRef<AbortController | null>(null);
44
+ const active = useRef(false);
67
45
 
68
46
  // The latest source/options without re-subscribing the interval on every
69
47
  // render (inline functions and option literals are expected).
@@ -71,6 +49,7 @@ export function useEventSource<T = unknown>(
71
49
  latest.current = { source, format, map };
72
50
 
73
51
  const load = useCallback(async (isManual: boolean) => {
52
+ if (!active.current) return;
74
53
  const gen = ++generation.current;
75
54
  abortRef.current?.abort();
76
55
  const controller = typeof AbortController === "undefined" ? null : new AbortController();
@@ -78,20 +57,12 @@ export function useEventSource<T = unknown>(
78
57
  const { source: src, format: fmt, map: mapper } = latest.current;
79
58
  if (isManual) setLoading(true);
80
59
  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
- }
60
+ const next = await loadEventSource({
61
+ source: src,
62
+ format: fmt,
63
+ map: mapper,
64
+ signal: controller?.signal,
65
+ });
95
66
  if (gen !== generation.current) return;
96
67
  setEvents(next);
97
68
  setError(null);
@@ -105,15 +76,23 @@ export function useEventSource<T = unknown>(
105
76
 
106
77
  const sourceKey = typeof source === "string" ? source : "fn";
107
78
  useEffect(() => {
79
+ active.current = true;
108
80
  void load(true);
109
- if (!refetchIntervalMs) {
81
+ if (
82
+ !refetchIntervalMs ||
83
+ !Number.isFinite(refetchIntervalMs) ||
84
+ refetchIntervalMs <= 0 ||
85
+ refetchIntervalMs > 2 ** 31 - 1
86
+ ) {
110
87
  return () => {
88
+ active.current = false;
111
89
  generation.current++;
112
90
  abortRef.current?.abort();
113
91
  };
114
92
  }
115
93
  const id = setInterval(() => void load(false), refetchIntervalMs);
116
94
  return () => {
95
+ active.current = false;
117
96
  clearInterval(id);
118
97
  generation.current++;
119
98
  abortRef.current?.abort();
@@ -0,0 +1,42 @@
1
+ import { useMemo } from "react";
2
+ import { buildMonthGrid, type MonthGrid, type UseMonthGridOptions } from "./monthGrid";
3
+
4
+ /**
5
+ * Headless month-grid hook. Returns the weeks and weekday headers for `month`,
6
+ * each day annotated with selection/disabled/today state, so you can render a
7
+ * fully custom calendar without reimplementing the date maths.
8
+ *
9
+ * ```tsx
10
+ * const { weeks, weekdays } = useMonthGrid(month, { selectedRange: range });
11
+ * // map weekdays -> header cells, weeks -> rows, days -> your own <DayCell />
12
+ * ```
13
+ */
14
+ export function useMonthGrid(month: Date, options: UseMonthGridOptions = {}): MonthGrid {
15
+ const {
16
+ weekStartsOn,
17
+ showSixWeeks,
18
+ isRTL,
19
+ selectedDates,
20
+ selectedRange,
21
+ minDate,
22
+ maxDate,
23
+ isDateDisabled,
24
+ locale,
25
+ } = options;
26
+ return useMemo(
27
+ () => buildMonthGrid(month, options),
28
+ // Deps are the destructured option fields, not the (unstable) options object.
29
+ [
30
+ month,
31
+ weekStartsOn,
32
+ showSixWeeks,
33
+ isRTL,
34
+ selectedDates,
35
+ selectedRange,
36
+ minDate,
37
+ maxDate,
38
+ isDateDisabled,
39
+ locale,
40
+ ],
41
+ );
42
+ }
package/src/vanilla.ts ADDED
@@ -0,0 +1,16 @@
1
+ /** Framework-independent calendar types, date calculations, layout, and theme tokens. */
2
+ export * from "./types";
3
+ export * from "./tokens";
4
+ export * from "./presentation";
5
+ export * from "./utils/dateRange";
6
+ export * from "./utils/dates";
7
+ export * from "./utils/drag";
8
+ export * from "./utils/eventDisplay";
9
+ export * from "./utils/ical";
10
+ export * from "./utils/labels";
11
+ export * from "./utils/layout";
12
+ export * from "./utils/monthGrid";
13
+ export * from "./utils/multiWeekGrid";
14
+ export * from "./utils/recurrence";
15
+ export * from "./utils/timezone";
16
+ export * from "./utils/eventSource";