@jsb188/calendar 1.1.10

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,161 @@
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 {};
58
+ }
59
+
60
+ /**
61
+ * Create the atom group for one mounted calendar.
62
+ */
63
+
64
+ export function createCalendarStateAtoms(scopeKey = '') {
65
+ 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),
95
+ };
96
+ }
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
+ }
@@ -0,0 +1,144 @@
1
+ import {
2
+ CALENDAR_DEFAULT_VIEW,
3
+ CALENDAR_SEARCH_PARAMS,
4
+ CALENDAR_VIEW_SLUGS,
5
+ type CalendarViewEnum,
6
+ } from '../constants/calendar.ts';
7
+ import { getCalendarDateKey, parseCalendarDateParam } from './calendar-range.ts';
8
+
9
+ /**
10
+ * The calendar's URL state.
11
+ *
12
+ * The URL is the calendar's state store for anything a person might want to
13
+ * link to or come back to: which view, which date, whose shifts, which
14
+ * calendars. It is kept deliberately terse and readable — one- and two-letter
15
+ * keys, lowercase view slugs, and every default omitted — so that
16
+ *
17
+ * /app/calendar
18
+ * /app/calendar?v=month&d=2026-07-25
19
+ * /app/calendar?me=1
20
+ *
21
+ * are what somebody actually sees in the address bar, rather than a query
22
+ * string carrying five parameters that all happen to be the default.
23
+ *
24
+ * Omitting defaults is not only cosmetic. It means "this week, everything" has
25
+ * exactly one URL instead of several equivalent ones, so the browser history
26
+ * and any shared link stay meaningful.
27
+ */
28
+
29
+ export interface CalendarUrlState {
30
+ view: CalendarViewEnum;
31
+ anchorDate: Date;
32
+ mineOnly: boolean;
33
+ // Calendars the viewer has explicitly HIDDEN — a blocklist, not a
34
+ // whitelist. Empty therefore means "show everything", which is what makes
35
+ // a calendar the viewer was just granted access to appear on its own
36
+ // instead of staying invisible until they find and tick it.
37
+ hiddenCalendarIds: string[];
38
+ }
39
+
40
+ const VIEW_BY_SLUG: Record<string, CalendarViewEnum> = Object.fromEntries(
41
+ Object.entries(CALENDAR_VIEW_SLUGS).map(([view, slug]) => [slug, view as CalendarViewEnum]),
42
+ );
43
+
44
+ /**
45
+ * Return the URL spelling of one view.
46
+ */
47
+
48
+ export function getCalendarViewSlug(view: CalendarViewEnum): string {
49
+ return CALENDAR_VIEW_SLUGS[view] || CALENDAR_VIEW_SLUGS[CALENDAR_DEFAULT_VIEW];
50
+ }
51
+
52
+ /**
53
+ * Resolve a URL view slug, falling back to the default.
54
+ *
55
+ * Also accepts the enum spelling, so an old link or a hand-typed
56
+ * "?v=FOUR_DAYS" still lands somewhere sensible rather than silently
57
+ * resetting to the week.
58
+ */
59
+
60
+ export function parseCalendarViewSlug(value: string | null | undefined): CalendarViewEnum {
61
+ const raw = String(value || '').trim().toLowerCase();
62
+
63
+ if (VIEW_BY_SLUG[raw]) {
64
+ return VIEW_BY_SLUG[raw];
65
+ }
66
+
67
+ const asEnum = raw.toUpperCase() as CalendarViewEnum;
68
+
69
+ return CALENDAR_VIEW_SLUGS[asEnum] ? asEnum : CALENDAR_DEFAULT_VIEW;
70
+ }
71
+
72
+ /**
73
+ * Read the calendar's state out of the URL.
74
+ */
75
+
76
+ export function readCalendarUrlState(
77
+ searchParams: URLSearchParams,
78
+ now: Date,
79
+ timeZone?: string | null,
80
+ ): CalendarUrlState {
81
+ const calendars = searchParams.get(CALENDAR_SEARCH_PARAMS.hiddenCalendars);
82
+
83
+ return {
84
+ view: parseCalendarViewSlug(searchParams.get(CALENDAR_SEARCH_PARAMS.view)),
85
+ anchorDate: parseCalendarDateParam(searchParams.get(CALENDAR_SEARCH_PARAMS.date), now, timeZone),
86
+ mineOnly: searchParams.get(CALENDAR_SEARCH_PARAMS.mine) === '1',
87
+ hiddenCalendarIds: calendars ? calendars.split(',').map((id) => id.trim()).filter(Boolean) : [],
88
+ };
89
+ }
90
+
91
+ /**
92
+ * Write the calendar's state back into a URL, dropping every default.
93
+ *
94
+ * Unrelated params on the URL are preserved — the calendar does not own the
95
+ * whole query string, and silently dropping somebody else's parameter is the
96
+ * kind of bug that only shows up in a link somebody already sent.
97
+ */
98
+
99
+ export function writeCalendarUrlState(
100
+ current: URLSearchParams,
101
+ next: Partial<CalendarUrlState>,
102
+ now: Date,
103
+ timeZone?: string | null,
104
+ ): URLSearchParams {
105
+ const params = new URLSearchParams(current);
106
+
107
+ const setOrDelete = (key: string, value: string | null) => {
108
+ if (value === null) {
109
+ params.delete(key);
110
+ } else {
111
+ params.set(key, value);
112
+ }
113
+ };
114
+
115
+ if (next.view !== undefined) {
116
+ setOrDelete(
117
+ CALENDAR_SEARCH_PARAMS.view,
118
+ next.view === CALENDAR_DEFAULT_VIEW ? null : getCalendarViewSlug(next.view),
119
+ );
120
+ }
121
+
122
+ if (next.anchorDate !== undefined) {
123
+ const dateKey = getCalendarDateKey(next.anchorDate, timeZone);
124
+
125
+ // Today needs no parameter: a calendar opened with no date shows now
126
+ setOrDelete(
127
+ CALENDAR_SEARCH_PARAMS.date,
128
+ dateKey === getCalendarDateKey(now, timeZone) ? null : dateKey,
129
+ );
130
+ }
131
+
132
+ if (next.mineOnly !== undefined) {
133
+ setOrDelete(CALENDAR_SEARCH_PARAMS.mine, next.mineOnly ? '1' : null);
134
+ }
135
+
136
+ if (next.hiddenCalendarIds !== undefined) {
137
+ setOrDelete(
138
+ CALENDAR_SEARCH_PARAMS.hiddenCalendars,
139
+ next.hiddenCalendarIds.length ? next.hiddenCalendarIds.join(',') : null,
140
+ );
141
+ }
142
+
143
+ return params;
144
+ }
package/src/main.ts ADDED
@@ -0,0 +1,29 @@
1
+ export { Calendar } from './modules/Calendar.tsx';
2
+ export { CalendarToolbarUI } from './ui/CalendarToolbarUI.tsx';
3
+ export type { CalendarToolbarUIProps } from './ui/CalendarToolbarUI.tsx';
4
+ export type { CalendarProps } from './modules/Calendar.tsx';
5
+ export {
6
+ CALENDAR_SEARCH_PARAMS,
7
+ CALENDAR_VIEW_ENUMS,
8
+ type CalendarViewEnum,
9
+ } from './constants/calendar.ts';
10
+ export {
11
+ getCalendarDateKey,
12
+ getCalendarRange,
13
+ getCalendarRangeTitle,
14
+ getCalendarStepAnchor,
15
+ parseCalendarDateParam,
16
+ } from './libs/calendar-range.ts';
17
+ export {
18
+ getCalendarViewSlug,
19
+ parseCalendarViewSlug,
20
+ readCalendarUrlState,
21
+ writeCalendarUrlState,
22
+ } from './libs/calendar-url.ts';
23
+ export type { CalendarUrlState } from './libs/calendar-url.ts';
24
+ export type {
25
+ CalendarDayObj,
26
+ CalendarEventObj,
27
+ CalendarRangeObj,
28
+ CalendarSourceObj,
29
+ } from './types/calendar.d.ts';