@jsb188/calendar 1.1.10 → 1.1.12

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.
@@ -1,4 +1,7 @@
1
- import { DEFAULT_TIMEZONE, isValidTimeZone } from '@jsb188/app/utils/timeZone.ts';
1
+ import {
2
+ DEFAULT_TIMEZONE,
3
+ isValidTimeZone,
4
+ } from '@jsb188/app/utils/timeZone.ts';
2
5
  import { DateTime } from 'luxon';
3
6
  import {
4
7
  CALENDAR_AGENDA_DAY_COUNT,
@@ -29,16 +32,34 @@ import type { CalendarDayObj, CalendarRangeObj } from '../types/calendar.d.ts';
29
32
  * because a setting is stale is worse.
30
33
  */
31
34
 
32
- function getCalendarZone(timeZone?: string | null): string {
35
+ export function getCalendarTimeZone(timeZone?: string | null): string {
33
36
  return timeZone && isValidTimeZone(timeZone) ? timeZone : DEFAULT_TIMEZONE;
34
37
  }
35
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
+
36
52
  /**
37
53
  * Return the local date key ("yyyy-MM-dd") one instant falls on, in a zone.
38
54
  */
39
55
 
40
- export function getCalendarDateKey(instant: Date, timeZone?: string | null): string {
41
- return DateTime.fromJSDate(instant, { zone: getCalendarZone(timeZone) }).toFormat(CALENDAR_DATE_PARAM_FORMAT);
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);
42
63
  }
43
64
 
44
65
  /**
@@ -53,10 +74,12 @@ export function parseCalendarDateParam(
53
74
  now: Date,
54
75
  timeZone?: string | null,
55
76
  ): Date {
56
- const zone = getCalendarZone(timeZone);
77
+ const zone = getCalendarTimeZone(timeZone);
57
78
 
58
79
  if (value) {
59
- const parsed = DateTime.fromFormat(value, CALENDAR_DATE_PARAM_FORMAT, { zone });
80
+ const parsed = DateTime.fromFormat(value, CALENDAR_DATE_PARAM_FORMAT, {
81
+ zone,
82
+ });
60
83
 
61
84
  if (parsed.isValid) {
62
85
  return parsed.startOf('day').toJSDate();
@@ -130,7 +153,11 @@ function getWeekStart(day: DateTime, weekStartsOn: number): DateTime {
130
153
  * each navigation.
131
154
  */
132
155
 
133
- function buildMonthDays(anchor: DateTime, weekStartsOn: number, todayKey: string): CalendarDayObj[] {
156
+ function buildMonthDays(
157
+ anchor: DateTime,
158
+ weekStartsOn: number,
159
+ todayKey: string,
160
+ ): CalendarDayObj[] {
134
161
  const monthStart = anchor.startOf('month');
135
162
  const monthEnd = anchor.endOf('month');
136
163
  const gridStart = getWeekStart(monthStart, weekStartsOn);
@@ -139,11 +166,9 @@ function buildMonthDays(anchor: DateTime, weekStartsOn: number, todayKey: string
139
166
  for (let index = 0; index < 42; index++) {
140
167
  const day = gridStart.plus({ days: index });
141
168
 
142
- days.push(buildCalendarDay(
143
- day,
144
- todayKey,
145
- day >= monthStart && day <= monthEnd,
146
- ));
169
+ days.push(
170
+ buildCalendarDay(day, todayKey, day >= monthStart && day <= monthEnd),
171
+ );
147
172
  }
148
173
 
149
174
  return days;
@@ -184,10 +209,14 @@ export function getCalendarRange(p: {
184
209
  weekStartsOn?: number;
185
210
  }): CalendarRangeObj {
186
211
  const { view, anchorDate, now } = p;
187
- const timeZone = getCalendarZone(p.timeZone);
188
- const weekStartsOn = Number.isInteger(p.weekStartsOn) ? Number(p.weekStartsOn) : 0;
189
- const anchor = DateTime.fromJSDate(anchorDate, { zone: timeZone }).startOf('day');
190
- const todayKey = DateTime.fromJSDate(now, { zone: timeZone }).toFormat(CALENDAR_DATE_PARAM_FORMAT);
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
+ );
191
220
 
192
221
  const days = getCalendarViewDays({ view, anchor, weekStartsOn, todayKey });
193
222
 
@@ -214,8 +243,13 @@ function getCalendarViewDays(p: {
214
243
  const { view, anchor, weekStartsOn, todayKey } = p;
215
244
 
216
245
  switch (view) {
246
+ case 'ROSTER':
217
247
  case 'WEEK':
218
- return buildConsecutiveDays(getWeekStart(anchor, weekStartsOn), 7, todayKey);
248
+ return buildConsecutiveDays(
249
+ getWeekStart(anchor, weekStartsOn),
250
+ 7,
251
+ todayKey,
252
+ );
219
253
  case 'MONTH':
220
254
  return buildMonthDays(anchor, weekStartsOn, todayKey);
221
255
  case 'YEAR':
@@ -225,7 +259,11 @@ function getCalendarViewDays(p: {
225
259
  default:
226
260
  // DAY and FOUR_DAYS both run forward from the anchor, so clicking a
227
261
  // day in the month view lands on that day rather than on its week
228
- return buildConsecutiveDays(anchor, CALENDAR_VIEW_DAY_COUNTS[view] || 1, todayKey);
262
+ return buildConsecutiveDays(
263
+ anchor,
264
+ CALENDAR_VIEW_DAY_COUNTS[view] || 1,
265
+ todayKey,
266
+ );
229
267
  }
230
268
  }
231
269
 
@@ -244,9 +282,12 @@ export function getCalendarStepAnchor(p: {
244
282
  timeZone?: string | null;
245
283
  }): Date {
246
284
  const { view, anchorDate, direction } = p;
247
- const anchor = DateTime.fromJSDate(anchorDate, { zone: getCalendarZone(p.timeZone) }).startOf('day');
285
+ const anchor = DateTime.fromJSDate(anchorDate, {
286
+ zone: getCalendarTimeZone(p.timeZone),
287
+ }).startOf('day');
248
288
 
249
289
  switch (view) {
290
+ case 'ROSTER':
250
291
  case 'WEEK':
251
292
  return anchor.plus({ weeks: direction }).toJSDate();
252
293
  case 'MONTH':
@@ -254,9 +295,13 @@ export function getCalendarStepAnchor(p: {
254
295
  case 'YEAR':
255
296
  return anchor.plus({ years: direction }).toJSDate();
256
297
  case 'AGENDA':
257
- return anchor.plus({ days: direction * CALENDAR_AGENDA_DAY_COUNT }).toJSDate();
298
+ return anchor
299
+ .plus({ days: direction * CALENDAR_AGENDA_DAY_COUNT })
300
+ .toJSDate();
258
301
  default:
259
- return anchor.plus({ days: direction * (CALENDAR_VIEW_DAY_COUNTS[view] || 1) }).toJSDate();
302
+ return anchor
303
+ .plus({ days: direction * (CALENDAR_VIEW_DAY_COUNTS[view] || 1) })
304
+ .toJSDate();
260
305
  }
261
306
  }
262
307
 
@@ -276,7 +321,10 @@ export function getMinutesFromDayStart(instant: Date, dayStart: Date): number {
276
321
  * Return the instant a number of minutes past a day's local start.
277
322
  */
278
323
 
279
- export function getInstantFromDayMinutes(dayStart: Date, minutes: number): Date {
324
+ export function getInstantFromDayMinutes(
325
+ dayStart: Date,
326
+ minutes: number,
327
+ ): Date {
280
328
  return new Date(dayStart.getTime() + minutes * 60_000);
281
329
  }
282
330
 
@@ -296,7 +344,11 @@ export function getDayLengthMinutes(day: CalendarDayObj): number {
296
344
  * Snap a minute offset to the nearest increment, clamped into the day.
297
345
  */
298
346
 
299
- export function snapMinutes(minutes: number, snapTo: number, dayLengthMinutes: number): number {
347
+ export function snapMinutes(
348
+ minutes: number,
349
+ snapTo: number,
350
+ dayLengthMinutes: number,
351
+ ): number {
300
352
  const snapped = Math.round(minutes / snapTo) * snapTo;
301
353
 
302
354
  return Math.max(0, Math.min(dayLengthMinutes, snapped));
@@ -311,17 +363,26 @@ export function snapMinutes(minutes: number, snapTo: number, dayLengthMinutes: n
311
363
  * where its days fall.
312
364
  */
313
365
 
314
- export function getCalendarRangeTitle(range: CalendarRangeObj, locale?: string | null): string {
366
+ export function getCalendarRangeTitle(
367
+ range: CalendarRangeObj,
368
+ locale?: string | null,
369
+ ): string {
315
370
  const zone = range.timeZone;
316
- const first = DateTime.fromJSDate(range.days[0].startAt, { zone }).setLocale(locale || 'en');
371
+ const first = DateTime.fromJSDate(range.days[0].startAt, { zone }).setLocale(
372
+ locale || 'en',
373
+ );
317
374
  const lastDay = range.days[range.days.length - 1];
318
- const last = DateTime.fromJSDate(new Date(lastDay.endAt.getTime() - 1), { zone }).setLocale(locale || 'en');
375
+ const last = DateTime.fromJSDate(new Date(lastDay.endAt.getTime() - 1), {
376
+ zone,
377
+ }).setLocale(locale || 'en');
319
378
 
320
379
  switch (range.view) {
321
380
  case 'YEAR':
322
381
  return first.toFormat('yyyy');
323
382
  case 'MONTH':
324
- return DateTime.fromJSDate(range.anchorDate, { zone }).setLocale(locale || 'en').toFormat('LLLL yyyy');
383
+ return DateTime.fromJSDate(range.anchorDate, { zone })
384
+ .setLocale(locale || 'en')
385
+ .toFormat('LLLL yyyy');
325
386
  case 'DAY':
326
387
  return first.toFormat('cccc, LLLL d, yyyy');
327
388
  default:
@@ -1,161 +1,26 @@
1
- import { atom } from 'jotai';
2
- import type { CalendarEventObj, CalendarSelectionObj } from '../types/calendar.d.ts';
3
-
4
- /**
5
- * Calendar app state.
6
- *
7
- * Three rules from the grid packages are followed here deliberately:
8
- *
9
- * - **Atoms are created per mounted calendar by a factory**, never at module
10
- * scope. There is one Jotai store in the whole app, so isolation comes from
11
- * atom object identity: two calendars on one page get two bags and cannot
12
- * see each other's selection.
13
- *
14
- * - **View and anchor date are NOT here.** They live in the URL, because the
15
- * app shell remounts a route on every pathname change but not on a search
16
- * change — so a week in the URL survives navigation, is linkable, and does
17
- * not tear the calendar down when the user pages through months.
18
- *
19
- * - **Nothing that changes every animation frame is an atom.** A drag in
20
- * progress is a ref inside the grid; only its committed result reaches this
21
- * module. An atom written on pointermove would re-render every event in the
22
- * week sixty times a second.
23
- */
24
-
25
- /**
26
- * What the user is currently doing with the pointer, once it has committed to
27
- * being something. The in-flight pixel positions stay in the grid's refs.
28
- */
29
-
30
- export interface CalendarDraftObj {
31
- kind: 'CREATE' | 'MOVE' | 'RESIZE';
32
- // The event being moved or resized; null while creating a new one
33
- eventId: string | null;
34
- startAt: Date;
35
- endAt: Date;
36
- allDay: boolean;
37
- calendarId: string | null;
38
- }
39
-
40
- /**
41
- * The event detail popover's anchor and target.
42
- */
43
-
44
- export interface CalendarPopoverStateObj {
45
- eventId: string;
46
- // Viewport coordinates of the element that opened it
47
- anchorRect: { top: number; left: number; width: number; height: number };
48
- }
49
-
50
- /*
51
- * Return the empty visible-calendar map. Absent means "not yet decided", which
52
- * the page fills from the URL or from the calendar list; an explicit false is
53
- * what a user actually unticking a calendar writes.
54
- */
55
-
56
- export function getInitialVisibleCalendarIds(): Record<string, boolean> {
57
- return {};
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>;
58
12
  }
59
13
 
60
- /**
61
- * Create the atom group for one mounted calendar.
62
- */
63
-
64
- export function createCalendarStateAtoms(scopeKey = '') {
14
+ /* Create isolated committed interaction state; pointer movement stays in refs and authority stays in server rows. */
15
+ export function createCalendarStateAtoms(): CalendarStateAtoms {
65
16
  return {
66
- scopeKey,
67
-
68
- // The event whose detail popover is open, with where to anchor it
69
- popoverStateAtom: atom<CalendarPopoverStateObj | null>(null),
70
-
71
- // The committed result of a drag: a new block being drawn, or an
72
- // existing event moved or resized but not yet saved
73
- draftAtom: atom<CalendarDraftObj | null>(null),
74
-
75
- // A time range the user has selected without creating anything yet
76
- selectionAtom: atom<CalendarSelectionObj | null>(null),
77
-
78
- // Which overlaid calendars are drawn; absent means visible
79
- visibleCalendarIdsAtom: atom<Record<string, boolean>>(getInitialVisibleCalendarIds()),
80
-
81
- // Optimistic edits applied over server data while a mutation is in
82
- // flight, keyed by event id. Cleared when authority arrives, so a
83
- // failed save snaps back rather than leaving a phantom shift behind.
84
- optimisticEventsAtom: atom<Map<string, CalendarEventObj>>(new Map()),
85
-
86
- // Events the user has just deleted or cancelled, hidden until the
87
- // server confirms; same reasoning as above in the other direction
88
- optimisticallyRemovedEventIdsAtom: atom<Set<string>>(new Set<string>()),
89
-
90
- // The coverage board's currently inspected violation, if any
91
- inspectedViolationKeyAtom: atom<string | null>(null),
92
-
93
- // Whether the left rail (calendar list, mini month) is expanded
94
- railOpenAtom: atom(true),
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),
95
25
  };
96
26
  }
97
-
98
- export type CalendarStateAtoms = ReturnType<typeof createCalendarStateAtoms>;
99
-
100
- /**
101
- * Return the stable scope key for one mounted calendar.
102
- */
103
-
104
- export function getCalendarStateScopeKey(organizationId?: string | null): string {
105
- return ['calendar', organizationId || 'pending'].join(':');
106
- }
107
-
108
- /**
109
- * Apply the optimistic overlays to a list of server events.
110
- *
111
- * Kept as a plain function rather than a derived atom so the caller decides
112
- * when it runs: it is a full pass over the week, and it should happen once per
113
- * data change inside a memo, not once per subscriber.
114
- */
115
-
116
- export function applyCalendarOptimisticOverlays(
117
- events: CalendarEventObj[],
118
- optimisticEvents: Map<string, CalendarEventObj>,
119
- removedEventIds: Set<string>,
120
- ): CalendarEventObj[] {
121
- if (!optimisticEvents.size && !removedEventIds.size) {
122
- // Returning the SAME array reference on a no-op matters: this feeds a
123
- // memoized layout pass, and a fresh array would recompute the whole week
124
- return events;
125
- }
126
-
127
- const merged: CalendarEventObj[] = [];
128
- const seen = new Set<string>();
129
-
130
- for (const event of events) {
131
- if (removedEventIds.has(event.id)) {
132
- continue;
133
- }
134
-
135
- seen.add(event.id);
136
- merged.push(optimisticEvents.get(event.id) || event);
137
- }
138
-
139
- // An optimistic event with no server counterpart is one being created
140
- for (const [eventId, event] of optimisticEvents) {
141
- if (!seen.has(eventId) && !removedEventIds.has(eventId)) {
142
- merged.push(event);
143
- }
144
- }
145
-
146
- return merged;
147
- }
148
-
149
- /**
150
- * Return whether one calendar is drawn, treating "absent" as visible.
151
- *
152
- * A calendar the viewer has just been granted access to should appear without
153
- * them having to find and tick it; only an explicit untick hides one.
154
- */
155
-
156
- export function isCalendarVisible(
157
- visibleCalendarIds: Record<string, boolean>,
158
- calendarId: string,
159
- ): boolean {
160
- return visibleCalendarIds[calendarId] !== false;
161
- }
@@ -4,7 +4,10 @@ import {
4
4
  CALENDAR_VIEW_SLUGS,
5
5
  type CalendarViewEnum,
6
6
  } from '../constants/calendar.ts';
7
- import { getCalendarDateKey, parseCalendarDateParam } from './calendar-range.ts';
7
+ import {
8
+ getCalendarDateKey,
9
+ parseCalendarDateParam,
10
+ } from './calendar-range.ts';
8
11
 
9
12
  /**
10
13
  * The calendar's URL state.
@@ -27,6 +30,11 @@ import { getCalendarDateKey, parseCalendarDateParam } from './calendar-range.ts'
27
30
  */
28
31
 
29
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;
30
38
  view: CalendarViewEnum;
31
39
  anchorDate: Date;
32
40
  mineOnly: boolean;
@@ -38,7 +46,10 @@ export interface CalendarUrlState {
38
46
  }
39
47
 
40
48
  const VIEW_BY_SLUG: Record<string, CalendarViewEnum> = Object.fromEntries(
41
- Object.entries(CALENDAR_VIEW_SLUGS).map(([view, slug]) => [slug, view as CalendarViewEnum]),
49
+ Object.entries(CALENDAR_VIEW_SLUGS).map(([view, slug]) => [
50
+ slug,
51
+ view as CalendarViewEnum,
52
+ ]),
42
53
  );
43
54
 
44
55
  /**
@@ -46,7 +57,9 @@ const VIEW_BY_SLUG: Record<string, CalendarViewEnum> = Object.fromEntries(
46
57
  */
47
58
 
48
59
  export function getCalendarViewSlug(view: CalendarViewEnum): string {
49
- return CALENDAR_VIEW_SLUGS[view] || CALENDAR_VIEW_SLUGS[CALENDAR_DEFAULT_VIEW];
60
+ return (
61
+ CALENDAR_VIEW_SLUGS[view] || CALENDAR_VIEW_SLUGS[CALENDAR_DEFAULT_VIEW]
62
+ );
50
63
  }
51
64
 
52
65
  /**
@@ -57,8 +70,12 @@ export function getCalendarViewSlug(view: CalendarViewEnum): string {
57
70
  * resetting to the week.
58
71
  */
59
72
 
60
- export function parseCalendarViewSlug(value: string | null | undefined): CalendarViewEnum {
61
- const raw = String(value || '').trim().toLowerCase();
73
+ export function parseCalendarViewSlug(
74
+ value: string | null | undefined,
75
+ ): CalendarViewEnum {
76
+ const raw = String(value || '')
77
+ .trim()
78
+ .toLowerCase();
62
79
 
63
80
  if (VIEW_BY_SLUG[raw]) {
64
81
  return VIEW_BY_SLUG[raw];
@@ -81,10 +98,28 @@ export function readCalendarUrlState(
81
98
  const calendars = searchParams.get(CALENDAR_SEARCH_PARAMS.hiddenCalendars);
82
99
 
83
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,
84
110
  view: parseCalendarViewSlug(searchParams.get(CALENDAR_SEARCH_PARAMS.view)),
85
- anchorDate: parseCalendarDateParam(searchParams.get(CALENDAR_SEARCH_PARAMS.date), now, timeZone),
111
+ anchorDate: parseCalendarDateParam(
112
+ searchParams.get(CALENDAR_SEARCH_PARAMS.date),
113
+ now,
114
+ timeZone,
115
+ ),
86
116
  mineOnly: searchParams.get(CALENDAR_SEARCH_PARAMS.mine) === '1',
87
- hiddenCalendarIds: calendars ? calendars.split(',').map((id) => id.trim()).filter(Boolean) : [],
117
+ hiddenCalendarIds: calendars
118
+ ? calendars
119
+ .split(',')
120
+ .map((id) => id.trim())
121
+ .filter(Boolean)
122
+ : [],
88
123
  };
89
124
  }
90
125
 
@@ -115,7 +150,9 @@ export function writeCalendarUrlState(
115
150
  if (next.view !== undefined) {
116
151
  setOrDelete(
117
152
  CALENDAR_SEARCH_PARAMS.view,
118
- next.view === CALENDAR_DEFAULT_VIEW ? null : getCalendarViewSlug(next.view),
153
+ next.view === CALENDAR_DEFAULT_VIEW
154
+ ? null
155
+ : getCalendarViewSlug(next.view),
119
156
  );
120
157
  }
121
158
 
@@ -140,5 +177,15 @@ export function writeCalendarUrlState(
140
177
  );
141
178
  }
142
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);
143
190
  return params;
144
191
  }