@jsb188/calendar 1.1.2

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,401 @@
1
+ import {
2
+ DEFAULT_TIMEZONE,
3
+ isValidTimeZone,
4
+ } from '@jsb188/app/utils/timeZone.ts';
5
+ import { DateTime } from 'luxon';
6
+ import {
7
+ CALENDAR_AGENDA_DAY_COUNT,
8
+ CALENDAR_DATE_PARAM_FORMAT,
9
+ CALENDAR_VIEW_DAY_COUNTS,
10
+ type CalendarViewEnum,
11
+ } from '../constants/calendar.ts';
12
+ import type { CalendarDayObj, CalendarRangeObj } from '../types/calendar.d.ts';
13
+
14
+ /**
15
+ * Calendar range math.
16
+ *
17
+ * Everything here is pure and takes its zone explicitly. A calendar is the one
18
+ * surface where "today" is genuinely ambiguous — the organization's day, the
19
+ * viewer's day, and UTC's day are three different things, and a shift that
20
+ * starts at 11pm belongs to whichever of them the calendar is drawn in. So
21
+ * nothing in this file reads a system zone or a system clock; both arrive as
22
+ * arguments and every date is built through luxon in the given zone.
23
+ *
24
+ * Days are half-open [start, end). A day boundary is not 23:59:59.999 — that
25
+ * loses the last millisecond, and over a DST fall-back day it loses an entire
26
+ * repeated hour.
27
+ */
28
+
29
+ /*
30
+ * Resolve a usable IANA zone, falling back rather than throwing: a calendar
31
+ * that renders in the wrong zone is a bug, but one that renders nothing
32
+ * because a setting is stale is worse.
33
+ */
34
+
35
+ export function getCalendarTimeZone(timeZone?: string | null): string {
36
+ return timeZone && isValidTimeZone(timeZone) ? timeZone : DEFAULT_TIMEZONE;
37
+ }
38
+
39
+ /**
40
+ * Normalize the app's Sunday-through-Saturday week-start convention.
41
+ */
42
+
43
+ export function normalizeCalendarWeekStartsOn(weekStartsOn?: number): number {
44
+ return typeof weekStartsOn === 'number' &&
45
+ Number.isInteger(weekStartsOn) &&
46
+ weekStartsOn >= 0 &&
47
+ weekStartsOn <= 6
48
+ ? weekStartsOn
49
+ : 0;
50
+ }
51
+
52
+ /**
53
+ * Return the local date key ("yyyy-MM-dd") one instant falls on, in a zone.
54
+ */
55
+
56
+ export function getCalendarDateKey(
57
+ instant: Date,
58
+ timeZone?: string | null,
59
+ ): string {
60
+ return DateTime.fromJSDate(instant, {
61
+ zone: getCalendarTimeZone(timeZone),
62
+ }).toFormat(CALENDAR_DATE_PARAM_FORMAT);
63
+ }
64
+
65
+ /**
66
+ * Parse a "yyyy-MM-dd" URL parameter into the local start of that day.
67
+ *
68
+ * Anything unparseable falls back to the supplied "now" rather than to the
69
+ * epoch: a mistyped URL should land the user on today, not in 1970.
70
+ */
71
+
72
+ export function parseCalendarDateParam(
73
+ value: string | null | undefined,
74
+ now: Date,
75
+ timeZone?: string | null,
76
+ ): Date {
77
+ const zone = getCalendarTimeZone(timeZone);
78
+
79
+ if (value) {
80
+ const parsed = DateTime.fromFormat(value, CALENDAR_DATE_PARAM_FORMAT, {
81
+ zone,
82
+ });
83
+
84
+ if (parsed.isValid) {
85
+ return parsed.startOf('day').toJSDate();
86
+ }
87
+ }
88
+
89
+ return DateTime.fromJSDate(now, { zone }).startOf('day').toJSDate();
90
+ }
91
+
92
+ /*
93
+ * Build one day descriptor.
94
+ */
95
+
96
+ function buildCalendarDay(
97
+ dayStart: DateTime,
98
+ todayKey: string,
99
+ isInPrimaryRange: boolean,
100
+ ): CalendarDayObj {
101
+ return {
102
+ dateKey: dayStart.toFormat(CALENDAR_DATE_PARAM_FORMAT),
103
+ startAt: dayStart.toJSDate(),
104
+ // Adding a calendar day rather than 24 hours: across a DST boundary the
105
+ // day is 23 or 25 hours long, and the grid has to agree with the clock
106
+ endAt: dayStart.plus({ days: 1 }).toJSDate(),
107
+ isToday: dayStart.toFormat(CALENDAR_DATE_PARAM_FORMAT) === todayKey,
108
+ // Luxon weekdays are 1 (Monday) through 7 (Sunday)
109
+ isWeekend: dayStart.weekday >= 6,
110
+ isInPrimaryRange,
111
+ };
112
+ }
113
+
114
+ /*
115
+ * Build a consecutive run of days starting at one local midnight.
116
+ */
117
+
118
+ function buildConsecutiveDays(
119
+ firstDay: DateTime,
120
+ dayCount: number,
121
+ todayKey: string,
122
+ ): CalendarDayObj[] {
123
+ const days: CalendarDayObj[] = [];
124
+
125
+ for (let index = 0; index < dayCount; index++) {
126
+ days.push(buildCalendarDay(firstDay.plus({ days: index }), todayKey, true));
127
+ }
128
+
129
+ return days;
130
+ }
131
+
132
+ /*
133
+ * Return the first day of the week containing an instant.
134
+ *
135
+ * weekStartsOn is 0 for Sunday through 6 for Saturday, matching the rest of
136
+ * the app's day-of-week convention rather than luxon's 1-7.
137
+ */
138
+
139
+ function getWeekStart(day: DateTime, weekStartsOn: number): DateTime {
140
+ // luxon: 1 = Monday .. 7 = Sunday; normalize to 0 = Sunday .. 6 = Saturday
141
+ const currentDayOfWeek = day.weekday % 7;
142
+ const offset = (currentDayOfWeek - weekStartsOn + 7) % 7;
143
+
144
+ return day.minus({ days: offset });
145
+ }
146
+
147
+ /*
148
+ * Build the six-week grid a month view draws, including the leading and
149
+ * trailing days of the neighbouring months.
150
+ *
151
+ * Always six weeks, never five: a grid that changes height between months
152
+ * makes every event jump, and the row heights would have to be recomputed on
153
+ * each navigation.
154
+ */
155
+
156
+ function buildMonthDays(
157
+ anchor: DateTime,
158
+ weekStartsOn: number,
159
+ todayKey: string,
160
+ ): CalendarDayObj[] {
161
+ const monthStart = anchor.startOf('month');
162
+ const monthEnd = anchor.endOf('month');
163
+ const gridStart = getWeekStart(monthStart, weekStartsOn);
164
+ const days: CalendarDayObj[] = [];
165
+
166
+ for (let index = 0; index < 42; index++) {
167
+ const day = gridStart.plus({ days: index });
168
+
169
+ days.push(
170
+ buildCalendarDay(day, todayKey, day >= monthStart && day <= monthEnd),
171
+ );
172
+ }
173
+
174
+ return days;
175
+ }
176
+
177
+ /*
178
+ * Build every day of one year.
179
+ *
180
+ * The year view is a NAVIGATION surface, not a display one: twelve mini month
181
+ * grids you click to jump into. It deliberately does not draw events, so this
182
+ * only has to produce the days — which is also why the page skips the
183
+ * occurrence query entirely for this view rather than asking for a year of
184
+ * shifts and silently truncating them at the window limit.
185
+ */
186
+
187
+ function buildYearDays(anchor: DateTime, todayKey: string): CalendarDayObj[] {
188
+ const yearStart = anchor.startOf('year');
189
+ const dayCount = yearStart.isInLeapYear ? 366 : 365;
190
+
191
+ return buildConsecutiveDays(yearStart, dayCount, todayKey);
192
+ }
193
+
194
+ /**
195
+ * Build the range one view is showing.
196
+ *
197
+ * The returned "from" and "to" are what the window query asks for, so they
198
+ * cover every day the view DRAWS — a month grid queries its leading and
199
+ * trailing days too, or the first row would render empty until the user
200
+ * navigated to the previous month.
201
+ */
202
+
203
+ export function getCalendarRange(p: {
204
+ view: CalendarViewEnum;
205
+ anchorDate: Date;
206
+ now: Date;
207
+ timeZone?: string | null;
208
+ // 0 = Sunday .. 6 = Saturday
209
+ weekStartsOn?: number;
210
+ }): CalendarRangeObj {
211
+ const { view, anchorDate, now } = p;
212
+ const timeZone = getCalendarTimeZone(p.timeZone);
213
+ const weekStartsOn = normalizeCalendarWeekStartsOn(p.weekStartsOn);
214
+ const anchor = DateTime.fromJSDate(anchorDate, { zone: timeZone }).startOf(
215
+ 'day',
216
+ );
217
+ const todayKey = DateTime.fromJSDate(now, { zone: timeZone }).toFormat(
218
+ CALENDAR_DATE_PARAM_FORMAT,
219
+ );
220
+
221
+ const days = getCalendarViewDays({ view, anchor, weekStartsOn, todayKey });
222
+
223
+ return {
224
+ view,
225
+ anchorDate: anchor.toJSDate(),
226
+ from: days[0].startAt,
227
+ to: days[days.length - 1].endAt,
228
+ days,
229
+ timeZone,
230
+ };
231
+ }
232
+
233
+ /*
234
+ * Return the days one view draws.
235
+ */
236
+
237
+ function getCalendarViewDays(p: {
238
+ view: CalendarViewEnum;
239
+ anchor: DateTime;
240
+ weekStartsOn: number;
241
+ todayKey: string;
242
+ }): CalendarDayObj[] {
243
+ const { view, anchor, weekStartsOn, todayKey } = p;
244
+
245
+ switch (view) {
246
+ case 'ROSTER':
247
+ case 'WEEK':
248
+ return buildConsecutiveDays(
249
+ getWeekStart(anchor, weekStartsOn),
250
+ 7,
251
+ todayKey,
252
+ );
253
+ case 'MONTH':
254
+ return buildMonthDays(anchor, weekStartsOn, todayKey);
255
+ case 'YEAR':
256
+ return buildYearDays(anchor, todayKey);
257
+ case 'AGENDA':
258
+ return buildConsecutiveDays(anchor, CALENDAR_AGENDA_DAY_COUNT, todayKey);
259
+ default:
260
+ // DAY and FOUR_DAYS both run forward from the anchor, so clicking a
261
+ // day in the month view lands on that day rather than on its week
262
+ return buildConsecutiveDays(
263
+ anchor,
264
+ CALENDAR_VIEW_DAY_COUNTS[view] || 1,
265
+ todayKey,
266
+ );
267
+ }
268
+ }
269
+
270
+ /**
271
+ * Return the anchor date one step forward or backward in a view.
272
+ *
273
+ * A month step is a calendar month, not 30 days: stepping from the 31st of
274
+ * March has to land in April, and luxon already clamps that to the 30th rather
275
+ * than overflowing into May.
276
+ */
277
+
278
+ export function getCalendarStepAnchor(p: {
279
+ view: CalendarViewEnum;
280
+ anchorDate: Date;
281
+ direction: 1 | -1;
282
+ timeZone?: string | null;
283
+ }): Date {
284
+ const { view, anchorDate, direction } = p;
285
+ const anchor = DateTime.fromJSDate(anchorDate, {
286
+ zone: getCalendarTimeZone(p.timeZone),
287
+ }).startOf('day');
288
+
289
+ switch (view) {
290
+ case 'ROSTER':
291
+ case 'WEEK':
292
+ return anchor.plus({ weeks: direction }).toJSDate();
293
+ case 'MONTH':
294
+ return anchor.plus({ months: direction }).toJSDate();
295
+ case 'YEAR':
296
+ return anchor.plus({ years: direction }).toJSDate();
297
+ case 'AGENDA':
298
+ return anchor
299
+ .plus({ days: direction * CALENDAR_AGENDA_DAY_COUNT })
300
+ .toJSDate();
301
+ default:
302
+ return anchor
303
+ .plus({ days: direction * (CALENDAR_VIEW_DAY_COUNTS[view] || 1) })
304
+ .toJSDate();
305
+ }
306
+ }
307
+
308
+ /**
309
+ * Return the minutes from local midnight one instant falls at, on a given day.
310
+ *
311
+ * Measured against the day's own start rather than by reading the clock, so a
312
+ * DST spring-forward day — where 2am never happens — still places events at
313
+ * the height the grid drew the hour lines at.
314
+ */
315
+
316
+ export function getMinutesFromDayStart(instant: Date, dayStart: Date): number {
317
+ return (instant.getTime() - dayStart.getTime()) / 60_000;
318
+ }
319
+
320
+ /**
321
+ * Return the instant a number of minutes past a day's local start.
322
+ */
323
+
324
+ export function getInstantFromDayMinutes(
325
+ dayStart: Date,
326
+ minutes: number,
327
+ ): Date {
328
+ return new Date(dayStart.getTime() + minutes * 60_000);
329
+ }
330
+
331
+ /**
332
+ * Return how many minutes long a day is, in its own zone.
333
+ *
334
+ * Almost always 1440 — but 1380 or 1500 on the two DST days a year, and the
335
+ * grid has to draw those days at the right height or every event after the
336
+ * transition sits an hour off.
337
+ */
338
+
339
+ export function getDayLengthMinutes(day: CalendarDayObj): number {
340
+ return (day.endAt.getTime() - day.startAt.getTime()) / 60_000;
341
+ }
342
+
343
+ /**
344
+ * Snap a minute offset to the nearest increment, clamped into the day.
345
+ */
346
+
347
+ export function snapMinutes(
348
+ minutes: number,
349
+ snapTo: number,
350
+ dayLengthMinutes: number,
351
+ ): number {
352
+ const snapped = Math.round(minutes / snapTo) * snapTo;
353
+
354
+ return Math.max(0, Math.min(dayLengthMinutes, snapped));
355
+ }
356
+
357
+ /**
358
+ * Format the heading one view shows for its range ("July 2026", "Jul 20 – 26,
359
+ * 2026", "Monday, July 20").
360
+ *
361
+ * Kept here rather than in the UI because the answer depends on the range
362
+ * math: whether a week spans two months or two years is the same question as
363
+ * where its days fall.
364
+ */
365
+
366
+ export function getCalendarRangeTitle(
367
+ range: CalendarRangeObj,
368
+ locale?: string | null,
369
+ ): string {
370
+ const zone = range.timeZone;
371
+ const first = DateTime.fromJSDate(range.days[0].startAt, { zone }).setLocale(
372
+ locale || 'en',
373
+ );
374
+ const lastDay = range.days[range.days.length - 1];
375
+ const last = DateTime.fromJSDate(new Date(lastDay.endAt.getTime() - 1), {
376
+ zone,
377
+ }).setLocale(locale || 'en');
378
+
379
+ switch (range.view) {
380
+ case 'YEAR':
381
+ return first.toFormat('yyyy');
382
+ case 'MONTH':
383
+ return DateTime.fromJSDate(range.anchorDate, { zone })
384
+ .setLocale(locale || 'en')
385
+ .toFormat('LLLL yyyy');
386
+ case 'DAY':
387
+ return first.toFormat('cccc, LLLL d, yyyy');
388
+ default:
389
+ break;
390
+ }
391
+
392
+ if (first.year !== last.year) {
393
+ return `${first.toFormat('LLL d, yyyy')} – ${last.toFormat('LLL d, yyyy')}`;
394
+ }
395
+
396
+ if (first.month !== last.month) {
397
+ return `${first.toFormat('LLL d')} – ${last.toFormat('LLL d, yyyy')}`;
398
+ }
399
+
400
+ return `${first.toFormat('LLL d')} – ${last.toFormat('d, yyyy')}`;
401
+ }
@@ -0,0 +1,26 @@
1
+ import { atom, type PrimitiveAtom } from 'jotai';
2
+
3
+ export interface CalendarStateAtoms {
4
+ selectedEventIdAtom: PrimitiveAtom<string | null>;
5
+ draftRangeAtom: PrimitiveAtom<{
6
+ startAt: Date;
7
+ endAt: Date;
8
+ roomId: string | null;
9
+ } | null>;
10
+ pendingIdsAtom: PrimitiveAtom<ReadonlySet<string>>;
11
+ hoverPersonIdAtom: PrimitiveAtom<string | null>;
12
+ }
13
+
14
+ /* Create isolated committed interaction state; pointer movement stays in refs and authority stays in server rows. */
15
+ export function createCalendarStateAtoms(): CalendarStateAtoms {
16
+ return {
17
+ selectedEventIdAtom: atom<string | null>(null),
18
+ draftRangeAtom: atom<{
19
+ startAt: Date;
20
+ endAt: Date;
21
+ roomId: string | null;
22
+ } | null>(null),
23
+ pendingIdsAtom: atom<ReadonlySet<string>>(new Set<string>()),
24
+ hoverPersonIdAtom: atom<string | null>(null),
25
+ };
26
+ }
@@ -0,0 +1,191 @@
1
+ import {
2
+ CALENDAR_DEFAULT_VIEW,
3
+ CALENDAR_SEARCH_PARAMS,
4
+ CALENDAR_VIEW_SLUGS,
5
+ type CalendarViewEnum,
6
+ } from '../constants/calendar.ts';
7
+ import {
8
+ getCalendarDateKey,
9
+ parseCalendarDateParam,
10
+ } from './calendar-range.ts';
11
+
12
+ /**
13
+ * The calendar's URL state.
14
+ *
15
+ * The URL is the calendar's state store for anything a person might want to
16
+ * link to or come back to: which view, which date, whose shifts, which
17
+ * calendars. It is kept deliberately terse and readable — one- and two-letter
18
+ * keys, lowercase view slugs, and every default omitted — so that
19
+ *
20
+ * /app/calendar
21
+ * /app/calendar?v=month&d=2026-07-25
22
+ * /app/calendar?me=1
23
+ *
24
+ * are what somebody actually sees in the address bar, rather than a query
25
+ * string carrying five parameters that all happen to be the default.
26
+ *
27
+ * Omitting defaults is not only cosmetic. It means "this week, everything" has
28
+ * exactly one URL instead of several equivalent ones, so the browser history
29
+ * and any shared link stay meaningful.
30
+ */
31
+
32
+ export interface CalendarUrlState {
33
+ calendarId: string | null;
34
+ roomId: string | null;
35
+ groupByRoom: boolean;
36
+ panel: 'open' | 'requests' | 'timeoff' | 'publish' | 'settings' | null;
37
+ openId: string | null;
38
+ view: CalendarViewEnum;
39
+ anchorDate: Date;
40
+ mineOnly: boolean;
41
+ // Calendars the viewer has explicitly HIDDEN — a blocklist, not a
42
+ // whitelist. Empty therefore means "show everything", which is what makes
43
+ // a calendar the viewer was just granted access to appear on its own
44
+ // instead of staying invisible until they find and tick it.
45
+ hiddenCalendarIds: string[];
46
+ }
47
+
48
+ const VIEW_BY_SLUG: Record<string, CalendarViewEnum> = Object.fromEntries(
49
+ Object.entries(CALENDAR_VIEW_SLUGS).map(([view, slug]) => [
50
+ slug,
51
+ view as CalendarViewEnum,
52
+ ]),
53
+ );
54
+
55
+ /**
56
+ * Return the URL spelling of one view.
57
+ */
58
+
59
+ export function getCalendarViewSlug(view: CalendarViewEnum): string {
60
+ return (
61
+ CALENDAR_VIEW_SLUGS[view] || CALENDAR_VIEW_SLUGS[CALENDAR_DEFAULT_VIEW]
62
+ );
63
+ }
64
+
65
+ /**
66
+ * Resolve a URL view slug, falling back to the default.
67
+ *
68
+ * Also accepts the enum spelling, so an old link or a hand-typed
69
+ * "?v=FOUR_DAYS" still lands somewhere sensible rather than silently
70
+ * resetting to the week.
71
+ */
72
+
73
+ export function parseCalendarViewSlug(
74
+ value: string | null | undefined,
75
+ ): CalendarViewEnum {
76
+ const raw = String(value || '')
77
+ .trim()
78
+ .toLowerCase();
79
+
80
+ if (VIEW_BY_SLUG[raw]) {
81
+ return VIEW_BY_SLUG[raw];
82
+ }
83
+
84
+ const asEnum = raw.toUpperCase() as CalendarViewEnum;
85
+
86
+ return CALENDAR_VIEW_SLUGS[asEnum] ? asEnum : CALENDAR_DEFAULT_VIEW;
87
+ }
88
+
89
+ /**
90
+ * Read the calendar's state out of the URL.
91
+ */
92
+
93
+ export function readCalendarUrlState(
94
+ searchParams: URLSearchParams,
95
+ now: Date,
96
+ timeZone?: string | null,
97
+ ): CalendarUrlState {
98
+ const calendars = searchParams.get(CALENDAR_SEARCH_PARAMS.hiddenCalendars);
99
+
100
+ return {
101
+ calendarId: searchParams.get('cal') || null,
102
+ roomId: searchParams.get('room') || null,
103
+ groupByRoom: searchParams.get('rooms') === '1',
104
+ panel: ['open', 'requests', 'timeoff', 'publish', 'settings'].includes(
105
+ searchParams.get('p') || '',
106
+ )
107
+ ? (searchParams.get('p') as CalendarUrlState['panel'])
108
+ : null,
109
+ openId: searchParams.get('o') || null,
110
+ view: parseCalendarViewSlug(searchParams.get(CALENDAR_SEARCH_PARAMS.view)),
111
+ anchorDate: parseCalendarDateParam(
112
+ searchParams.get(CALENDAR_SEARCH_PARAMS.date),
113
+ now,
114
+ timeZone,
115
+ ),
116
+ mineOnly: searchParams.get(CALENDAR_SEARCH_PARAMS.mine) === '1',
117
+ hiddenCalendarIds: calendars
118
+ ? calendars
119
+ .split(',')
120
+ .map((id) => id.trim())
121
+ .filter(Boolean)
122
+ : [],
123
+ };
124
+ }
125
+
126
+ /**
127
+ * Write the calendar's state back into a URL, dropping every default.
128
+ *
129
+ * Unrelated params on the URL are preserved — the calendar does not own the
130
+ * whole query string, and silently dropping somebody else's parameter is the
131
+ * kind of bug that only shows up in a link somebody already sent.
132
+ */
133
+
134
+ export function writeCalendarUrlState(
135
+ current: URLSearchParams,
136
+ next: Partial<CalendarUrlState>,
137
+ now: Date,
138
+ timeZone?: string | null,
139
+ ): URLSearchParams {
140
+ const params = new URLSearchParams(current);
141
+
142
+ const setOrDelete = (key: string, value: string | null) => {
143
+ if (value === null) {
144
+ params.delete(key);
145
+ } else {
146
+ params.set(key, value);
147
+ }
148
+ };
149
+
150
+ if (next.view !== undefined) {
151
+ setOrDelete(
152
+ CALENDAR_SEARCH_PARAMS.view,
153
+ next.view === CALENDAR_DEFAULT_VIEW
154
+ ? null
155
+ : getCalendarViewSlug(next.view),
156
+ );
157
+ }
158
+
159
+ if (next.anchorDate !== undefined) {
160
+ const dateKey = getCalendarDateKey(next.anchorDate, timeZone);
161
+
162
+ // Today needs no parameter: a calendar opened with no date shows now
163
+ setOrDelete(
164
+ CALENDAR_SEARCH_PARAMS.date,
165
+ dateKey === getCalendarDateKey(now, timeZone) ? null : dateKey,
166
+ );
167
+ }
168
+
169
+ if (next.mineOnly !== undefined) {
170
+ setOrDelete(CALENDAR_SEARCH_PARAMS.mine, next.mineOnly ? '1' : null);
171
+ }
172
+
173
+ if (next.hiddenCalendarIds !== undefined) {
174
+ setOrDelete(
175
+ CALENDAR_SEARCH_PARAMS.hiddenCalendars,
176
+ next.hiddenCalendarIds.length ? next.hiddenCalendarIds.join(',') : null,
177
+ );
178
+ }
179
+
180
+ for (const [field, key] of [
181
+ ['calendarId', 'cal'],
182
+ ['roomId', 'room'],
183
+ ['panel', 'p'],
184
+ ['openId', 'o'],
185
+ ] as const) {
186
+ if (next[field] !== undefined) setOrDelete(key, next[field] || null);
187
+ }
188
+ if (next.groupByRoom !== undefined)
189
+ setOrDelete('rooms', next.groupByRoom ? '1' : null);
190
+ return params;
191
+ }