@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.d.mts +154 -13
- package/dist/index.d.ts +154 -13
- package/dist/index.js +248 -42
- package/dist/index.mjs +243 -44
- package/package.json +1 -1
- package/src/index.ts +2 -0
- package/src/tokens.ts +4 -0
- package/src/types.ts +50 -9
- package/src/utils/dates.ts +39 -9
- package/src/utils/drag.ts +18 -0
- package/src/utils/layout.ts +56 -8
- package/src/utils/monthGrid.ts +7 -1
- package/src/utils/recurrence.ts +16 -3
- package/src/utils/useEventSource.ts +125 -0
- package/src/utils/useNow.ts +47 -0
package/src/utils/layout.ts
CHANGED
|
@@ -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
|
-
|
|
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
|
-
|
|
188
|
-
const
|
|
189
|
-
|
|
190
|
-
|
|
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
|
-
|
|
193
|
-
|
|
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
|
+
}
|
package/src/utils/monthGrid.ts
CHANGED
|
@@ -80,6 +80,8 @@ export function weekdayFormatToken(format: WeekdayFormat): string {
|
|
|
80
80
|
export interface UseMonthGridOptions extends DateSelectionConstraints {
|
|
81
81
|
/** First day of the week. Sunday = 0 (default) … Saturday = 6. */
|
|
82
82
|
weekStartsOn?: WeekStartsOn;
|
|
83
|
+
/** Weekdays (0=Sunday…6=Saturday) to drop from the grid and header. */
|
|
84
|
+
hiddenDays?: number[];
|
|
83
85
|
/** Weekday header label width. Default `short` ("Mon"). */
|
|
84
86
|
weekdayFormat?: WeekdayFormat;
|
|
85
87
|
/** Always return six week rows for a fixed-height grid. Default false. */
|
|
@@ -105,6 +107,7 @@ export function buildMonthGrid(month: Date, options: UseMonthGridOptions = {}):
|
|
|
105
107
|
weekdayFormat = "short",
|
|
106
108
|
showSixWeeks = false,
|
|
107
109
|
isRTL = false,
|
|
110
|
+
hiddenDays,
|
|
108
111
|
selectedDates,
|
|
109
112
|
selectedRange,
|
|
110
113
|
minDate,
|
|
@@ -113,7 +116,7 @@ export function buildMonthGrid(month: Date, options: UseMonthGridOptions = {}):
|
|
|
113
116
|
locale,
|
|
114
117
|
} = options;
|
|
115
118
|
|
|
116
|
-
const rows = buildMonthWeeks(month, weekStartsOn, { showSixWeeks, isRTL });
|
|
119
|
+
const rows = buildMonthWeeks(month, weekStartsOn, { showSixWeeks, isRTL, hiddenDays });
|
|
117
120
|
|
|
118
121
|
const weeks: MonthGridWeek[] = rows.map((days) => ({
|
|
119
122
|
id: days[0].toISOString(),
|
|
@@ -136,6 +139,9 @@ export function buildMonthGrid(month: Date, options: UseMonthGridOptions = {}):
|
|
|
136
139
|
}));
|
|
137
140
|
|
|
138
141
|
// Weekday labels depend only on the first row's dates (already ordered).
|
|
142
|
+
// `hiddenDays` covering every weekday leaves no rows; return an empty grid
|
|
143
|
+
// rather than dereferencing a missing first row.
|
|
144
|
+
if (rows.length === 0) return { weeks: [], weekdays: [] };
|
|
139
145
|
const weekdays: MonthGridWeekday[] = rows[0].map((date) => ({
|
|
140
146
|
date,
|
|
141
147
|
label: format(date, WEEKDAY_TOKENS[weekdayFormat], { locale }),
|
package/src/utils/recurrence.ts
CHANGED
|
@@ -221,9 +221,22 @@ export function expandRecurringEvents<T>(
|
|
|
221
221
|
continue;
|
|
222
222
|
}
|
|
223
223
|
const durationMs = event.end.getTime() - event.start.getTime();
|
|
224
|
-
//
|
|
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
|
|
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 (
|
|
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
|
+
}
|