@moltenship/calendar-react 0.0.0-stage → 1.0.0-rc.1
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/LICENSE +21 -0
- package/README.md +27 -2
- package/dist/index.d.mts +686 -0
- package/dist/index.mjs +2353 -0
- package/package.json +52 -3
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,2353 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
import { anchorShowingDate, applyEventOverlay, busyResources, closedDates, createAnnotationSnapshot, createAvailabilitySnapshot, createEventSnapshotCache, createEventTransactions, createResourceTree, fitsAvailability, formatPlacementRange, keyboardSessionProposal, moveKeyboardCursor, projectTimeGridAnnotations, projectTimeGridAvailability, projectTimelineAvailability, readOnlyPolicy, resolveSecondaryTimeZones, resolveViewInstantRange, resolveViewLoadRange, resourceStatusAt, sameFocus, showsInResource, slotDuration, startKeyboardSession, visibleResources } from "@moltenship/calendar-core";
|
|
3
|
+
import { createContext, createElement, createRef, useCallback, useContext, useEffect, useId, useInsertionEffect, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
|
|
4
|
+
import { createSystemClock, plainDateIntervalContains } from "@moltenship/calendar-temporal";
|
|
5
|
+
//#region src/annotations.ts
|
|
6
|
+
/** The nearest root's annotations, shared by every factory so annotation hooks work in any view. */
|
|
7
|
+
const CalendarAnnotationsContext = createContext(null);
|
|
8
|
+
function useCalendarAnnotations() {
|
|
9
|
+
const annotations = useContext(CalendarAnnotationsContext);
|
|
10
|
+
if (annotations === null) throw new Error("calendar-hook-outside-root");
|
|
11
|
+
return annotations;
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* The root's annotations laid out beside a time grid's columns, one list of marks per column; see
|
|
15
|
+
* `projectTimeGridAnnotations`. Marks carry the root's source objects unchanged.
|
|
16
|
+
*/
|
|
17
|
+
function useTimeGridAnnotations(columns, { layout, maxLanes, minGap, minHeight } = {}) {
|
|
18
|
+
const { snapshot, sources } = useCalendarAnnotations();
|
|
19
|
+
return useMemo(() => projectTimeGridAnnotations(columns, snapshot, sources, {
|
|
20
|
+
layout,
|
|
21
|
+
maxLanes,
|
|
22
|
+
minGap,
|
|
23
|
+
minHeight
|
|
24
|
+
}), [
|
|
25
|
+
columns,
|
|
26
|
+
layout,
|
|
27
|
+
maxLanes,
|
|
28
|
+
minGap,
|
|
29
|
+
minHeight,
|
|
30
|
+
snapshot,
|
|
31
|
+
sources
|
|
32
|
+
]);
|
|
33
|
+
}
|
|
34
|
+
//#endregion
|
|
35
|
+
//#region src/interaction.ts
|
|
36
|
+
/** Time-grid slots when a view does not choose its own, as in the pointer layer. */
|
|
37
|
+
const DEFAULT_SNAP = Object.freeze({
|
|
38
|
+
increment: 15,
|
|
39
|
+
smallestUnit: "minute"
|
|
40
|
+
});
|
|
41
|
+
const CalendarInteractionContext = createContext(null);
|
|
42
|
+
const CalendarViewRuntimeContext = createContext(null);
|
|
43
|
+
function useInteractionRuntime() {
|
|
44
|
+
const runtime = useContext(CalendarInteractionContext);
|
|
45
|
+
if (runtime === null) throw new Error("calendar-hook-outside-root");
|
|
46
|
+
return runtime;
|
|
47
|
+
}
|
|
48
|
+
function useViewRuntime() {
|
|
49
|
+
const runtime = useContext(CalendarViewRuntimeContext);
|
|
50
|
+
if (runtime === null) throw new Error("calendar-view-hook-outside-active-view");
|
|
51
|
+
return runtime;
|
|
52
|
+
}
|
|
53
|
+
//#endregion
|
|
54
|
+
//#region src/announcer.ts
|
|
55
|
+
function buildMessage(messages, update, context) {
|
|
56
|
+
const build = messages[update.phase];
|
|
57
|
+
return build(update, context);
|
|
58
|
+
}
|
|
59
|
+
/** `getEnvironment` and `getResources` read the root's last commit when an update arrives. */
|
|
60
|
+
function createAnnouncerChannel(getEnvironment, getResources) {
|
|
61
|
+
const mounted = [];
|
|
62
|
+
function formatRange(placement) {
|
|
63
|
+
const { locale, timeZone } = getEnvironment();
|
|
64
|
+
return (mounted.at(-1)?.getMessages().formatRange ?? formatPlacementRange)(placement, {
|
|
65
|
+
locale,
|
|
66
|
+
timeZone
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
function resourceTitle(resourceId) {
|
|
70
|
+
return getResources().byId.get(resourceId)?.resource.title;
|
|
71
|
+
}
|
|
72
|
+
function say(build) {
|
|
73
|
+
const current = mounted.at(-1);
|
|
74
|
+
if (current === void 0) return;
|
|
75
|
+
const { locale, timeZone } = getEnvironment();
|
|
76
|
+
const text = build({
|
|
77
|
+
formatRange,
|
|
78
|
+
locale,
|
|
79
|
+
resourceTitle,
|
|
80
|
+
timeZone
|
|
81
|
+
}, current.getMessages());
|
|
82
|
+
if (text !== null && text !== "") current.speak(text);
|
|
83
|
+
}
|
|
84
|
+
return Object.freeze({
|
|
85
|
+
announcer: Object.freeze({
|
|
86
|
+
announce: (update) => say((context, messages) => buildMessage(messages, update, context)),
|
|
87
|
+
formatRange
|
|
88
|
+
}),
|
|
89
|
+
mount(getMessages, speak) {
|
|
90
|
+
const entry = {
|
|
91
|
+
getMessages,
|
|
92
|
+
speak
|
|
93
|
+
};
|
|
94
|
+
mounted.push(entry);
|
|
95
|
+
return () => {
|
|
96
|
+
const index = mounted.lastIndexOf(entry);
|
|
97
|
+
if (index !== -1) mounted.splice(index, 1);
|
|
98
|
+
};
|
|
99
|
+
},
|
|
100
|
+
say
|
|
101
|
+
});
|
|
102
|
+
}
|
|
103
|
+
/** Hidden from view but read by screen readers. */
|
|
104
|
+
const visuallyHidden = {
|
|
105
|
+
border: 0,
|
|
106
|
+
clipPath: "inset(50%)",
|
|
107
|
+
height: 1,
|
|
108
|
+
margin: -1,
|
|
109
|
+
overflow: "hidden",
|
|
110
|
+
padding: 0,
|
|
111
|
+
position: "absolute",
|
|
112
|
+
whiteSpace: "nowrap",
|
|
113
|
+
width: 1
|
|
114
|
+
};
|
|
115
|
+
/**
|
|
116
|
+
* A polite live region that speaks keyboard and pointer moves, resizes, and creates in the
|
|
117
|
+
* calendar's locale through `messages`. Render one inside `Root`.
|
|
118
|
+
*/
|
|
119
|
+
function Announcer({ messages, style, ...props }) {
|
|
120
|
+
const { announcements } = useInteractionRuntime();
|
|
121
|
+
const latest = useRef(messages);
|
|
122
|
+
useInsertionEffect(() => {
|
|
123
|
+
latest.current = messages;
|
|
124
|
+
});
|
|
125
|
+
const [spoken, setSpoken] = useState({
|
|
126
|
+
repeat: false,
|
|
127
|
+
text: ""
|
|
128
|
+
});
|
|
129
|
+
useLayoutEffect(() => announcements.mount(() => latest.current, (text) => setSpoken((last) => ({
|
|
130
|
+
repeat: last.text === text && !last.repeat,
|
|
131
|
+
text
|
|
132
|
+
}))), [announcements]);
|
|
133
|
+
return createElement("div", {
|
|
134
|
+
"aria-atomic": true,
|
|
135
|
+
"aria-live": "polite",
|
|
136
|
+
role: "status",
|
|
137
|
+
...props,
|
|
138
|
+
"data-calendar-part": "announcer",
|
|
139
|
+
style: {
|
|
140
|
+
...visuallyHidden,
|
|
141
|
+
...style
|
|
142
|
+
}
|
|
143
|
+
}, spoken.repeat ? `${spoken.text}\u00a0` : spoken.text);
|
|
144
|
+
}
|
|
145
|
+
/**
|
|
146
|
+
* The announcer views pass to the pointer layer (`useCalendarPointer({ announcer })`), so pointer
|
|
147
|
+
* gestures are spoken by the same messages and its preview labels ranges the same way.
|
|
148
|
+
*/
|
|
149
|
+
function useCalendarAnnouncer() {
|
|
150
|
+
return useInteractionRuntime().announcements.announcer;
|
|
151
|
+
}
|
|
152
|
+
//#endregion
|
|
153
|
+
//#region src/availability.ts
|
|
154
|
+
/** The nearest root's working hours, shared by every factory so the hooks work in any view. */
|
|
155
|
+
const CalendarAvailabilityContext = createContext(null);
|
|
156
|
+
/** The root's working hours: the calendar's, and each resource's on its time zone. */
|
|
157
|
+
function useCalendarAvailability() {
|
|
158
|
+
const availability = useContext(CalendarAvailabilityContext);
|
|
159
|
+
if (availability === null) throw new Error("calendar-hook-outside-root");
|
|
160
|
+
return availability;
|
|
161
|
+
}
|
|
162
|
+
/**
|
|
163
|
+
* The closed time of each time-grid column, as bands on its 24-hour axis with their reasons: the
|
|
164
|
+
* calendar's, or with `resourceId` that resource's, on its own time zone. See
|
|
165
|
+
* `projectTimeGridAvailability`.
|
|
166
|
+
*/
|
|
167
|
+
function useTimeGridAvailability(columns, resourceId) {
|
|
168
|
+
const schedule = useCalendarAvailability().forResource(resourceId ?? null);
|
|
169
|
+
return useMemo(() => projectTimeGridAvailability(columns, schedule), [columns, schedule]);
|
|
170
|
+
}
|
|
171
|
+
/**
|
|
172
|
+
* The closed time along a timeline of `columns`: the calendar's, or with `resourceId` that
|
|
173
|
+
* resource's. See `projectTimelineAvailability`.
|
|
174
|
+
*/
|
|
175
|
+
function useTimelineAvailability(columns, resourceId) {
|
|
176
|
+
const schedule = useCalendarAvailability().forResource(resourceId ?? null);
|
|
177
|
+
return useMemo(() => projectTimelineAvailability(columns, schedule), [columns, schedule]);
|
|
178
|
+
}
|
|
179
|
+
/**
|
|
180
|
+
* The dates of `range` with no open time on their day in the display time zone: the calendar's,
|
|
181
|
+
* or with `resourceId` that resource's. See `closedDates`.
|
|
182
|
+
*/
|
|
183
|
+
function useClosedDates(range, resourceId) {
|
|
184
|
+
const availability = useCalendarAvailability();
|
|
185
|
+
const schedule = availability.forResource(resourceId ?? null);
|
|
186
|
+
const { timeZone } = availability;
|
|
187
|
+
return useMemo(() => closedDates(range, schedule, timeZone), [
|
|
188
|
+
range,
|
|
189
|
+
schedule,
|
|
190
|
+
timeZone
|
|
191
|
+
]);
|
|
192
|
+
}
|
|
193
|
+
//#endregion
|
|
194
|
+
//#region src/context.ts
|
|
195
|
+
/** Each factory owns its contexts, so its hooks resolve its own root inside another calendar. */
|
|
196
|
+
function createCalendarContexts() {
|
|
197
|
+
return Object.freeze({
|
|
198
|
+
actions: createContext(null),
|
|
199
|
+
changes: createContext(null),
|
|
200
|
+
meta: createContext(null),
|
|
201
|
+
source: createContext(null),
|
|
202
|
+
state: createContext(null),
|
|
203
|
+
view: createContext(void 0)
|
|
204
|
+
});
|
|
205
|
+
}
|
|
206
|
+
/** The nearest root's clock, shared by every factory so `useNow` works inside any calendar. */
|
|
207
|
+
const CalendarNowSourceContext = createContext(void 0);
|
|
208
|
+
function useRootContext(context) {
|
|
209
|
+
const value = useContext(context);
|
|
210
|
+
if (value === null) throw new Error("calendar-hook-outside-root");
|
|
211
|
+
return value;
|
|
212
|
+
}
|
|
213
|
+
function useActiveViewContext(context) {
|
|
214
|
+
const view = useContext(context);
|
|
215
|
+
if (view === void 0) throw new Error("calendar-hook-outside-root");
|
|
216
|
+
return view;
|
|
217
|
+
}
|
|
218
|
+
//#endregion
|
|
219
|
+
//#region src/equality.ts
|
|
220
|
+
function sameElements(left, right) {
|
|
221
|
+
return left === right || left.length === right.length && left.every((value, index) => Object.is(value, right[index]));
|
|
222
|
+
}
|
|
223
|
+
/** Compares own enumerable properties with `Object.is`; non-objects compare with `Object.is`. */
|
|
224
|
+
function shallowEqual(left, right) {
|
|
225
|
+
if (Object.is(left, right)) return true;
|
|
226
|
+
if (typeof left !== "object" || typeof right !== "object" || left === null || right === null) return false;
|
|
227
|
+
const leftKeys = Object.keys(left);
|
|
228
|
+
return leftKeys.length === Object.keys(right).length && leftKeys.every((key) => Object.hasOwn(right, key) && Object.is(left[key], right[key]));
|
|
229
|
+
}
|
|
230
|
+
function samePlainDate(left, right) {
|
|
231
|
+
return left === right || left != null && right != null && left.equals(right);
|
|
232
|
+
}
|
|
233
|
+
function sameInstant$1(left, right) {
|
|
234
|
+
return left === right || left !== void 0 && right !== void 0 && left.equals(right);
|
|
235
|
+
}
|
|
236
|
+
function sameRange(left, right) {
|
|
237
|
+
return left === right || left !== void 0 && right !== void 0 && left.start.equals(right.start) && left.end.equals(right.end);
|
|
238
|
+
}
|
|
239
|
+
function sameWeekRules(left, right) {
|
|
240
|
+
return left === right || left.firstDay === right.firstDay && left.minimalDays === right.minimalDays && sameElements(left.weekend, right.weekend);
|
|
241
|
+
}
|
|
242
|
+
const isRecord = (value) => typeof value === "object" && value !== null;
|
|
243
|
+
/**
|
|
244
|
+
* Lists by element: identical values, or records `same` matches. Anything else, such as an
|
|
245
|
+
* invalid entry the snapshot reports, matches only itself.
|
|
246
|
+
*/
|
|
247
|
+
function sameList(left, right, same) {
|
|
248
|
+
if (left === right) return true;
|
|
249
|
+
if (!Array.isArray(left) || !Array.isArray(right) || left.length !== right.length) return false;
|
|
250
|
+
return Array.from(left).every((value, index) => {
|
|
251
|
+
const other = right[index];
|
|
252
|
+
return Object.is(value, other) || isRecord(value) && isRecord(other) && same(value, other);
|
|
253
|
+
});
|
|
254
|
+
}
|
|
255
|
+
/** Temporal dates and times by value; anything else, such as invalid input, by identity. */
|
|
256
|
+
function sameTemporal(left, right) {
|
|
257
|
+
if (Object.is(left, right)) return true;
|
|
258
|
+
if (left instanceof Temporal.PlainTime) return right instanceof Temporal.PlainTime && left.equals(right);
|
|
259
|
+
return left instanceof Temporal.PlainDate && right instanceof Temporal.PlainDate && left.equals(right);
|
|
260
|
+
}
|
|
261
|
+
function sameHours(left, right) {
|
|
262
|
+
return sameTemporal(left.start, right.start) && sameTemporal(left.end, right.end);
|
|
263
|
+
}
|
|
264
|
+
/**
|
|
265
|
+
* Compares working hours by value, so an inline `availability` keeps its shading cached. Invalid
|
|
266
|
+
* entries never throw here; the snapshot reports them.
|
|
267
|
+
*/
|
|
268
|
+
function sameAvailability(left, right) {
|
|
269
|
+
return left === right || isRecord(left) && isRecord(right) && left.timeZone === right.timeZone && sameList(left.weekly, right.weekly, (a, b) => sameHours(a, b) && sameList(a.days, b.days, Object.is)) && sameList(left.exceptions, right.exceptions, (a, b) => sameTemporal(a.date, b.date) && a.label === b.label && sameList(a.hours, b.hours, sameHours));
|
|
270
|
+
}
|
|
271
|
+
const sameZone = (left, right) => Object.is(left, right) || isRecord(left) && isRecord(right) && left.timeZone === right.timeZone && left.label === right.label;
|
|
272
|
+
/**
|
|
273
|
+
* Compares secondary time zones by value, so an inline list keeps the environment as it is. A
|
|
274
|
+
* single zone passed where a list belongs, which the root reports, compares by value too.
|
|
275
|
+
*/
|
|
276
|
+
function sameSecondaryTimeZones(left, right) {
|
|
277
|
+
return Array.isArray(left) && Array.isArray(right) ? sameList(left, right, sameZone) : sameZone(left, right);
|
|
278
|
+
}
|
|
279
|
+
//#endregion
|
|
280
|
+
//#region src/store.ts
|
|
281
|
+
const handlerNames = Object.freeze({
|
|
282
|
+
anchorDate: "onAnchorDateChange",
|
|
283
|
+
expandedResourceIds: "onExpandedResourceIdsChange",
|
|
284
|
+
focus: "onFocusChange",
|
|
285
|
+
selection: "onSelectionChange",
|
|
286
|
+
timeZone: "onTimeZoneChange",
|
|
287
|
+
view: "onViewChange"
|
|
288
|
+
});
|
|
289
|
+
const stateSlices = Object.keys(handlerNames);
|
|
290
|
+
const storeInternals = /* @__PURE__ */ new WeakMap();
|
|
291
|
+
function uniqueResourceIds(resourceIds) {
|
|
292
|
+
return Object.freeze([...new Set(resourceIds)]);
|
|
293
|
+
}
|
|
294
|
+
function sameSliceValue(slice, previous, next) {
|
|
295
|
+
if (slice === "anchorDate") return samePlainDate(previous, next);
|
|
296
|
+
if (slice === "expandedResourceIds") return sameElements(previous, next);
|
|
297
|
+
return Object.is(previous, next);
|
|
298
|
+
}
|
|
299
|
+
/** Overlays every defined controlled slice on the uncontrolled state. */
|
|
300
|
+
function mergeControlledState(state, controlled) {
|
|
301
|
+
if (controlled === void 0) return state;
|
|
302
|
+
const overlay = stateSlices.filter((slice) => controlled[slice] !== void 0);
|
|
303
|
+
if (overlay.length === 0) return state;
|
|
304
|
+
const merged = { ...state };
|
|
305
|
+
for (const slice of overlay) Object.assign(merged, { [slice]: controlled[slice] });
|
|
306
|
+
return Object.freeze(merged);
|
|
307
|
+
}
|
|
308
|
+
function getCalendarStoreInternals(store) {
|
|
309
|
+
const internals = storeInternals.get(store);
|
|
310
|
+
if (internals === void 0) throw new TypeError("calendar-store-not-created-by-createCalendarStore");
|
|
311
|
+
return internals;
|
|
312
|
+
}
|
|
313
|
+
function createCalendarStore(options) {
|
|
314
|
+
let state = Object.freeze({
|
|
315
|
+
anchorDate: options.defaultAnchorDate,
|
|
316
|
+
expandedResourceIds: uniqueResourceIds(options.defaultExpandedResourceIds ?? []),
|
|
317
|
+
focus: options.defaultFocus ?? null,
|
|
318
|
+
selection: options.defaultSelection ?? null,
|
|
319
|
+
timeZone: options.defaultTimeZone,
|
|
320
|
+
view: options.defaultView
|
|
321
|
+
});
|
|
322
|
+
const listeners = /* @__PURE__ */ new Set();
|
|
323
|
+
const mountedRoots = [];
|
|
324
|
+
function createActions(dispatch) {
|
|
325
|
+
return Object.freeze({
|
|
326
|
+
setAnchorDate: (next) => dispatch("anchorDate", next),
|
|
327
|
+
setExpandedResourceIds: (next) => dispatch("expandedResourceIds", next),
|
|
328
|
+
setFocus: (next) => dispatch("focus", next),
|
|
329
|
+
setSelection: (next) => dispatch("selection", next),
|
|
330
|
+
setTimeZone: (next) => dispatch("timeZone", next),
|
|
331
|
+
setView: (next) => dispatch("view", next)
|
|
332
|
+
});
|
|
333
|
+
}
|
|
334
|
+
function bind(initial) {
|
|
335
|
+
let current = initial;
|
|
336
|
+
let pending;
|
|
337
|
+
/**
|
|
338
|
+
* Values the owners of controlled slices were told about and have not committed: an owner
|
|
339
|
+
* that defers or declines a change still holds it.
|
|
340
|
+
*/
|
|
341
|
+
let unsettled = {};
|
|
342
|
+
const requestListeners = /* @__PURE__ */ new Set();
|
|
343
|
+
const read = () => mergeControlledState(mergeControlledState(state, current.controlled), pending);
|
|
344
|
+
function dispatch(slice, requested) {
|
|
345
|
+
const next = slice === "expandedResourceIds" ? uniqueResourceIds(requested) : requested;
|
|
346
|
+
for (const listener of requestListeners) listener(slice, next);
|
|
347
|
+
const previous = read()[slice];
|
|
348
|
+
const controlled = current.controlled[slice] !== void 0;
|
|
349
|
+
if (sameSliceValue(slice, previous, next)) {
|
|
350
|
+
const told = unsettled[slice];
|
|
351
|
+
if (!controlled || told === void 0 || sameSliceValue(slice, told, next)) return;
|
|
352
|
+
}
|
|
353
|
+
if (controlled) {
|
|
354
|
+
if (pending === void 0) queueMicrotask(() => pending = void 0);
|
|
355
|
+
pending = {
|
|
356
|
+
...pending,
|
|
357
|
+
[slice]: next
|
|
358
|
+
};
|
|
359
|
+
const settled = sameSliceValue(slice, current.controlled[slice], next);
|
|
360
|
+
unsettled = {
|
|
361
|
+
...unsettled,
|
|
362
|
+
[slice]: settled ? void 0 : next
|
|
363
|
+
};
|
|
364
|
+
} else {
|
|
365
|
+
state = Object.freeze({
|
|
366
|
+
...state,
|
|
367
|
+
[slice]: next
|
|
368
|
+
});
|
|
369
|
+
for (const listener of listeners) listener();
|
|
370
|
+
}
|
|
371
|
+
const handler = current.handlers[handlerNames[slice]];
|
|
372
|
+
handler?.(next, Object.freeze({
|
|
373
|
+
controlled,
|
|
374
|
+
previous,
|
|
375
|
+
slice
|
|
376
|
+
}));
|
|
377
|
+
}
|
|
378
|
+
const binding = Object.freeze({
|
|
379
|
+
actions: createActions(dispatch),
|
|
380
|
+
attach: () => {
|
|
381
|
+
mountedRoots.push(binding);
|
|
382
|
+
return () => {
|
|
383
|
+
const index = mountedRoots.lastIndexOf(binding);
|
|
384
|
+
if (index !== -1) mountedRoots.splice(index, 1);
|
|
385
|
+
};
|
|
386
|
+
},
|
|
387
|
+
commit: (next) => {
|
|
388
|
+
const previous = current;
|
|
389
|
+
current = next;
|
|
390
|
+
for (const slice of stateSlices) {
|
|
391
|
+
const committed = next.controlled[slice];
|
|
392
|
+
if (unsettled[slice] !== void 0 && (committed === void 0 || !sameSliceValue(slice, previous.controlled[slice], committed))) unsettled = {
|
|
393
|
+
...unsettled,
|
|
394
|
+
[slice]: void 0
|
|
395
|
+
};
|
|
396
|
+
}
|
|
397
|
+
if (pending === void 0) return;
|
|
398
|
+
const retained = { ...pending };
|
|
399
|
+
for (const slice of stateSlices) {
|
|
400
|
+
if (retained[slice] === void 0) continue;
|
|
401
|
+
const committed = next.controlled[slice];
|
|
402
|
+
if (committed === void 0 || !sameSliceValue(slice, previous.controlled[slice], committed)) delete retained[slice];
|
|
403
|
+
}
|
|
404
|
+
pending = stateSlices.some((slice) => retained[slice] !== void 0) ? retained : void 0;
|
|
405
|
+
},
|
|
406
|
+
read,
|
|
407
|
+
subscribeRequests: (listener) => {
|
|
408
|
+
requestListeners.add(listener);
|
|
409
|
+
return () => {
|
|
410
|
+
requestListeners.delete(listener);
|
|
411
|
+
};
|
|
412
|
+
}
|
|
413
|
+
});
|
|
414
|
+
return binding;
|
|
415
|
+
}
|
|
416
|
+
const unbound = bind({
|
|
417
|
+
controlled: {},
|
|
418
|
+
handlers: {}
|
|
419
|
+
});
|
|
420
|
+
const owner = () => mountedRoots.at(-1) ?? unbound;
|
|
421
|
+
const store = {
|
|
422
|
+
actions: Object.freeze({
|
|
423
|
+
setAnchorDate: (next) => owner().actions.setAnchorDate(next),
|
|
424
|
+
setExpandedResourceIds: (next) => owner().actions.setExpandedResourceIds(next),
|
|
425
|
+
setFocus: (next) => owner().actions.setFocus(next),
|
|
426
|
+
setSelection: (next) => owner().actions.setSelection(next),
|
|
427
|
+
setTimeZone: (next) => owner().actions.setTimeZone(next),
|
|
428
|
+
setView: (next) => owner().actions.setView(next)
|
|
429
|
+
}),
|
|
430
|
+
getSnapshot: () => state,
|
|
431
|
+
subscribe: (listener) => {
|
|
432
|
+
listeners.add(listener);
|
|
433
|
+
return () => {
|
|
434
|
+
listeners.delete(listener);
|
|
435
|
+
};
|
|
436
|
+
}
|
|
437
|
+
};
|
|
438
|
+
storeInternals.set(store, { bind });
|
|
439
|
+
return store;
|
|
440
|
+
}
|
|
441
|
+
//#endregion
|
|
442
|
+
//#region src/use-stable-value.ts
|
|
443
|
+
/** Returns the previous value while `isEqual` considers the next one equivalent. */
|
|
444
|
+
function useStableValue(value, isEqual) {
|
|
445
|
+
const [stable, setStable] = useState(value);
|
|
446
|
+
if (stable === value || isEqual(stable, value)) return stable;
|
|
447
|
+
setStable(() => value);
|
|
448
|
+
return value;
|
|
449
|
+
}
|
|
450
|
+
//#endregion
|
|
451
|
+
//#region src/state-binding.ts
|
|
452
|
+
const uncommittedBinding = Object.freeze({
|
|
453
|
+
controlled: {},
|
|
454
|
+
handlers: {}
|
|
455
|
+
});
|
|
456
|
+
function sameControlledState(left, right) {
|
|
457
|
+
return samePlainDate(left.anchorDate, right.anchorDate) && (left.expandedResourceIds === right.expandedResourceIds || left.expandedResourceIds !== void 0 && right.expandedResourceIds !== void 0 && sameElements(left.expandedResourceIds, right.expandedResourceIds)) && Object.is(left.focus, right.focus) && Object.is(left.selection, right.selection) && left.timeZone === right.timeZone && left.view === right.view;
|
|
458
|
+
}
|
|
459
|
+
function createStateSource(store, controlled) {
|
|
460
|
+
let base;
|
|
461
|
+
let merged;
|
|
462
|
+
return Object.freeze({
|
|
463
|
+
getSnapshot: () => {
|
|
464
|
+
const next = store.getSnapshot();
|
|
465
|
+
if (next !== base || merged === void 0) {
|
|
466
|
+
base = next;
|
|
467
|
+
merged = mergeControlledState(next, controlled);
|
|
468
|
+
}
|
|
469
|
+
return merged;
|
|
470
|
+
},
|
|
471
|
+
subscribe: store.subscribe
|
|
472
|
+
});
|
|
473
|
+
}
|
|
474
|
+
/**
|
|
475
|
+
* Binds a store to a root's controlled slices and handlers. Controlled values are read during
|
|
476
|
+
* render, so they are current in the first render that receives them, and Temporal or array values
|
|
477
|
+
* that are recreated inline keep their identity while they stay equal.
|
|
478
|
+
*/
|
|
479
|
+
function useCalendarStateBinding(injectedStore, defaults, { controlled: controlledInput, handlers }) {
|
|
480
|
+
const ownedStore = useRef(null);
|
|
481
|
+
if (injectedStore === void 0) ownedStore.current ??= createCalendarStore(defaults());
|
|
482
|
+
const store = injectedStore ?? ownedStore.current;
|
|
483
|
+
if (store === null) throw new Error("calendar-store-not-created");
|
|
484
|
+
const internals = getCalendarStoreInternals(store);
|
|
485
|
+
const controlled = useStableValue(controlledInput, sameControlledState);
|
|
486
|
+
const binding = useMemo(() => internals.bind(uncommittedBinding), [internals]);
|
|
487
|
+
useInsertionEffect(() => binding.commit({
|
|
488
|
+
controlled,
|
|
489
|
+
handlers
|
|
490
|
+
}));
|
|
491
|
+
useInsertionEffect(() => binding.attach(), [binding]);
|
|
492
|
+
const source = useMemo(() => createStateSource(store, controlled), [controlled, store]);
|
|
493
|
+
return {
|
|
494
|
+
binding,
|
|
495
|
+
source,
|
|
496
|
+
state: useSyncExternalStore(source.subscribe, source.getSnapshot, source.getSnapshot),
|
|
497
|
+
store
|
|
498
|
+
};
|
|
499
|
+
}
|
|
500
|
+
/** Subscribes once per source; inline selectors and `isEqual` callbacks are read per render. */
|
|
501
|
+
function useStateSelector(source, selector, { isEqual = Object.is } = {}) {
|
|
502
|
+
const committed = useRef(null);
|
|
503
|
+
const [getSelection, getServerSelection] = useMemo(() => {
|
|
504
|
+
let memo;
|
|
505
|
+
const select = (state) => {
|
|
506
|
+
if (memo !== void 0 && memo.state === state) return memo.selected;
|
|
507
|
+
const next = selector(state);
|
|
508
|
+
const previous = memo ?? committed.current;
|
|
509
|
+
const selected = previous !== null && isEqual(previous.selected, next) ? previous.selected : next;
|
|
510
|
+
memo = {
|
|
511
|
+
selected,
|
|
512
|
+
state
|
|
513
|
+
};
|
|
514
|
+
return selected;
|
|
515
|
+
};
|
|
516
|
+
const client = () => select(source.getSnapshot());
|
|
517
|
+
const server = source.getServerSnapshot;
|
|
518
|
+
return [client, server === void 0 ? client : () => select(server())];
|
|
519
|
+
}, [
|
|
520
|
+
isEqual,
|
|
521
|
+
selector,
|
|
522
|
+
source
|
|
523
|
+
]);
|
|
524
|
+
const selected = useSyncExternalStore(source.subscribe, getSelection, getServerSelection);
|
|
525
|
+
useInsertionEffect(() => {
|
|
526
|
+
committed.current = { selected };
|
|
527
|
+
});
|
|
528
|
+
return selected;
|
|
529
|
+
}
|
|
530
|
+
//#endregion
|
|
531
|
+
//#region src/roving-focus.ts
|
|
532
|
+
/** Whether `focus` is on an element that shows `target` across `days` dates. */
|
|
533
|
+
function focusLandsOn(focus, target, days) {
|
|
534
|
+
if (focus.kind === "event" && target.kind === "event") {
|
|
535
|
+
const offset = target.date.until(focus.date).days;
|
|
536
|
+
return focus.eventId === target.eventId && focus.resourceId === target.resourceId && offset >= 0 && offset < days;
|
|
537
|
+
}
|
|
538
|
+
return sameFocus(focus, target);
|
|
539
|
+
}
|
|
540
|
+
/**
|
|
541
|
+
* `focus` as it lands on an element showing `target` across `days` dates, or `null` when it does
|
|
542
|
+
* not. A resource on only one side matches, so focus carries over between views with and without
|
|
543
|
+
* resources, and then takes the element's resource, keeping its date: one copy is the tab stop,
|
|
544
|
+
* and keys act in the resource it shows.
|
|
545
|
+
*/
|
|
546
|
+
function landOn(focus, target, days) {
|
|
547
|
+
const { resourceId } = target;
|
|
548
|
+
if (focus.resourceId === resourceId) return focusLandsOn(focus, target, days) ? focus : null;
|
|
549
|
+
if (focus.resourceId !== void 0 && resourceId !== void 0) return null;
|
|
550
|
+
const landed = {
|
|
551
|
+
...focus,
|
|
552
|
+
resourceId
|
|
553
|
+
};
|
|
554
|
+
return focusLandsOn(landed, target, days) ? landed : null;
|
|
555
|
+
}
|
|
556
|
+
function createRovingFocusStore(initialEntry) {
|
|
557
|
+
const items = /* @__PURE__ */ new Map();
|
|
558
|
+
const listeners = /* @__PURE__ */ new Set();
|
|
559
|
+
let focus = null;
|
|
560
|
+
let getEntry = initialEntry;
|
|
561
|
+
let entryCommand = "home";
|
|
562
|
+
let resolved = null;
|
|
563
|
+
/**
|
|
564
|
+
* DOM focus owed after the next update: to the tab stop, as keyboard navigation asks, or only
|
|
565
|
+
* to the focused target once it renders, after the element holding DOM focus went away.
|
|
566
|
+
*/
|
|
567
|
+
let owed = null;
|
|
568
|
+
/**
|
|
569
|
+
* The last element let go while it held DOM focus. It can stay in the document, as a scrolling
|
|
570
|
+
* view keeps days around the visible ones, and focus on it is still the view's to move.
|
|
571
|
+
*/
|
|
572
|
+
let released = null;
|
|
573
|
+
function find(target) {
|
|
574
|
+
if (target === null) return void 0;
|
|
575
|
+
let compatible;
|
|
576
|
+
for (const [element, item] of items) {
|
|
577
|
+
const landed = landOn(target, item.target, item.days);
|
|
578
|
+
if (landed === target) return {
|
|
579
|
+
element,
|
|
580
|
+
target
|
|
581
|
+
};
|
|
582
|
+
if (landed !== null) compatible ??= {
|
|
583
|
+
element,
|
|
584
|
+
target: landed
|
|
585
|
+
};
|
|
586
|
+
}
|
|
587
|
+
return compatible;
|
|
588
|
+
}
|
|
589
|
+
function resolve() {
|
|
590
|
+
if (resolved !== null) return resolved;
|
|
591
|
+
const entry = getEntry(entryCommand);
|
|
592
|
+
if (items.size === 0) return resolved = { target: entry ?? focus };
|
|
593
|
+
const found = find(focus);
|
|
594
|
+
if (found !== void 0) return resolved = {
|
|
595
|
+
...found,
|
|
596
|
+
isFocus: true
|
|
597
|
+
};
|
|
598
|
+
const entered = find(entry);
|
|
599
|
+
if (entered !== void 0) return resolved = entered;
|
|
600
|
+
const [element] = [...items.keys()].sort((left, right) => left.compareDocumentPosition(right) & Node.DOCUMENT_POSITION_FOLLOWING ? -1 : 1);
|
|
601
|
+
return resolved = {
|
|
602
|
+
element,
|
|
603
|
+
target: element === void 0 ? null : items.get(element).target
|
|
604
|
+
};
|
|
605
|
+
}
|
|
606
|
+
function changed() {
|
|
607
|
+
resolved = null;
|
|
608
|
+
for (const listener of listeners) listener();
|
|
609
|
+
}
|
|
610
|
+
let notifying = false;
|
|
611
|
+
/**
|
|
612
|
+
* `changed` for elements coming and going: a commit registers them one by one, hundreds in a
|
|
613
|
+
* year of days, so their elements hear once, after it, rather than once per element.
|
|
614
|
+
*/
|
|
615
|
+
function changedLater() {
|
|
616
|
+
resolved = null;
|
|
617
|
+
if (notifying) return;
|
|
618
|
+
notifying = true;
|
|
619
|
+
queueMicrotask(() => {
|
|
620
|
+
notifying = false;
|
|
621
|
+
changed();
|
|
622
|
+
});
|
|
623
|
+
}
|
|
624
|
+
function itemAt(node) {
|
|
625
|
+
for (let current = node; current !== null; current = current.parentNode) {
|
|
626
|
+
const item = items.get(current);
|
|
627
|
+
if (item !== void 0) return item;
|
|
628
|
+
}
|
|
629
|
+
}
|
|
630
|
+
/** Focuses the tab stop unless focus has moved elsewhere on the page in the meantime. */
|
|
631
|
+
function focusNow() {
|
|
632
|
+
const { element, isFocus = false } = resolve();
|
|
633
|
+
if (owed === "focus" && !isFocus) return;
|
|
634
|
+
owed = null;
|
|
635
|
+
const active = document.activeElement;
|
|
636
|
+
if (element === void 0 || element === active) return;
|
|
637
|
+
const ours = itemAt(active) !== void 0 || released?.contains(active) === true;
|
|
638
|
+
if (active !== null && active !== document.body && !ours) return;
|
|
639
|
+
released = null;
|
|
640
|
+
element.focus();
|
|
641
|
+
}
|
|
642
|
+
let retrying = false;
|
|
643
|
+
/**
|
|
644
|
+
* Retries owed focus once the commit that registered an element is done. By then this commit's
|
|
645
|
+
* focus has reached the store, so a newer focus wins over the element that came back.
|
|
646
|
+
*/
|
|
647
|
+
function retryOwedFocus() {
|
|
648
|
+
if (retrying) return;
|
|
649
|
+
retrying = true;
|
|
650
|
+
queueMicrotask(() => {
|
|
651
|
+
retrying = false;
|
|
652
|
+
if (owed === "focus") focusNow();
|
|
653
|
+
});
|
|
654
|
+
}
|
|
655
|
+
return Object.freeze({
|
|
656
|
+
enterFromEnd() {
|
|
657
|
+
entryCommand = "end";
|
|
658
|
+
},
|
|
659
|
+
focusAt(node) {
|
|
660
|
+
const item = itemAt(node);
|
|
661
|
+
if (item === void 0) return focus;
|
|
662
|
+
return (focus === null ? null : landOn(focus, item.target, item.days)) ?? item.target;
|
|
663
|
+
},
|
|
664
|
+
focusTabStop(when) {
|
|
665
|
+
owed = "tab-stop";
|
|
666
|
+
if (when === "now") focusNow();
|
|
667
|
+
},
|
|
668
|
+
isTabStop(target, days) {
|
|
669
|
+
const stop = resolve().target;
|
|
670
|
+
return stop !== null && focusLandsOn(stop, target, days);
|
|
671
|
+
},
|
|
672
|
+
register(element, target, days) {
|
|
673
|
+
items.set(element, {
|
|
674
|
+
days,
|
|
675
|
+
target
|
|
676
|
+
});
|
|
677
|
+
changedLater();
|
|
678
|
+
if (owed === "focus") retryOwedFocus();
|
|
679
|
+
return () => {
|
|
680
|
+
if (items.get(element)?.target !== target) return;
|
|
681
|
+
if (element.contains(document.activeElement)) {
|
|
682
|
+
owed ??= "focus";
|
|
683
|
+
released = element;
|
|
684
|
+
}
|
|
685
|
+
items.delete(element);
|
|
686
|
+
changedLater();
|
|
687
|
+
};
|
|
688
|
+
},
|
|
689
|
+
subscribe(listener) {
|
|
690
|
+
listeners.add(listener);
|
|
691
|
+
return () => {
|
|
692
|
+
listeners.delete(listener);
|
|
693
|
+
};
|
|
694
|
+
},
|
|
695
|
+
update(nextFocus, nextEntry) {
|
|
696
|
+
focus = nextFocus;
|
|
697
|
+
getEntry = nextEntry;
|
|
698
|
+
if (nextFocus !== null) entryCommand = "home";
|
|
699
|
+
changed();
|
|
700
|
+
if (owed !== null) focusNow();
|
|
701
|
+
}
|
|
702
|
+
});
|
|
703
|
+
}
|
|
704
|
+
const selectFocus = (state) => state.focus;
|
|
705
|
+
/** The active view's entry points, from its navigation with no focus. */
|
|
706
|
+
function viewEntry(view) {
|
|
707
|
+
return (command) => {
|
|
708
|
+
if (view === null) return null;
|
|
709
|
+
const { definition, environment, options, projection, range } = view;
|
|
710
|
+
const result = definition.strategy.getSpatialNavigation?.({
|
|
711
|
+
command,
|
|
712
|
+
environment,
|
|
713
|
+
focus: null,
|
|
714
|
+
options,
|
|
715
|
+
projection,
|
|
716
|
+
range,
|
|
717
|
+
snap: DEFAULT_SNAP
|
|
718
|
+
});
|
|
719
|
+
return result != null && "focus" in result ? result.focus : null;
|
|
720
|
+
};
|
|
721
|
+
}
|
|
722
|
+
/**
|
|
723
|
+
* Keeps the active view's roving store on the root's focus. Rendered after the view, so the
|
|
724
|
+
* elements of a commit are registered before focus moves to one of them.
|
|
725
|
+
*/
|
|
726
|
+
function RovingFocusSync({ roving, source, view }) {
|
|
727
|
+
const focus = useStateSelector(source, selectFocus);
|
|
728
|
+
const entry = useMemo(() => viewEntry(view), [view]);
|
|
729
|
+
useLayoutEffect(() => roving.update(focus, entry), [
|
|
730
|
+
entry,
|
|
731
|
+
focus,
|
|
732
|
+
roving
|
|
733
|
+
]);
|
|
734
|
+
return null;
|
|
735
|
+
}
|
|
736
|
+
function focusKey(target) {
|
|
737
|
+
const { resourceId } = target;
|
|
738
|
+
const resource = resourceId === void 0 ? "" : resourceId === null ? "|unassigned" : `|${typeof resourceId}:${resourceId}`;
|
|
739
|
+
switch (target.kind) {
|
|
740
|
+
case "day": return `day:${target.date.toString()}${resource}`;
|
|
741
|
+
case "slot": return `slot:${target.date.toString()}T${target.time.toString()}${resource}`;
|
|
742
|
+
case "event": return `event:${typeof target.eventId}:${target.eventId}@${target.date.toString()}${resource}`;
|
|
743
|
+
}
|
|
744
|
+
}
|
|
745
|
+
/**
|
|
746
|
+
* Props for one focusable element of a view: a day cell, a slot, or an event. The view's one tab
|
|
747
|
+
* stop gets `tabIndex={0}`; focusing an element makes it the calendar's focus, and keyboard
|
|
748
|
+
* navigation moves DOM focus to the new target, even when it renders in a new place. Only the
|
|
749
|
+
* elements whose tab stop changes re-render.
|
|
750
|
+
*/
|
|
751
|
+
function useRovingFocus(target, { days = 1 } = {}) {
|
|
752
|
+
const { actions, read } = useInteractionRuntime();
|
|
753
|
+
const { roving } = useViewRuntime();
|
|
754
|
+
const latest = useRef(target);
|
|
755
|
+
useInsertionEffect(() => {
|
|
756
|
+
latest.current = target;
|
|
757
|
+
});
|
|
758
|
+
const isTabStop = () => roving.isTabStop(target, days);
|
|
759
|
+
const tabStop = useSyncExternalStore(roving.subscribe, isTabStop, isTabStop);
|
|
760
|
+
const key = focusKey(target);
|
|
761
|
+
const ref = useCallback((element) => element === null ? void 0 : roving.register(element, latest.current, days), [
|
|
762
|
+
days,
|
|
763
|
+
key,
|
|
764
|
+
roving
|
|
765
|
+
]);
|
|
766
|
+
return {
|
|
767
|
+
onFocus: useCallback((event) => {
|
|
768
|
+
if (event.target !== event.currentTarget) return;
|
|
769
|
+
const focus = read().focus;
|
|
770
|
+
const landed = focus === null ? null : landOn(focus, latest.current, days);
|
|
771
|
+
if (landed === null || landed !== focus) actions.setFocus(landed ?? latest.current);
|
|
772
|
+
}, [
|
|
773
|
+
actions,
|
|
774
|
+
days,
|
|
775
|
+
read
|
|
776
|
+
]),
|
|
777
|
+
ref,
|
|
778
|
+
tabIndex: tabStop ? 0 : -1
|
|
779
|
+
};
|
|
780
|
+
}
|
|
781
|
+
//#endregion
|
|
782
|
+
//#region src/parts.ts
|
|
783
|
+
const selectView = (state) => state.view;
|
|
784
|
+
function useComposedRef(internalRef, externalRef) {
|
|
785
|
+
return useCallback((node) => {
|
|
786
|
+
internalRef.current = node;
|
|
787
|
+
const externalCleanup = typeof externalRef === "function" ? externalRef(node) : void 0;
|
|
788
|
+
if (externalRef !== null && externalRef !== void 0 && typeof externalRef !== "function") externalRef.current = node;
|
|
789
|
+
if (node === null) return void 0;
|
|
790
|
+
return () => {
|
|
791
|
+
internalRef.current = null;
|
|
792
|
+
if (typeof externalRef === "function") {
|
|
793
|
+
if (typeof externalCleanup === "function") externalCleanup();
|
|
794
|
+
else externalRef(null);
|
|
795
|
+
} else if (externalRef !== null && externalRef !== void 0) externalRef.current = null;
|
|
796
|
+
};
|
|
797
|
+
}, [externalRef, internalRef]);
|
|
798
|
+
}
|
|
799
|
+
/** Builds the compound parts that read one factory's root. */
|
|
800
|
+
function createCalendarParts(contexts) {
|
|
801
|
+
function Frame({ children, ref, ...props }) {
|
|
802
|
+
const meta = useRootContext(contexts.meta);
|
|
803
|
+
const composedRef = useComposedRef(meta.refs.frame, ref);
|
|
804
|
+
return createElement("section", {
|
|
805
|
+
"aria-labelledby": meta.ids.title,
|
|
806
|
+
...props,
|
|
807
|
+
"data-calendar-instance": meta.instanceId,
|
|
808
|
+
"data-calendar-part": "frame",
|
|
809
|
+
id: meta.ids.frame,
|
|
810
|
+
ref: composedRef
|
|
811
|
+
}, children);
|
|
812
|
+
}
|
|
813
|
+
function Toolbar({ children, ref, ...props }) {
|
|
814
|
+
const composedRef = useComposedRef(useRootContext(contexts.meta).refs.toolbar, ref);
|
|
815
|
+
return createElement("header", {
|
|
816
|
+
...props,
|
|
817
|
+
"data-calendar-part": "toolbar",
|
|
818
|
+
ref: composedRef
|
|
819
|
+
}, children);
|
|
820
|
+
}
|
|
821
|
+
function Viewport({ children, ref, ...props }) {
|
|
822
|
+
const meta = useRootContext(contexts.meta);
|
|
823
|
+
const composedRef = useComposedRef(meta.refs.viewport, ref);
|
|
824
|
+
return createElement("div", {
|
|
825
|
+
...props,
|
|
826
|
+
"data-calendar-part": "viewport",
|
|
827
|
+
id: meta.ids.viewport,
|
|
828
|
+
ref: composedRef
|
|
829
|
+
}, children);
|
|
830
|
+
}
|
|
831
|
+
function Title({ children, ref, ...props }) {
|
|
832
|
+
const meta = useRootContext(contexts.meta);
|
|
833
|
+
const activeView = useActiveViewContext(contexts.view);
|
|
834
|
+
const composedRef = useComposedRef(meta.refs.title, ref);
|
|
835
|
+
const title = useMemo(() => activeView?.definition.strategy.getTitle(activeView.range, activeView.environment, activeView.options) ?? "", [activeView]);
|
|
836
|
+
return createElement("span", {
|
|
837
|
+
...props,
|
|
838
|
+
"data-calendar-part": "title",
|
|
839
|
+
id: meta.ids.title,
|
|
840
|
+
ref: composedRef
|
|
841
|
+
}, children ?? title);
|
|
842
|
+
}
|
|
843
|
+
function createTrigger(part, command) {
|
|
844
|
+
return function Trigger({ children, disabled, ref, type = "button", ...props }) {
|
|
845
|
+
const actions = useRootContext(contexts.actions);
|
|
846
|
+
const meta = useRootContext(contexts.meta);
|
|
847
|
+
const requiresView = command !== "navigateToday";
|
|
848
|
+
return createElement("button", {
|
|
849
|
+
...props,
|
|
850
|
+
"aria-controls": props["aria-controls"] ?? meta.ids.viewport,
|
|
851
|
+
"data-calendar-part": part,
|
|
852
|
+
disabled: disabled ?? (requiresView && meta.activeView === void 0),
|
|
853
|
+
onClick: (event) => {
|
|
854
|
+
props.onClick?.(event);
|
|
855
|
+
if (!event.defaultPrevented) actions[command]();
|
|
856
|
+
},
|
|
857
|
+
ref,
|
|
858
|
+
type
|
|
859
|
+
}, children);
|
|
860
|
+
};
|
|
861
|
+
}
|
|
862
|
+
const PreviousTrigger = createTrigger("previous-trigger", "navigatePrevious");
|
|
863
|
+
const NextTrigger = createTrigger("next-trigger", "navigateNext");
|
|
864
|
+
const TodayTrigger = createTrigger("today-trigger", "navigateToday");
|
|
865
|
+
function ViewSwitcher({ getViewLabel, onChange, ref, ...props }) {
|
|
866
|
+
const actions = useRootContext(contexts.actions);
|
|
867
|
+
const meta = useRootContext(contexts.meta);
|
|
868
|
+
const view = useStateSelector(useRootContext(contexts.source), selectView);
|
|
869
|
+
return createElement("select", {
|
|
870
|
+
...props,
|
|
871
|
+
"data-calendar-part": "view-switcher",
|
|
872
|
+
onChange: (event) => {
|
|
873
|
+
onChange?.(event);
|
|
874
|
+
const next = event.currentTarget.value;
|
|
875
|
+
if (!event.defaultPrevented && meta.views.some((candidate) => candidate.name === next)) actions.setView(next);
|
|
876
|
+
},
|
|
877
|
+
ref,
|
|
878
|
+
value: view
|
|
879
|
+
}, meta.views.map(({ name }) => createElement("option", {
|
|
880
|
+
key: name,
|
|
881
|
+
value: name
|
|
882
|
+
}, getViewLabel(name))));
|
|
883
|
+
}
|
|
884
|
+
function ActiveView({ fallback = null }) {
|
|
885
|
+
const actions = useRootContext(contexts.actions);
|
|
886
|
+
const activeView = useActiveViewContext(contexts.view);
|
|
887
|
+
const { isReadOnly, source } = useInteractionRuntime();
|
|
888
|
+
const latest = useRef(activeView);
|
|
889
|
+
useInsertionEffect(() => {
|
|
890
|
+
latest.current = activeView;
|
|
891
|
+
});
|
|
892
|
+
const [roving] = useState(() => createRovingFocusStore(viewEntry(activeView)));
|
|
893
|
+
const runtime = useMemo(() => Object.freeze({
|
|
894
|
+
getView: () => latest.current,
|
|
895
|
+
roving
|
|
896
|
+
}), [roving]);
|
|
897
|
+
if (activeView === null) return fallback;
|
|
898
|
+
const { definition, environment, events, loadRange, options, projection, range } = activeView;
|
|
899
|
+
return createElement(CalendarViewRuntimeContext, { value: runtime }, createElement(definition.Renderer, {
|
|
900
|
+
actions,
|
|
901
|
+
environment,
|
|
902
|
+
events,
|
|
903
|
+
isReadOnly,
|
|
904
|
+
loadRange,
|
|
905
|
+
options,
|
|
906
|
+
projection,
|
|
907
|
+
range
|
|
908
|
+
}), createElement(RovingFocusSync, {
|
|
909
|
+
roving,
|
|
910
|
+
source,
|
|
911
|
+
view: activeView
|
|
912
|
+
}));
|
|
913
|
+
}
|
|
914
|
+
function EventPart({ children, eventId, fallback = null }) {
|
|
915
|
+
const normalized = useRootContext(contexts.meta).eventSnapshot.get(eventId);
|
|
916
|
+
return normalized === void 0 ? fallback : children({
|
|
917
|
+
event: normalized.event,
|
|
918
|
+
normalized
|
|
919
|
+
});
|
|
920
|
+
}
|
|
921
|
+
return Object.freeze({
|
|
922
|
+
ActiveView,
|
|
923
|
+
EventPart,
|
|
924
|
+
Frame,
|
|
925
|
+
NextTrigger,
|
|
926
|
+
PreviousTrigger,
|
|
927
|
+
Title,
|
|
928
|
+
TodayTrigger,
|
|
929
|
+
Toolbar,
|
|
930
|
+
ViewSwitcher,
|
|
931
|
+
Viewport
|
|
932
|
+
});
|
|
933
|
+
}
|
|
934
|
+
//#endregion
|
|
935
|
+
//#region src/status.ts
|
|
936
|
+
/** The nearest root's events, pending changes included, for hooks that work in any factory. */
|
|
937
|
+
const CalendarEventsContext = createContext(null);
|
|
938
|
+
const systemClock$2 = createSystemClock();
|
|
939
|
+
/** How often the clock is sampled between changes, in case it jumps. */
|
|
940
|
+
const SAMPLE_MS = 6e4;
|
|
941
|
+
const serverSnapshot$2 = () => null;
|
|
942
|
+
const subscribeToNothing$2 = () => () => void 0;
|
|
943
|
+
function sameInstant(left, right) {
|
|
944
|
+
return left === right || left !== null && right !== null && left.equals(right);
|
|
945
|
+
}
|
|
946
|
+
function sameStatus(left, right) {
|
|
947
|
+
const [a, b] = [left.availability, right.availability];
|
|
948
|
+
const [c, d] = [left.busy, right.busy];
|
|
949
|
+
return sameInstant(left.changesAt, right.changesAt) && (a.available ? b.available && sameInstant(a.closesAt, b.closesAt) : !b.available && a.reason === b.reason && a.label === b.label && sameInstant(a.opensAt, b.opensAt)) && (c.busy ? d.busy && sameInstant(c.freeAt, d.freeAt) && c.events.length === d.events.length && c.events.every((event, index) => event === d.events[index]) : !d.busy && sameInstant(c.nextEventAt, d.nextEventAt));
|
|
950
|
+
}
|
|
951
|
+
/**
|
|
952
|
+
* The status on the clock: it samples when the status next changes, and every minute in case the
|
|
953
|
+
* clock jumps, and tells subscribers only when the status differs.
|
|
954
|
+
*/
|
|
955
|
+
function createStatusClock(source, compute) {
|
|
956
|
+
const clock = source?.clock ?? systemClock$2;
|
|
957
|
+
let current;
|
|
958
|
+
return {
|
|
959
|
+
getSnapshot: () => current ??= compute(clock.instant()),
|
|
960
|
+
subscribe: (onChange) => {
|
|
961
|
+
let timer;
|
|
962
|
+
const sample = () => {
|
|
963
|
+
const now = clock.instant();
|
|
964
|
+
const next = compute(now);
|
|
965
|
+
if (current === void 0 || !sameStatus(current, next)) {
|
|
966
|
+
current = next;
|
|
967
|
+
onChange();
|
|
968
|
+
}
|
|
969
|
+
const until = next.changesAt === null ? SAMPLE_MS : now.until(next.changesAt).total("milliseconds");
|
|
970
|
+
timer = setTimeout(sample, Math.max(0, Math.min(SAMPLE_MS, until)));
|
|
971
|
+
};
|
|
972
|
+
sample();
|
|
973
|
+
return () => clearTimeout(timer);
|
|
974
|
+
}
|
|
975
|
+
};
|
|
976
|
+
}
|
|
977
|
+
/**
|
|
978
|
+
* Whether a resource is within its working hours and whether its events occupy it, `at` an
|
|
979
|
+
* instant or now on the calendar's clock; see `resourceStatusAt`. Without `resourceId` it is the
|
|
980
|
+
* calendar's hours and every event. All-day and floating events count on the display time zone,
|
|
981
|
+
* as the views show them. On the clock it re-renders only when the status changes, and is `null`
|
|
982
|
+
* while server rendering unless the calendar fixes `now`. A `null` resource turns it off, such as
|
|
983
|
+
* for the Unassigned column, with nothing computed or scheduled.
|
|
984
|
+
*/
|
|
985
|
+
/** The root's events, pending changes included, for hooks that work in any factory. */
|
|
986
|
+
function useCalendarEvents() {
|
|
987
|
+
const events = useContext(CalendarEventsContext);
|
|
988
|
+
if (events === null) throw new Error("calendar-hook-outside-root");
|
|
989
|
+
return events;
|
|
990
|
+
}
|
|
991
|
+
function useResourceStatus(resourceId, at) {
|
|
992
|
+
const availability = useCalendarAvailability();
|
|
993
|
+
const events = useCalendarEvents();
|
|
994
|
+
const source = useContext(CalendarNowSourceContext);
|
|
995
|
+
const fixed = at ?? source?.now;
|
|
996
|
+
const { timeZone } = availability;
|
|
997
|
+
const compute = useCallback((instant) => resourceStatusAt(availability, events, instant, {
|
|
998
|
+
resourceId: resourceId ?? void 0,
|
|
999
|
+
timeZone
|
|
1000
|
+
}), [
|
|
1001
|
+
availability,
|
|
1002
|
+
events,
|
|
1003
|
+
resourceId,
|
|
1004
|
+
timeZone
|
|
1005
|
+
]);
|
|
1006
|
+
const off = resourceId === null;
|
|
1007
|
+
const onClock = fixed === void 0 && !off;
|
|
1008
|
+
const store = useMemo(() => onClock ? createStatusClock(source, compute) : null, [
|
|
1009
|
+
compute,
|
|
1010
|
+
onClock,
|
|
1011
|
+
source
|
|
1012
|
+
]);
|
|
1013
|
+
const sampled = useSyncExternalStore(store?.subscribe ?? subscribeToNothing$2, store?.getSnapshot ?? serverSnapshot$2, serverSnapshot$2);
|
|
1014
|
+
const pinnedAt = off ? void 0 : fixed?.epochNanoseconds;
|
|
1015
|
+
return useMemo(() => pinnedAt === void 0 ? null : compute(Temporal.Instant.fromEpochNanoseconds(pinnedAt)), [compute, pinnedAt]) ?? sampled;
|
|
1016
|
+
}
|
|
1017
|
+
//#endregion
|
|
1018
|
+
//#region src/draft.ts
|
|
1019
|
+
function createDraftStore() {
|
|
1020
|
+
let draft = null;
|
|
1021
|
+
const listeners = /* @__PURE__ */ new Set();
|
|
1022
|
+
return Object.freeze({
|
|
1023
|
+
getSnapshot: () => draft,
|
|
1024
|
+
set(next) {
|
|
1025
|
+
if (next === draft) return;
|
|
1026
|
+
draft = next;
|
|
1027
|
+
for (const listener of listeners) listener();
|
|
1028
|
+
},
|
|
1029
|
+
subscribe(listener) {
|
|
1030
|
+
listeners.add(listener);
|
|
1031
|
+
return () => listeners.delete(listener);
|
|
1032
|
+
}
|
|
1033
|
+
});
|
|
1034
|
+
}
|
|
1035
|
+
function sameIds(left, right) {
|
|
1036
|
+
return left === right || left !== void 0 && right !== void 0 && sameElements(left, right);
|
|
1037
|
+
}
|
|
1038
|
+
function sameInterval(left, right) {
|
|
1039
|
+
return left === right || left !== null && right !== null && ("kind" in left ? left.kind : "timed") === ("kind" in right ? right.kind : "timed") && left.start.toString() === right.start.toString() && left.end.toString() === right.end.toString();
|
|
1040
|
+
}
|
|
1041
|
+
const nothingBusy = /* @__PURE__ */ new Map();
|
|
1042
|
+
/**
|
|
1043
|
+
* The resources busy during `range`, such as a meeting being placed, with their events; free
|
|
1044
|
+
* ones are absent. It queries the root's events, pending changes included, once per change of
|
|
1045
|
+
* events or range, however many components ask. `exclude` leaves out an event, such as the one
|
|
1046
|
+
* being moved; `null` asks nothing.
|
|
1047
|
+
*/
|
|
1048
|
+
function useBusyResources(range, { exclude, resourceIds } = {}) {
|
|
1049
|
+
const events = useCalendarEvents();
|
|
1050
|
+
const { timeZone } = useCalendarAvailability();
|
|
1051
|
+
const stableRange = useStableValue(range, sameInterval);
|
|
1052
|
+
const ids = useStableValue(resourceIds, sameIds);
|
|
1053
|
+
return useMemo(() => stableRange === null ? nothingBusy : busyResources(events, stableRange, {
|
|
1054
|
+
...exclude == null ? {} : { exclude },
|
|
1055
|
+
...ids === void 0 ? {} : { resourceIds: ids },
|
|
1056
|
+
timeZone
|
|
1057
|
+
}), [
|
|
1058
|
+
events,
|
|
1059
|
+
exclude,
|
|
1060
|
+
ids,
|
|
1061
|
+
stableRange,
|
|
1062
|
+
timeZone
|
|
1063
|
+
]);
|
|
1064
|
+
}
|
|
1065
|
+
/** Each draft's busy resources, worked out once for every header that asks. */
|
|
1066
|
+
const draftBusy = /* @__PURE__ */ new WeakMap();
|
|
1067
|
+
function busyFor(draft, events, timeZone) {
|
|
1068
|
+
const cached = draftBusy.get(draft);
|
|
1069
|
+
if (cached?.events === events) return cached.busy;
|
|
1070
|
+
const busy = busyResources(events, draft.proposed, {
|
|
1071
|
+
...draft.eventId === null ? {} : { exclude: draft.eventId },
|
|
1072
|
+
timeZone
|
|
1073
|
+
});
|
|
1074
|
+
draftBusy.set(draft, {
|
|
1075
|
+
busy,
|
|
1076
|
+
events
|
|
1077
|
+
});
|
|
1078
|
+
return busy;
|
|
1079
|
+
}
|
|
1080
|
+
/** Each keyboard session as a draft, the same object for as long as the session is. */
|
|
1081
|
+
const sessionDrafts = /* @__PURE__ */ new WeakMap();
|
|
1082
|
+
function draftOf(session) {
|
|
1083
|
+
let draft = sessionDrafts.get(session);
|
|
1084
|
+
if (draft === void 0) {
|
|
1085
|
+
draft = Object.freeze({
|
|
1086
|
+
eventId: session.eventId,
|
|
1087
|
+
proposed: session.proposed
|
|
1088
|
+
});
|
|
1089
|
+
sessionDrafts.set(session, draft);
|
|
1090
|
+
}
|
|
1091
|
+
return draft;
|
|
1092
|
+
}
|
|
1093
|
+
/** Subscribes to the keyboard's and the pointer's drafts. */
|
|
1094
|
+
function useDraftSource() {
|
|
1095
|
+
const { keyboard, pointerDraft } = useInteractionRuntime();
|
|
1096
|
+
return useMemo(() => ({
|
|
1097
|
+
getSnapshot: () => {
|
|
1098
|
+
const session = keyboard.grabs.getSnapshot()?.session;
|
|
1099
|
+
return session === void 0 ? pointerDraft.getSnapshot() : draftOf(session);
|
|
1100
|
+
},
|
|
1101
|
+
subscribe: (listener) => {
|
|
1102
|
+
const stops = [keyboard.grabs.subscribe(listener), pointerDraft.subscribe(listener)];
|
|
1103
|
+
return () => {
|
|
1104
|
+
for (const stop of stops) stop();
|
|
1105
|
+
};
|
|
1106
|
+
}
|
|
1107
|
+
}), [keyboard, pointerDraft]);
|
|
1108
|
+
}
|
|
1109
|
+
/** Reports the pointer's draft to the root, for `onPreview` of `useCalendarPointer`. */
|
|
1110
|
+
function useCalendarDraftReporter() {
|
|
1111
|
+
return useInteractionRuntime().pointerDraft.set;
|
|
1112
|
+
}
|
|
1113
|
+
/**
|
|
1114
|
+
* The change being drafted, by pointer or keyboard: the event it changes (`null` when creating)
|
|
1115
|
+
* and where it would land; `null` without one. It changes once a slot step, so pass its
|
|
1116
|
+
* `proposed` to `useBusyResources` for any "who's busy" UI of your own.
|
|
1117
|
+
*/
|
|
1118
|
+
function useCalendarDraft() {
|
|
1119
|
+
const source = useDraftSource();
|
|
1120
|
+
return useSyncExternalStore(source.subscribe, source.getSnapshot, () => null);
|
|
1121
|
+
}
|
|
1122
|
+
const noEvents = Object.freeze([]);
|
|
1123
|
+
function sameBusy(left, right) {
|
|
1124
|
+
return left === right || left !== null && right !== null && left.outsideHours === right.outsideHours && left.events.length === right.events.length && left.events.every((event, index) => event === right.events[index]);
|
|
1125
|
+
}
|
|
1126
|
+
/**
|
|
1127
|
+
* A resource during the draft's time while one is being made, by pointer or keyboard: the busy
|
|
1128
|
+
* events that overlap it (the draft's own event aside; see `isBusy` on the event adapter), and
|
|
1129
|
+
* whether the time falls outside its hours. `null` without a draft, or for a `null` resource.
|
|
1130
|
+
* The draft's busy resources are worked out once a step for every component that asks, and a
|
|
1131
|
+
* component re-renders only when its own resource's answer changes.
|
|
1132
|
+
*/
|
|
1133
|
+
function useDraftBusy(resourceId) {
|
|
1134
|
+
const source = useDraftSource();
|
|
1135
|
+
const events = useCalendarEvents();
|
|
1136
|
+
const availability = useCalendarAvailability();
|
|
1137
|
+
const last = useRef(null);
|
|
1138
|
+
const read = () => {
|
|
1139
|
+
const draft = source.getSnapshot();
|
|
1140
|
+
if (draft === null || resourceId === null) return last.current = null;
|
|
1141
|
+
const { timeZone } = availability;
|
|
1142
|
+
const next = {
|
|
1143
|
+
events: busyFor(draft, events, timeZone).get(resourceId) ?? noEvents,
|
|
1144
|
+
outsideHours: !fitsAvailability(draft.proposed, availability.forResource(resourceId), timeZone)
|
|
1145
|
+
};
|
|
1146
|
+
if (!sameBusy(last.current, next)) last.current = next;
|
|
1147
|
+
return last.current;
|
|
1148
|
+
};
|
|
1149
|
+
return useSyncExternalStore(source.subscribe, read, () => null);
|
|
1150
|
+
}
|
|
1151
|
+
//#endregion
|
|
1152
|
+
//#region src/event-input.ts
|
|
1153
|
+
const readNothing = () => null;
|
|
1154
|
+
const subscribeToNothing$1 = () => () => void 0;
|
|
1155
|
+
function isEventSource(input) {
|
|
1156
|
+
return !Array.isArray(input);
|
|
1157
|
+
}
|
|
1158
|
+
/**
|
|
1159
|
+
* The events `Root` shows: an array as given, or a source's current array. A source is read
|
|
1160
|
+
* through `useSyncExternalStore`, so its updates render the calendar and not the component that
|
|
1161
|
+
* renders `Root`; the server and hydration read `getServerSnapshot`.
|
|
1162
|
+
*/
|
|
1163
|
+
function useEventInput(input) {
|
|
1164
|
+
const source = isEventSource(input) ? input : void 0;
|
|
1165
|
+
const { read, readServer, subscribe } = useMemo(() => source === void 0 ? {
|
|
1166
|
+
read: readNothing,
|
|
1167
|
+
readServer: readNothing,
|
|
1168
|
+
subscribe: subscribeToNothing$1
|
|
1169
|
+
} : {
|
|
1170
|
+
read: () => source.getSnapshot(),
|
|
1171
|
+
readServer: () => source.getServerSnapshot(),
|
|
1172
|
+
subscribe: (listener) => source.subscribe(listener)
|
|
1173
|
+
}, [source]);
|
|
1174
|
+
const sourced = useSyncExternalStore(subscribe, read, readServer);
|
|
1175
|
+
return source === void 0 ? input : sourced;
|
|
1176
|
+
}
|
|
1177
|
+
//#endregion
|
|
1178
|
+
//#region src/keyboard-store.ts
|
|
1179
|
+
const noPreview = /* @__PURE__ */ new Map();
|
|
1180
|
+
function createKeyboardSessionStore() {
|
|
1181
|
+
let grab = null;
|
|
1182
|
+
let preview = noPreview;
|
|
1183
|
+
const listeners = /* @__PURE__ */ new Set();
|
|
1184
|
+
const subscribe = (listener) => {
|
|
1185
|
+
listeners.add(listener);
|
|
1186
|
+
return () => {
|
|
1187
|
+
listeners.delete(listener);
|
|
1188
|
+
};
|
|
1189
|
+
};
|
|
1190
|
+
return Object.freeze({
|
|
1191
|
+
get: () => grab,
|
|
1192
|
+
getPreview: () => preview,
|
|
1193
|
+
grabs: Object.freeze({
|
|
1194
|
+
getSnapshot: () => grab,
|
|
1195
|
+
subscribe
|
|
1196
|
+
}),
|
|
1197
|
+
set(next) {
|
|
1198
|
+
if (next === grab) return;
|
|
1199
|
+
grab = next;
|
|
1200
|
+
const session = next?.session;
|
|
1201
|
+
preview = session?.eventId == null ? noPreview : /* @__PURE__ */ new Map([[session.eventId, session.proposed]]);
|
|
1202
|
+
for (const listener of listeners) listener();
|
|
1203
|
+
},
|
|
1204
|
+
subscribe
|
|
1205
|
+
});
|
|
1206
|
+
}
|
|
1207
|
+
//#endregion
|
|
1208
|
+
//#region src/report-error.ts
|
|
1209
|
+
/** Reports an application callback's error without failing what it was told about. */
|
|
1210
|
+
function reportCallbackError(error) {
|
|
1211
|
+
if (typeof reportError === "function") reportError(error);
|
|
1212
|
+
else console.error(error);
|
|
1213
|
+
}
|
|
1214
|
+
//#endregion
|
|
1215
|
+
//#region src/resources.ts
|
|
1216
|
+
/** The nearest root's resource tree, shared by every factory so resource hooks work in any view. */
|
|
1217
|
+
const CalendarResourcesContext = createContext(null);
|
|
1218
|
+
const selectExpanded = (state) => state.expandedResourceIds;
|
|
1219
|
+
/**
|
|
1220
|
+
* The root's resources as a view shows them: depth first, with collapsed resources' descendants
|
|
1221
|
+
* left out (see `visibleResources`). Re-renders when the resources or their expansion change.
|
|
1222
|
+
*/
|
|
1223
|
+
function useVisibleResources(options = {}) {
|
|
1224
|
+
const tree = useContext(CalendarResourcesContext);
|
|
1225
|
+
if (tree === null) throw new Error("calendar-hook-outside-root");
|
|
1226
|
+
const expanded = useStateSelector(useInteractionRuntime().source, selectExpanded, { isEqual: sameElements });
|
|
1227
|
+
const { unassigned } = options;
|
|
1228
|
+
return useMemo(() => visibleResources(tree, expanded, { unassigned }), [
|
|
1229
|
+
expanded,
|
|
1230
|
+
tree,
|
|
1231
|
+
unassigned
|
|
1232
|
+
]);
|
|
1233
|
+
}
|
|
1234
|
+
/**
|
|
1235
|
+
* One resource's expansion and the commands that change it, through `expandedResourceIds`. A
|
|
1236
|
+
* component re-renders only when this resource expands or collapses, so a resource header can
|
|
1237
|
+
* own its toggle.
|
|
1238
|
+
*/
|
|
1239
|
+
function useResourceExpansion(resourceId) {
|
|
1240
|
+
const { actions, read, source } = useInteractionRuntime();
|
|
1241
|
+
const expanded = useStateSelector(source, (state) => state.expandedResourceIds.includes(resourceId));
|
|
1242
|
+
return useMemo(() => {
|
|
1243
|
+
const set = (next) => {
|
|
1244
|
+
const current = read().expandedResourceIds;
|
|
1245
|
+
if (current.includes(resourceId) === next) return;
|
|
1246
|
+
actions.setExpandedResourceIds(next ? [...current, resourceId] : current.filter((id) => id !== resourceId));
|
|
1247
|
+
};
|
|
1248
|
+
return Object.freeze({
|
|
1249
|
+
collapse: () => set(false),
|
|
1250
|
+
expand: () => set(true),
|
|
1251
|
+
expanded,
|
|
1252
|
+
toggle: () => set(!read().expandedResourceIds.includes(resourceId))
|
|
1253
|
+
});
|
|
1254
|
+
}, [
|
|
1255
|
+
actions,
|
|
1256
|
+
expanded,
|
|
1257
|
+
read,
|
|
1258
|
+
resourceId
|
|
1259
|
+
]);
|
|
1260
|
+
}
|
|
1261
|
+
//#endregion
|
|
1262
|
+
//#region src/use-now.ts
|
|
1263
|
+
const systemClock$1 = createSystemClock();
|
|
1264
|
+
const serverSnapshot$1 = () => null;
|
|
1265
|
+
const subscribeToNothing = () => () => void 0;
|
|
1266
|
+
function createClockTicker(clock, intervalMs) {
|
|
1267
|
+
let current;
|
|
1268
|
+
return {
|
|
1269
|
+
getSnapshot: () => current ??= clock.instant(),
|
|
1270
|
+
subscribe: (onChange) => {
|
|
1271
|
+
const sample = () => {
|
|
1272
|
+
const next = clock.instant();
|
|
1273
|
+
if (current?.equals(next) === true) return;
|
|
1274
|
+
current = next;
|
|
1275
|
+
onChange();
|
|
1276
|
+
};
|
|
1277
|
+
sample();
|
|
1278
|
+
const timer = setInterval(sample, intervalMs);
|
|
1279
|
+
return () => clearInterval(timer);
|
|
1280
|
+
}
|
|
1281
|
+
};
|
|
1282
|
+
}
|
|
1283
|
+
/** Samples `source`; `null` while server rendering and hydrating unless `now` is fixed. */
|
|
1284
|
+
function useNowFrom(source, intervalMs) {
|
|
1285
|
+
const clock = source?.clock ?? systemClock$1;
|
|
1286
|
+
const ticker = useMemo(() => createClockTicker(clock, intervalMs), [clock, intervalMs]);
|
|
1287
|
+
const fixed = source?.now;
|
|
1288
|
+
const sampled = useSyncExternalStore(fixed === void 0 ? ticker.subscribe : subscribeToNothing, ticker.getSnapshot, serverSnapshot$1);
|
|
1289
|
+
return fixed ?? sampled;
|
|
1290
|
+
}
|
|
1291
|
+
/**
|
|
1292
|
+
* The current instant from the nearest calendar's `now` or `clock`, falling back to the system
|
|
1293
|
+
* clock. It is `null` during server rendering and hydration unless the calendar fixes `now`.
|
|
1294
|
+
*/
|
|
1295
|
+
function useNow({ intervalMs = 6e4 } = {}) {
|
|
1296
|
+
return useNowFrom(useContext(CalendarNowSourceContext), intervalMs);
|
|
1297
|
+
}
|
|
1298
|
+
//#endregion
|
|
1299
|
+
//#region src/views.ts
|
|
1300
|
+
function defineCalendarView(view) {
|
|
1301
|
+
return Object.freeze({
|
|
1302
|
+
defaultOptions: view.defaultOptions,
|
|
1303
|
+
name: view.name,
|
|
1304
|
+
Renderer: view.Renderer,
|
|
1305
|
+
strategy: view.strategy
|
|
1306
|
+
});
|
|
1307
|
+
}
|
|
1308
|
+
/** Applies a root's partial overrides to a view's `defaultOptions`. */
|
|
1309
|
+
function resolveViewOptions(view, overrides) {
|
|
1310
|
+
return overrides === void 0 ? view.defaultOptions : {
|
|
1311
|
+
...view.defaultOptions,
|
|
1312
|
+
...overrides
|
|
1313
|
+
};
|
|
1314
|
+
}
|
|
1315
|
+
//#endregion
|
|
1316
|
+
//#region src/root.ts
|
|
1317
|
+
const noResources = Object.freeze([]);
|
|
1318
|
+
const noAnnotations = Object.freeze([]);
|
|
1319
|
+
const noSecondaryTimeZones = Object.freeze([]);
|
|
1320
|
+
const todaySampleIntervalMs = 6e4;
|
|
1321
|
+
/** Today, when `Root` has neither `now` nor a clock. */
|
|
1322
|
+
const systemClock = createSystemClock();
|
|
1323
|
+
/** A root without `onEventChange` is read-only, so its checks reject everything. */
|
|
1324
|
+
const readOnlyRoot = () => ({
|
|
1325
|
+
reason: "read-only",
|
|
1326
|
+
type: "reject"
|
|
1327
|
+
});
|
|
1328
|
+
/** A read-only root's handler: its check rejects every change first, so this never runs. */
|
|
1329
|
+
const noHandler = () => {
|
|
1330
|
+
throw new TypeError("calendar-root-is-read-only");
|
|
1331
|
+
};
|
|
1332
|
+
/** The detail of a proposal made without one, or with something that names no input. */
|
|
1333
|
+
const apiInput = Object.freeze({ input: "api" });
|
|
1334
|
+
function sameLocale(left, right) {
|
|
1335
|
+
return String(left) === String(right);
|
|
1336
|
+
}
|
|
1337
|
+
function sameIssue(left, right) {
|
|
1338
|
+
return left.code === right.code && left.index === right.index && left.eventId === right.eventId && left.accessor === right.accessor && left.message === right.message && left.resourceIndex === right.resourceIndex;
|
|
1339
|
+
}
|
|
1340
|
+
function sameDiagnostics(left, right) {
|
|
1341
|
+
return left.length === right.length && left.every((diagnostic, index) => {
|
|
1342
|
+
const other = right[index];
|
|
1343
|
+
if (other === void 0 || other.code !== diagnostic.code) return false;
|
|
1344
|
+
switch (diagnostic.code) {
|
|
1345
|
+
case "invalid-event": return other.code === "invalid-event" && sameIssue(diagnostic.issue, other.issue);
|
|
1346
|
+
case "invalid-annotation": return other.code === "invalid-annotation" && other.issue.annotation === diagnostic.issue.annotation && other.issue.code === diagnostic.issue.code && other.issue.index === diagnostic.issue.index;
|
|
1347
|
+
case "invalid-availability": return other.code === "invalid-availability" && other.issue.code === diagnostic.issue.code && other.issue.resourceId === diagnostic.issue.resourceId && other.issue.value === diagnostic.issue.value;
|
|
1348
|
+
case "invalid-secondary-time-zone": return other.code === "invalid-secondary-time-zone" && other.issue.index === diagnostic.issue.index && other.issue.value === diagnostic.issue.value;
|
|
1349
|
+
case "unregistered-active-view": return other.code === "unregistered-active-view" && other.viewName === diagnostic.viewName;
|
|
1350
|
+
}
|
|
1351
|
+
});
|
|
1352
|
+
}
|
|
1353
|
+
function collectDiagnostics(view, viewIsRegistered, issues, annotationIssues, availabilityIssues, secondaryTimeZoneIssues) {
|
|
1354
|
+
const diagnostics = [];
|
|
1355
|
+
if (!viewIsRegistered) diagnostics.push(Object.freeze({
|
|
1356
|
+
code: "unregistered-active-view",
|
|
1357
|
+
severity: "error",
|
|
1358
|
+
viewName: view
|
|
1359
|
+
}));
|
|
1360
|
+
for (const issue of issues) diagnostics.push(Object.freeze({
|
|
1361
|
+
code: "invalid-event",
|
|
1362
|
+
issue,
|
|
1363
|
+
severity: "error"
|
|
1364
|
+
}));
|
|
1365
|
+
for (const issue of annotationIssues) diagnostics.push(Object.freeze({
|
|
1366
|
+
code: "invalid-annotation",
|
|
1367
|
+
issue,
|
|
1368
|
+
severity: "error"
|
|
1369
|
+
}));
|
|
1370
|
+
for (const issue of availabilityIssues) diagnostics.push(Object.freeze({
|
|
1371
|
+
code: "invalid-availability",
|
|
1372
|
+
issue,
|
|
1373
|
+
severity: "error"
|
|
1374
|
+
}));
|
|
1375
|
+
for (const issue of secondaryTimeZoneIssues) diagnostics.push(Object.freeze({
|
|
1376
|
+
code: "invalid-secondary-time-zone",
|
|
1377
|
+
issue,
|
|
1378
|
+
severity: "error"
|
|
1379
|
+
}));
|
|
1380
|
+
return Object.freeze(diagnostics);
|
|
1381
|
+
}
|
|
1382
|
+
function createSemanticActions({ actions, read }, viewsByName, committed, transactions, readOnly) {
|
|
1383
|
+
/** The policies every change runs through; a root without `onEventChange` rejects them all. */
|
|
1384
|
+
function policiesOf({ onEventChange, policies = [] }) {
|
|
1385
|
+
return onEventChange === void 0 ? [readOnlyRoot] : [readOnly, ...policies];
|
|
1386
|
+
}
|
|
1387
|
+
function navigate(delta) {
|
|
1388
|
+
const latest = read();
|
|
1389
|
+
const view = viewsByName.get(latest.view);
|
|
1390
|
+
if (view === void 0) return;
|
|
1391
|
+
const options = resolveViewOptions(view, committed.current.viewOptions?.[latest.view]);
|
|
1392
|
+
actions.setAnchorDate(view.strategy.navigate(latest.anchorDate, delta, options));
|
|
1393
|
+
}
|
|
1394
|
+
return Object.freeze({
|
|
1395
|
+
...actions,
|
|
1396
|
+
checkEventChange(proposal) {
|
|
1397
|
+
const { availability, eventSnapshot } = committed.current;
|
|
1398
|
+
return transactions.check(proposal, {
|
|
1399
|
+
availability,
|
|
1400
|
+
policies: policiesOf(committed.current),
|
|
1401
|
+
snapshot: eventSnapshot,
|
|
1402
|
+
timeZone: read().timeZone
|
|
1403
|
+
});
|
|
1404
|
+
},
|
|
1405
|
+
navigateNext: () => navigate(1),
|
|
1406
|
+
navigatePrevious: () => navigate(-1),
|
|
1407
|
+
navigateToday() {
|
|
1408
|
+
const { environment } = committed.current;
|
|
1409
|
+
const instant = environment.now ?? (environment.clock ?? systemClock).instant();
|
|
1410
|
+
actions.setAnchorDate(instant.toZonedDateTimeISO(read().timeZone).toPlainDate());
|
|
1411
|
+
},
|
|
1412
|
+
proposeEventChange(proposal, detail) {
|
|
1413
|
+
const { availability, eventSnapshot, onEventChange } = committed.current;
|
|
1414
|
+
const input = detail?.input;
|
|
1415
|
+
const reported = input === "pointer" || input === "keyboard" || input === "api" ? detail : apiInput;
|
|
1416
|
+
return transactions.propose(proposal, {
|
|
1417
|
+
availability,
|
|
1418
|
+
onEventChange: onEventChange ?? noHandler,
|
|
1419
|
+
policies: policiesOf(committed.current),
|
|
1420
|
+
snapshot: eventSnapshot,
|
|
1421
|
+
timeZone: read().timeZone
|
|
1422
|
+
}).then((result) => {
|
|
1423
|
+
try {
|
|
1424
|
+
committed.current.onEventChangeResult?.(result, reported);
|
|
1425
|
+
} catch (error) {
|
|
1426
|
+
reportCallbackError(error);
|
|
1427
|
+
}
|
|
1428
|
+
return result;
|
|
1429
|
+
});
|
|
1430
|
+
}
|
|
1431
|
+
});
|
|
1432
|
+
}
|
|
1433
|
+
function createCalendarRoot(config, contexts) {
|
|
1434
|
+
const viewsByName = new Map(config.views.map((view) => [view.name, view]));
|
|
1435
|
+
const readOnly = readOnlyPolicy();
|
|
1436
|
+
return function Root({ anchorDate, annotationSources = noAnnotations, annotations = noAnnotations, availability, children, clock, defaultAnchorDate, defaultExpandedResourceIds, defaultFocus, defaultSelection, defaultTimeZone, defaultView, direction = "ltr", disambiguation = "compatible", events, expandedResourceIds, focus, id, locale, now, onAnchorDateChange, onDiagnosticsChange, onEventChange, onEventChangeResult, onExpandedResourceIdsChange, onFocusChange, onSelectionChange, onTimeZoneChange, onViewChange, onVisibleRangeChange, policies, resources = noResources, secondaryTimeZones = noSecondaryTimeZones, selection, store: injectedStore, timeZone, view, viewOptions, weekRules }) {
|
|
1437
|
+
const reactId = useId();
|
|
1438
|
+
const instanceId = id ?? reactId;
|
|
1439
|
+
const { binding, source, state } = useCalendarStateBinding(injectedStore, () => {
|
|
1440
|
+
const initialAnchorDate = defaultAnchorDate ?? anchorDate;
|
|
1441
|
+
const initialTimeZone = defaultTimeZone ?? timeZone;
|
|
1442
|
+
const initialView = defaultView ?? view ?? config.views[0]?.name;
|
|
1443
|
+
if (initialAnchorDate === void 0) throw new TypeError("calendar-root-requires-anchor-date");
|
|
1444
|
+
if (initialTimeZone === void 0) throw new TypeError("calendar-root-requires-time-zone");
|
|
1445
|
+
if (initialView === void 0) throw new TypeError("calendar-root-requires-view");
|
|
1446
|
+
return {
|
|
1447
|
+
defaultAnchorDate: initialAnchorDate,
|
|
1448
|
+
defaultExpandedResourceIds,
|
|
1449
|
+
defaultFocus,
|
|
1450
|
+
defaultSelection,
|
|
1451
|
+
defaultTimeZone: initialTimeZone,
|
|
1452
|
+
defaultView: initialView
|
|
1453
|
+
};
|
|
1454
|
+
}, {
|
|
1455
|
+
controlled: {
|
|
1456
|
+
anchorDate,
|
|
1457
|
+
expandedResourceIds,
|
|
1458
|
+
focus,
|
|
1459
|
+
selection,
|
|
1460
|
+
timeZone,
|
|
1461
|
+
view
|
|
1462
|
+
},
|
|
1463
|
+
handlers: {
|
|
1464
|
+
onAnchorDateChange,
|
|
1465
|
+
onExpandedResourceIdsChange,
|
|
1466
|
+
onFocusChange,
|
|
1467
|
+
onSelectionChange,
|
|
1468
|
+
onTimeZoneChange,
|
|
1469
|
+
onViewChange
|
|
1470
|
+
}
|
|
1471
|
+
});
|
|
1472
|
+
const stableLocale = useStableValue(locale, sameLocale);
|
|
1473
|
+
const stableWeekRules = useStableValue(weekRules, sameWeekRules);
|
|
1474
|
+
const stableNow = useStableValue(now, sameInstant$1);
|
|
1475
|
+
const stableSecondaryTimeZones = useStableValue(secondaryTimeZones, sameSecondaryTimeZones);
|
|
1476
|
+
const secondary = useMemo(() => resolveSecondaryTimeZones(stableSecondaryTimeZones), [stableSecondaryTimeZones]);
|
|
1477
|
+
const viewEnvironment = useMemo(() => Object.freeze({
|
|
1478
|
+
direction,
|
|
1479
|
+
disambiguation,
|
|
1480
|
+
locale: stableLocale,
|
|
1481
|
+
secondaryTimeZones: secondary.zones,
|
|
1482
|
+
timeZone: state.timeZone,
|
|
1483
|
+
weekRules: stableWeekRules
|
|
1484
|
+
}), [
|
|
1485
|
+
direction,
|
|
1486
|
+
disambiguation,
|
|
1487
|
+
secondary.zones,
|
|
1488
|
+
stableLocale,
|
|
1489
|
+
stableWeekRules,
|
|
1490
|
+
state.timeZone
|
|
1491
|
+
]);
|
|
1492
|
+
const environment = useMemo(() => {
|
|
1493
|
+
if (stableNow !== void 0) return Object.freeze({
|
|
1494
|
+
...viewEnvironment,
|
|
1495
|
+
now: stableNow
|
|
1496
|
+
});
|
|
1497
|
+
if (clock !== void 0) return Object.freeze({
|
|
1498
|
+
...viewEnvironment,
|
|
1499
|
+
clock
|
|
1500
|
+
});
|
|
1501
|
+
return viewEnvironment;
|
|
1502
|
+
}, [
|
|
1503
|
+
clock,
|
|
1504
|
+
stableNow,
|
|
1505
|
+
viewEnvironment
|
|
1506
|
+
]);
|
|
1507
|
+
const [snapshotCache] = useState(() => createEventSnapshotCache(config.eventAdapter, { invalidEventPolicy: config.invalidEventPolicy }));
|
|
1508
|
+
const stableEvents = useStableValue(useEventInput(events), sameElements);
|
|
1509
|
+
const eventSnapshot = useMemo(() => snapshotCache.getSnapshot(stableEvents), [snapshotCache, stableEvents]);
|
|
1510
|
+
const [transactions] = useState(() => createEventTransactions());
|
|
1511
|
+
const pending = useSyncExternalStore(transactions.subscribe, transactions.getPending, transactions.getPending);
|
|
1512
|
+
const [pendingChanges] = useState(() => {
|
|
1513
|
+
const none = transactions.getPendingChanges();
|
|
1514
|
+
return Object.freeze({
|
|
1515
|
+
getServerSnapshot: () => none,
|
|
1516
|
+
getSnapshot: transactions.getPendingChanges,
|
|
1517
|
+
subscribe: transactions.subscribe
|
|
1518
|
+
});
|
|
1519
|
+
});
|
|
1520
|
+
const [keyboard] = useState(createKeyboardSessionStore);
|
|
1521
|
+
const [pointerDraft] = useState(createDraftStore);
|
|
1522
|
+
const preview = useSyncExternalStore(keyboard.subscribe, keyboard.getPreview, keyboard.getPreview);
|
|
1523
|
+
const visibleSnapshot = useMemo(() => applyEventOverlay(applyEventOverlay(eventSnapshot, pending), preview), [
|
|
1524
|
+
eventSnapshot,
|
|
1525
|
+
pending,
|
|
1526
|
+
preview
|
|
1527
|
+
]);
|
|
1528
|
+
useLayoutEffect(() => transactions.reconcile(eventSnapshot), [eventSnapshot, transactions]);
|
|
1529
|
+
const stableResources = useStableValue(resources, sameElements);
|
|
1530
|
+
const resourceTree = useMemo(() => createResourceTree(stableResources), [stableResources]);
|
|
1531
|
+
const stableExpandedResourceIds = useStableValue(state.expandedResourceIds, sameElements);
|
|
1532
|
+
const stableAnnotations = useStableValue(annotations, sameElements);
|
|
1533
|
+
const annotationSnapshot = useMemo(() => createAnnotationSnapshot(stableAnnotations), [stableAnnotations]);
|
|
1534
|
+
const stableAnnotationSources = useStableValue(annotationSources, sameElements);
|
|
1535
|
+
const annotationContext = useMemo(() => Object.freeze({
|
|
1536
|
+
snapshot: annotationSnapshot,
|
|
1537
|
+
sources: stableAnnotationSources
|
|
1538
|
+
}), [annotationSnapshot, stableAnnotationSources]);
|
|
1539
|
+
const stableAvailability = useStableValue(availability, sameAvailability);
|
|
1540
|
+
const availabilitySnapshot = useMemo(() => createAvailabilitySnapshot({
|
|
1541
|
+
availability: stableAvailability,
|
|
1542
|
+
resources: stableResources,
|
|
1543
|
+
timeZone: state.timeZone
|
|
1544
|
+
}), [
|
|
1545
|
+
stableAvailability,
|
|
1546
|
+
stableResources,
|
|
1547
|
+
state.timeZone
|
|
1548
|
+
]);
|
|
1549
|
+
const activeDefinition = viewsByName.get(state.view);
|
|
1550
|
+
const viewOverrides = viewOptions;
|
|
1551
|
+
const options = useStableValue(activeDefinition === void 0 ? void 0 : resolveViewOptions(activeDefinition, viewOverrides?.[state.view]), shallowEqual);
|
|
1552
|
+
const range = useStableValue(activeDefinition?.strategy.getRange(state.anchorDate, viewEnvironment, options), sameRange);
|
|
1553
|
+
const loadRange = useStableValue(activeDefinition === void 0 || range === void 0 ? void 0 : resolveViewLoadRange(activeDefinition.strategy, state.anchorDate, viewEnvironment, options, range), sameRange);
|
|
1554
|
+
const instant = useNowFrom(environment, todaySampleIntervalMs);
|
|
1555
|
+
const today = useStableValue(instant === null ? null : instant.toZonedDateTimeISO(state.timeZone).toPlainDate(), samePlainDate);
|
|
1556
|
+
const visibleRange = useMemo(() => activeDefinition === void 0 || range === void 0 || loadRange === void 0 ? null : Object.freeze({
|
|
1557
|
+
instantRange: resolveViewInstantRange(range, viewEnvironment.timeZone),
|
|
1558
|
+
loadInstantRange: resolveViewInstantRange(loadRange, viewEnvironment.timeZone),
|
|
1559
|
+
loadRange,
|
|
1560
|
+
range,
|
|
1561
|
+
view: activeDefinition.name
|
|
1562
|
+
}), [
|
|
1563
|
+
activeDefinition,
|
|
1564
|
+
loadRange,
|
|
1565
|
+
range,
|
|
1566
|
+
viewEnvironment.timeZone
|
|
1567
|
+
]);
|
|
1568
|
+
const activeView = useMemo(() => {
|
|
1569
|
+
if (activeDefinition === void 0 || visibleRange === null) return null;
|
|
1570
|
+
const { instantRange, loadInstantRange, loadRange, range } = visibleRange;
|
|
1571
|
+
return Object.freeze({
|
|
1572
|
+
definition: activeDefinition,
|
|
1573
|
+
environment: viewEnvironment,
|
|
1574
|
+
events: visibleSnapshot,
|
|
1575
|
+
instantRange,
|
|
1576
|
+
loadInstantRange,
|
|
1577
|
+
loadRange,
|
|
1578
|
+
options,
|
|
1579
|
+
projection: activeDefinition.strategy.project({
|
|
1580
|
+
environment: viewEnvironment,
|
|
1581
|
+
expandedResourceIds: stableExpandedResourceIds,
|
|
1582
|
+
instantRange,
|
|
1583
|
+
loadRange,
|
|
1584
|
+
options,
|
|
1585
|
+
range,
|
|
1586
|
+
resources: resourceTree,
|
|
1587
|
+
snapshot: visibleSnapshot,
|
|
1588
|
+
today
|
|
1589
|
+
}),
|
|
1590
|
+
range,
|
|
1591
|
+
view: activeDefinition.name
|
|
1592
|
+
});
|
|
1593
|
+
}, [
|
|
1594
|
+
activeDefinition,
|
|
1595
|
+
options,
|
|
1596
|
+
visibleRange,
|
|
1597
|
+
resourceTree,
|
|
1598
|
+
stableExpandedResourceIds,
|
|
1599
|
+
today,
|
|
1600
|
+
viewEnvironment,
|
|
1601
|
+
visibleSnapshot
|
|
1602
|
+
]);
|
|
1603
|
+
const diagnostics = useStableValue(collectDiagnostics(state.view, activeDefinition !== void 0, eventSnapshot.issues, annotationSnapshot.issues, availabilitySnapshot.issues, secondary.issues), sameDiagnostics);
|
|
1604
|
+
const committedInputs = {
|
|
1605
|
+
activeView,
|
|
1606
|
+
availability: availabilitySnapshot,
|
|
1607
|
+
environment,
|
|
1608
|
+
eventSnapshot,
|
|
1609
|
+
onDiagnosticsChange,
|
|
1610
|
+
onEventChange,
|
|
1611
|
+
onEventChangeResult,
|
|
1612
|
+
onVisibleRangeChange,
|
|
1613
|
+
policies,
|
|
1614
|
+
resourceTree,
|
|
1615
|
+
viewOptions: viewOverrides
|
|
1616
|
+
};
|
|
1617
|
+
const committed = useRef(committedInputs);
|
|
1618
|
+
useInsertionEffect(() => {
|
|
1619
|
+
committed.current = committedInputs;
|
|
1620
|
+
});
|
|
1621
|
+
useEffect(() => committed.current.onDiagnosticsChange?.(diagnostics), [diagnostics]);
|
|
1622
|
+
const reportedRange = useRef(null);
|
|
1623
|
+
useEffect(() => {
|
|
1624
|
+
if (visibleRange === null || visibleRange === reportedRange.current) return;
|
|
1625
|
+
reportedRange.current = visibleRange;
|
|
1626
|
+
committed.current.onVisibleRangeChange?.(visibleRange);
|
|
1627
|
+
}, [visibleRange]);
|
|
1628
|
+
const actions = useMemo(() => createSemanticActions(binding, viewsByName, committed, transactions, readOnly), [binding, transactions]);
|
|
1629
|
+
const [announcements] = useState(() => createAnnouncerChannel(() => committed.current.environment, () => committed.current.resourceTree));
|
|
1630
|
+
const isReadOnly = onEventChange === void 0;
|
|
1631
|
+
const interaction = useMemo(() => Object.freeze({
|
|
1632
|
+
actions,
|
|
1633
|
+
announcements,
|
|
1634
|
+
changes: pendingChanges,
|
|
1635
|
+
isReadOnly,
|
|
1636
|
+
keyboard,
|
|
1637
|
+
pointerDraft,
|
|
1638
|
+
rangeOf: (anchor) => {
|
|
1639
|
+
const view = committed.current.activeView;
|
|
1640
|
+
return view === null ? null : view.definition.strategy.getRange(anchor, view.environment, view.options);
|
|
1641
|
+
},
|
|
1642
|
+
read: binding.read,
|
|
1643
|
+
requests: binding.subscribeRequests,
|
|
1644
|
+
source
|
|
1645
|
+
}), [
|
|
1646
|
+
actions,
|
|
1647
|
+
announcements,
|
|
1648
|
+
binding,
|
|
1649
|
+
isReadOnly,
|
|
1650
|
+
keyboard,
|
|
1651
|
+
pendingChanges,
|
|
1652
|
+
pointerDraft,
|
|
1653
|
+
source
|
|
1654
|
+
]);
|
|
1655
|
+
const [refs] = useState(() => Object.freeze({
|
|
1656
|
+
frame: createRef(),
|
|
1657
|
+
title: createRef(),
|
|
1658
|
+
toolbar: createRef(),
|
|
1659
|
+
viewport: createRef()
|
|
1660
|
+
}));
|
|
1661
|
+
const ids = useMemo(() => Object.freeze({
|
|
1662
|
+
frame: `${instanceId}-frame`,
|
|
1663
|
+
title: `${instanceId}-title`,
|
|
1664
|
+
viewport: `${instanceId}-viewport`
|
|
1665
|
+
}), [instanceId]);
|
|
1666
|
+
const meta = useMemo(() => Object.freeze({
|
|
1667
|
+
activeView: activeDefinition,
|
|
1668
|
+
diagnostics,
|
|
1669
|
+
environment,
|
|
1670
|
+
eventSnapshot: visibleSnapshot,
|
|
1671
|
+
ids,
|
|
1672
|
+
instanceId,
|
|
1673
|
+
refs,
|
|
1674
|
+
resources: stableResources,
|
|
1675
|
+
views: config.views
|
|
1676
|
+
}), [
|
|
1677
|
+
activeDefinition,
|
|
1678
|
+
diagnostics,
|
|
1679
|
+
environment,
|
|
1680
|
+
visibleSnapshot,
|
|
1681
|
+
ids,
|
|
1682
|
+
instanceId,
|
|
1683
|
+
refs,
|
|
1684
|
+
stableResources
|
|
1685
|
+
]);
|
|
1686
|
+
return createElement(CalendarNowSourceContext, { value: environment }, createElement(contexts.source, { value: source }, createElement(contexts.actions, { value: actions }, createElement(contexts.changes, { value: pendingChanges }, createElement(contexts.meta, { value: meta }, createElement(contexts.state, { value: state }, createElement(contexts.view, { value: activeView }, createElement(CalendarResourcesContext, { value: resourceTree }, createElement(CalendarAnnotationsContext, { value: annotationContext }, createElement(CalendarAvailabilityContext, { value: availabilitySnapshot }, createElement(CalendarEventsContext, { value: visibleSnapshot }, createElement(CalendarInteractionContext, { value: interaction }, children))))))))))));
|
|
1687
|
+
};
|
|
1688
|
+
}
|
|
1689
|
+
//#endregion
|
|
1690
|
+
//#region src/calendar.ts
|
|
1691
|
+
/** `useCalendarPendingChanges` without a selector: the map itself. */
|
|
1692
|
+
const allChanges = (changes) => changes;
|
|
1693
|
+
/**
|
|
1694
|
+
* Creates a typed calendar. The first call fixes the application's record types; the second infers
|
|
1695
|
+
* the view-name union and identifier types from `views` and `eventAdapter`.
|
|
1696
|
+
*
|
|
1697
|
+
* ```ts
|
|
1698
|
+
* const Calendar = createCalendar<Meeting, Room>()({ eventAdapter, views: [monthView] });
|
|
1699
|
+
* ```
|
|
1700
|
+
*/
|
|
1701
|
+
function createCalendar() {
|
|
1702
|
+
return function createTypedCalendar(options) {
|
|
1703
|
+
const views = Object.freeze([...options.views ?? []]);
|
|
1704
|
+
const names = /* @__PURE__ */ new Set();
|
|
1705
|
+
for (const view of views) {
|
|
1706
|
+
if (names.has(view.name)) throw new TypeError(`calendar-duplicate-view-name:${view.name}`);
|
|
1707
|
+
names.add(view.name);
|
|
1708
|
+
}
|
|
1709
|
+
const contexts = createCalendarContexts();
|
|
1710
|
+
const { EventPart, ViewSwitcher, ...parts } = createCalendarParts(contexts);
|
|
1711
|
+
const Root = createCalendarRoot({
|
|
1712
|
+
eventAdapter: options.eventAdapter,
|
|
1713
|
+
invalidEventPolicy: options.invalidEventPolicy,
|
|
1714
|
+
views
|
|
1715
|
+
}, contexts);
|
|
1716
|
+
const useCalendarActions = () => useRootContext(contexts.actions);
|
|
1717
|
+
const useCalendarMeta = () => useRootContext(contexts.meta);
|
|
1718
|
+
const useCalendarState = () => useRootContext(contexts.state);
|
|
1719
|
+
return Object.freeze({
|
|
1720
|
+
...parts,
|
|
1721
|
+
Announcer,
|
|
1722
|
+
Event: EventPart,
|
|
1723
|
+
Root,
|
|
1724
|
+
ViewSwitcher,
|
|
1725
|
+
views,
|
|
1726
|
+
useCalendar() {
|
|
1727
|
+
const actions = useCalendarActions();
|
|
1728
|
+
const meta = useCalendarMeta();
|
|
1729
|
+
const state = useCalendarState();
|
|
1730
|
+
return useMemo(() => Object.freeze({
|
|
1731
|
+
actions,
|
|
1732
|
+
meta,
|
|
1733
|
+
state
|
|
1734
|
+
}), [
|
|
1735
|
+
actions,
|
|
1736
|
+
meta,
|
|
1737
|
+
state
|
|
1738
|
+
]);
|
|
1739
|
+
},
|
|
1740
|
+
useCalendarActions,
|
|
1741
|
+
useCalendarMeta,
|
|
1742
|
+
useCalendarPendingChanges(selector, selectorOptions) {
|
|
1743
|
+
return useStateSelector(useRootContext(contexts.changes), selector ?? allChanges, selectorOptions);
|
|
1744
|
+
},
|
|
1745
|
+
useCalendarSelector(selector, selectorOptions) {
|
|
1746
|
+
return useStateSelector(useRootContext(contexts.source), selector, selectorOptions);
|
|
1747
|
+
},
|
|
1748
|
+
useCalendarState,
|
|
1749
|
+
useViewProjection: () => useActiveViewContext(contexts.view),
|
|
1750
|
+
useVisibleRange: () => useActiveViewContext(contexts.view)?.range ?? null
|
|
1751
|
+
});
|
|
1752
|
+
};
|
|
1753
|
+
}
|
|
1754
|
+
//#endregion
|
|
1755
|
+
//#region src/history.ts
|
|
1756
|
+
/**
|
|
1757
|
+
* What the server and hydration read: nothing recorded yet. A plain literal, so a bundler drops
|
|
1758
|
+
* it from a calendar that doesn't use the history.
|
|
1759
|
+
*/
|
|
1760
|
+
const serverSnapshot = {
|
|
1761
|
+
future: [],
|
|
1762
|
+
latest: null,
|
|
1763
|
+
past: [],
|
|
1764
|
+
pending: null
|
|
1765
|
+
};
|
|
1766
|
+
const getServerSnapshot = () => serverSnapshot;
|
|
1767
|
+
/** Whether a change is still validating or saving: a saved one waiting for events is done. */
|
|
1768
|
+
function isUnsettled(changes) {
|
|
1769
|
+
for (const { phase } of changes.values()) if (phase !== "awaiting-events") return true;
|
|
1770
|
+
return false;
|
|
1771
|
+
}
|
|
1772
|
+
/**
|
|
1773
|
+
* Binds an event history to the nearest `Root`: undo and redo propose the inverse through the
|
|
1774
|
+
* root's `proposeEventChange`, against the events the user sees, and with `messages` their
|
|
1775
|
+
* outcomes are spoken through the root's `Announcer`. The history records through `Root`'s
|
|
1776
|
+
* `onEventChangeResult`:
|
|
1777
|
+
*
|
|
1778
|
+
* ```tsx
|
|
1779
|
+
* const [history] = useState(() => createEventHistory<Meeting, string, string>());
|
|
1780
|
+
* <Calendar.Root onEventChangeResult={history.record} …>
|
|
1781
|
+
* <UndoButtons history={history} />
|
|
1782
|
+
* </Calendar.Root>
|
|
1783
|
+
* // Inside: const { canUndo, undo } = useCalendarHistory(history, { messages });
|
|
1784
|
+
* ```
|
|
1785
|
+
*
|
|
1786
|
+
* The server and hydration read an empty history.
|
|
1787
|
+
*/
|
|
1788
|
+
function useCalendarHistory(history, options = {}) {
|
|
1789
|
+
const { actions, announcements, changes } = useInteractionRuntime();
|
|
1790
|
+
const events = useContext(CalendarEventsContext);
|
|
1791
|
+
const latest = useRef({
|
|
1792
|
+
events,
|
|
1793
|
+
options
|
|
1794
|
+
});
|
|
1795
|
+
useInsertionEffect(() => {
|
|
1796
|
+
latest.current = {
|
|
1797
|
+
events,
|
|
1798
|
+
options
|
|
1799
|
+
};
|
|
1800
|
+
});
|
|
1801
|
+
const snapshot = useSyncExternalStore(history.subscribe, history.getSnapshot, getServerSnapshot);
|
|
1802
|
+
const commands = useMemo(() => {
|
|
1803
|
+
/**
|
|
1804
|
+
* Resolves once no change is validating or saving, after the turn in which the last one ended,
|
|
1805
|
+
* so its result has reached `onEventChangeResult` and the history.
|
|
1806
|
+
*/
|
|
1807
|
+
function whenSettled() {
|
|
1808
|
+
if (!isUnsettled(changes.getSnapshot())) return void 0;
|
|
1809
|
+
return new Promise((resolve) => {
|
|
1810
|
+
const unsubscribe = changes.subscribe(() => {
|
|
1811
|
+
if (isUnsettled(changes.getSnapshot())) return;
|
|
1812
|
+
unsubscribe();
|
|
1813
|
+
setTimeout(resolve);
|
|
1814
|
+
});
|
|
1815
|
+
});
|
|
1816
|
+
}
|
|
1817
|
+
function run(direction, { input } = {}) {
|
|
1818
|
+
let checked;
|
|
1819
|
+
const getEvents = () => {
|
|
1820
|
+
const { events } = latest.current;
|
|
1821
|
+
checked ??= events;
|
|
1822
|
+
return events;
|
|
1823
|
+
};
|
|
1824
|
+
const context = {
|
|
1825
|
+
getEvents,
|
|
1826
|
+
input,
|
|
1827
|
+
propose: actions.proposeEventChange,
|
|
1828
|
+
whenSettled
|
|
1829
|
+
};
|
|
1830
|
+
return history[direction](context).then((outcome) => {
|
|
1831
|
+
const build = latest.current.options.messages?.[direction];
|
|
1832
|
+
if (build !== void 0) {
|
|
1833
|
+
const eventId = outcome.status === "empty" ? null : outcome.step.eventId;
|
|
1834
|
+
const event = eventId === null ? void 0 : latest.current.events.get(eventId) ?? checked?.get(eventId);
|
|
1835
|
+
try {
|
|
1836
|
+
announcements.say((where) => build(outcome, {
|
|
1837
|
+
...where,
|
|
1838
|
+
event
|
|
1839
|
+
}));
|
|
1840
|
+
} catch (error) {
|
|
1841
|
+
reportCallbackError(error);
|
|
1842
|
+
}
|
|
1843
|
+
}
|
|
1844
|
+
return outcome;
|
|
1845
|
+
});
|
|
1846
|
+
}
|
|
1847
|
+
return {
|
|
1848
|
+
redo: (commandOptions) => run("redo", commandOptions),
|
|
1849
|
+
undo: (commandOptions) => run("undo", commandOptions)
|
|
1850
|
+
};
|
|
1851
|
+
}, [
|
|
1852
|
+
actions,
|
|
1853
|
+
announcements,
|
|
1854
|
+
changes,
|
|
1855
|
+
history
|
|
1856
|
+
]);
|
|
1857
|
+
return useMemo(() => Object.freeze({
|
|
1858
|
+
...snapshot,
|
|
1859
|
+
...commands,
|
|
1860
|
+
canRedo: snapshot.future.length > 0,
|
|
1861
|
+
canUndo: snapshot.past.length > 0
|
|
1862
|
+
}), [commands, snapshot]);
|
|
1863
|
+
}
|
|
1864
|
+
//#endregion
|
|
1865
|
+
//#region src/history-shortcuts.ts
|
|
1866
|
+
const defaultUndo = ["Mod+Z"];
|
|
1867
|
+
const defaultRedo = ["Shift+Mod+Z", "Ctrl+Y"];
|
|
1868
|
+
const keyboardInput$1 = { input: "keyboard" };
|
|
1869
|
+
/**
|
|
1870
|
+
* Where a key belongs to something else: text the browser undoes in its own field, and dialogs,
|
|
1871
|
+
* menus and lists inside the calendar, which handle their own keys.
|
|
1872
|
+
*/
|
|
1873
|
+
const ownKeys = "input, textarea, select, [contenteditable]:not([contenteditable=\"false\"]), [role=\"textbox\"], [role=\"dialog\"], [role=\"alertdialog\"], [role=\"menu\"], [role=\"listbox\"]";
|
|
1874
|
+
function isApplePlatform() {
|
|
1875
|
+
const { platform, userAgentData } = navigator;
|
|
1876
|
+
return /mac|iphone|ipad|ipod/i.test(userAgentData?.platform ?? platform);
|
|
1877
|
+
}
|
|
1878
|
+
/** Whether `event` is `binding`: exactly its modifiers, and its key by name or position. */
|
|
1879
|
+
function matches(event, binding, apple) {
|
|
1880
|
+
const parts = binding.split("+").map((part) => part.trim().toLowerCase());
|
|
1881
|
+
const key = parts.pop();
|
|
1882
|
+
if (key === void 0 || key === "") return false;
|
|
1883
|
+
let ctrl = false;
|
|
1884
|
+
let meta = false;
|
|
1885
|
+
let shift = false;
|
|
1886
|
+
let alt = false;
|
|
1887
|
+
for (const modifier of parts) if (modifier === "mod") {
|
|
1888
|
+
if (apple) meta = true;
|
|
1889
|
+
else ctrl = true;
|
|
1890
|
+
} else if (modifier === "ctrl" || modifier === "control") ctrl = true;
|
|
1891
|
+
else if (modifier === "meta" || modifier === "cmd" || modifier === "command") meta = true;
|
|
1892
|
+
else if (modifier === "shift") shift = true;
|
|
1893
|
+
else if (modifier === "alt" || modifier === "option") alt = true;
|
|
1894
|
+
else return false;
|
|
1895
|
+
if (event.ctrlKey !== ctrl || event.metaKey !== meta || event.shiftKey !== shift || event.altKey !== alt) return false;
|
|
1896
|
+
const typed = event.key.toLowerCase();
|
|
1897
|
+
if (typed === key) return true;
|
|
1898
|
+
if (/^[a-z0-9]$/.test(typed)) return false;
|
|
1899
|
+
if (/^[a-z]$/.test(key)) return event.code === `Key${key.toUpperCase()}`;
|
|
1900
|
+
return /^[0-9]$/.test(key) && event.code === `Digit${key}`;
|
|
1901
|
+
}
|
|
1902
|
+
/**
|
|
1903
|
+
* Whether something on the key's path inside `scope`, from its target out, handles keys of its
|
|
1904
|
+
* own: a field, also inside a web component's shadow root, or a dialog, menu or list. A dialog
|
|
1905
|
+
* around the whole calendar doesn't count.
|
|
1906
|
+
*/
|
|
1907
|
+
function ownsKeys(path, scope) {
|
|
1908
|
+
for (const node of path) {
|
|
1909
|
+
if (node === scope) return false;
|
|
1910
|
+
if (!(node instanceof Element)) continue;
|
|
1911
|
+
if (node instanceof HTMLElement && node.isContentEditable || node.matches(ownKeys)) return true;
|
|
1912
|
+
}
|
|
1913
|
+
return false;
|
|
1914
|
+
}
|
|
1915
|
+
/**
|
|
1916
|
+
* Undo and redo keys for a calendar: Mod+Z undoes, and Shift+Mod+Z or Ctrl+Y redoes, where Mod is
|
|
1917
|
+
* ⌘ on Apple platforms and Ctrl elsewhere. While the hook is mounted and enabled, one `keydown`
|
|
1918
|
+
* listener on the document acts on keys whose target is inside `scope`, after the page's own
|
|
1919
|
+
* handlers, React's included. Keys never undo in a text field, where the browser undoes the
|
|
1920
|
+
* text, or in a dialog, menu or list inside the scope, nor during a keyboard or pointer gesture,
|
|
1921
|
+
* nor once something else handled them. Commands pass `{ input: "keyboard" }`.
|
|
1922
|
+
*
|
|
1923
|
+
* ```tsx
|
|
1924
|
+
* const history = useCalendarHistory(eventHistory);
|
|
1925
|
+
* useCalendarHistoryShortcuts(history, { scope: Calendar.useCalendarMeta().refs.frame });
|
|
1926
|
+
* ```
|
|
1927
|
+
*/
|
|
1928
|
+
function useCalendarHistoryShortcuts(history, options) {
|
|
1929
|
+
const { keyboard, pointerDraft } = useInteractionRuntime();
|
|
1930
|
+
const latest = useRef({
|
|
1931
|
+
history,
|
|
1932
|
+
options
|
|
1933
|
+
});
|
|
1934
|
+
useInsertionEffect(() => {
|
|
1935
|
+
latest.current = {
|
|
1936
|
+
history,
|
|
1937
|
+
options
|
|
1938
|
+
};
|
|
1939
|
+
});
|
|
1940
|
+
const { disabled = false } = options;
|
|
1941
|
+
useEffect(() => {
|
|
1942
|
+
if (disabled) return;
|
|
1943
|
+
const apple = isApplePlatform();
|
|
1944
|
+
const listener = (event) => {
|
|
1945
|
+
const scope = latest.current.options.scope.current;
|
|
1946
|
+
if (event.defaultPrevented || event.isComposing || scope === null) return;
|
|
1947
|
+
const path = event.composedPath();
|
|
1948
|
+
if (!path.includes(scope)) return;
|
|
1949
|
+
const { undo = defaultUndo, redo = defaultRedo } = latest.current.options;
|
|
1950
|
+
const direction = undo.some((binding) => matches(event, binding, apple)) ? "undo" : redo.some((binding) => matches(event, binding, apple)) ? "redo" : null;
|
|
1951
|
+
if (direction === null || ownsKeys(path, scope)) return;
|
|
1952
|
+
if (keyboard.get() !== null || pointerDraft.getSnapshot() !== null) return;
|
|
1953
|
+
event.preventDefault();
|
|
1954
|
+
try {
|
|
1955
|
+
Promise.resolve(latest.current.history[direction](keyboardInput$1)).catch(reportCallbackError);
|
|
1956
|
+
} catch (error) {
|
|
1957
|
+
reportCallbackError(error);
|
|
1958
|
+
}
|
|
1959
|
+
};
|
|
1960
|
+
document.addEventListener("keydown", listener);
|
|
1961
|
+
return () => document.removeEventListener("keydown", listener);
|
|
1962
|
+
}, [
|
|
1963
|
+
disabled,
|
|
1964
|
+
keyboard,
|
|
1965
|
+
pointerDraft
|
|
1966
|
+
]);
|
|
1967
|
+
}
|
|
1968
|
+
//#endregion
|
|
1969
|
+
//#region src/keyboard.ts
|
|
1970
|
+
const DEFAULT_CREATE_DURATION = { hours: 1 };
|
|
1971
|
+
const keyboardInput = Object.freeze({ input: "keyboard" });
|
|
1972
|
+
const navigationKeys = {
|
|
1973
|
+
ArrowDown: "down",
|
|
1974
|
+
ArrowLeft: "left",
|
|
1975
|
+
ArrowRight: "right",
|
|
1976
|
+
ArrowUp: "up",
|
|
1977
|
+
End: "end",
|
|
1978
|
+
Home: "home",
|
|
1979
|
+
PageDown: "page-down",
|
|
1980
|
+
PageUp: "page-up"
|
|
1981
|
+
};
|
|
1982
|
+
function createKeyboardHandlers({ actions, announcements, isReadOnly, keyboard, read }, { getView, roving }, getOptions, getResources) {
|
|
1983
|
+
const getSnap = () => getOptions().snap ?? DEFAULT_SNAP;
|
|
1984
|
+
const view = () => getView();
|
|
1985
|
+
function navigate(command, focus) {
|
|
1986
|
+
const { definition, environment, options, projection, range } = view();
|
|
1987
|
+
return definition.strategy.getSpatialNavigation?.({
|
|
1988
|
+
command,
|
|
1989
|
+
environment,
|
|
1990
|
+
focus,
|
|
1991
|
+
options,
|
|
1992
|
+
projection,
|
|
1993
|
+
range,
|
|
1994
|
+
snap: getSnap()
|
|
1995
|
+
}) ?? null;
|
|
1996
|
+
}
|
|
1997
|
+
/** The cell a navigation result names, for keys that move a cell. */
|
|
1998
|
+
function cellOf(result) {
|
|
1999
|
+
return result !== null && "focus" in result && result.focus.kind !== "event" ? result.focus : null;
|
|
2000
|
+
}
|
|
2001
|
+
function interactionOptions() {
|
|
2002
|
+
return {
|
|
2003
|
+
snap: getSnap(),
|
|
2004
|
+
timeZone: view().environment.timeZone
|
|
2005
|
+
};
|
|
2006
|
+
}
|
|
2007
|
+
/** Navigates the view by whole ranges until it shows `date`. */
|
|
2008
|
+
function reveal(date) {
|
|
2009
|
+
const { definition, environment, options, range } = view();
|
|
2010
|
+
if (plainDateIntervalContains(range, date)) return;
|
|
2011
|
+
const { anchorDate } = read();
|
|
2012
|
+
actions.setAnchorDate(anchorShowingDate(definition.strategy, anchorDate, date, environment, options));
|
|
2013
|
+
}
|
|
2014
|
+
/** Moves the calendar's focus and, once the view renders it, DOM focus. */
|
|
2015
|
+
function moveFocus(focus) {
|
|
2016
|
+
if (sameFocus(focus, read().focus)) {
|
|
2017
|
+
roving.focusTabStop("now");
|
|
2018
|
+
return;
|
|
2019
|
+
}
|
|
2020
|
+
roving.focusTabStop("after-update");
|
|
2021
|
+
actions.setFocus(focus);
|
|
2022
|
+
if (focus !== null) reveal(focus.date);
|
|
2023
|
+
}
|
|
2024
|
+
function apply(result) {
|
|
2025
|
+
if (result === null) return false;
|
|
2026
|
+
if ("focus" in result) moveFocus(result.focus);
|
|
2027
|
+
else {
|
|
2028
|
+
const { definition, options } = view();
|
|
2029
|
+
roving.focusTabStop("after-update");
|
|
2030
|
+
if (result.page < 0) roving.enterFromEnd();
|
|
2031
|
+
actions.setAnchorDate(definition.strategy.navigate(read().anchorDate, result.page, options));
|
|
2032
|
+
actions.setFocus(null);
|
|
2033
|
+
}
|
|
2034
|
+
return true;
|
|
2035
|
+
}
|
|
2036
|
+
function announce(grab, detail) {
|
|
2037
|
+
const { check, session } = grab;
|
|
2038
|
+
announcements.announcer.announce({
|
|
2039
|
+
cause: session.cause,
|
|
2040
|
+
event: grab.event,
|
|
2041
|
+
input: "keyboard",
|
|
2042
|
+
original: session.original,
|
|
2043
|
+
proposed: session.proposed,
|
|
2044
|
+
...detail.phase === "start" || detail.phase === "step" ? { check } : void 0,
|
|
2045
|
+
...detail
|
|
2046
|
+
});
|
|
2047
|
+
}
|
|
2048
|
+
/** What the root's policies would say to committing `session` now, as its preview shows. */
|
|
2049
|
+
function checkOf(session) {
|
|
2050
|
+
const proposal = keyboardSessionProposal(session);
|
|
2051
|
+
return proposal === null ? null : actions.checkEventChange(proposal);
|
|
2052
|
+
}
|
|
2053
|
+
/**
|
|
2054
|
+
* Follows the grabbed event into the cursor's date and resource, or a create's cell. A move out
|
|
2055
|
+
* of the event's last copy in a resource, as into the unassigned bucket, follows it to a resource
|
|
2056
|
+
* it still shows in.
|
|
2057
|
+
*/
|
|
2058
|
+
function focusOfSession(session) {
|
|
2059
|
+
const { cursor, eventId, proposed } = session;
|
|
2060
|
+
return eventId === null ? cursor : {
|
|
2061
|
+
date: cursor.date,
|
|
2062
|
+
eventId,
|
|
2063
|
+
kind: "event",
|
|
2064
|
+
resourceId: resourceOn(proposed, cursor.resourceId)
|
|
2065
|
+
};
|
|
2066
|
+
}
|
|
2067
|
+
/** A slot create starts `createDuration` long: its cursor steps later, as a drag would. */
|
|
2068
|
+
function startCreate(cell) {
|
|
2069
|
+
let session = startKeyboardSession({
|
|
2070
|
+
cause: "create",
|
|
2071
|
+
cell
|
|
2072
|
+
}, interactionOptions());
|
|
2073
|
+
if (cell.kind !== "slot") return session;
|
|
2074
|
+
const later = getOptions().axis !== "inline" ? "down" : view().environment.direction === "rtl" ? "left" : "right";
|
|
2075
|
+
const duration = Temporal.Duration.from(getOptions().createDuration ?? DEFAULT_CREATE_DURATION);
|
|
2076
|
+
const slots = Math.round(duration.total({ unit: "minutes" }) / slotDuration(getSnap()).total({ unit: "minutes" }));
|
|
2077
|
+
for (let step = 1; step < slots; step += 1) {
|
|
2078
|
+
const cursor = cellOf(navigate(later, session.cursor));
|
|
2079
|
+
if (cursor === null) break;
|
|
2080
|
+
session = moveKeyboardCursor(session, cursor, interactionOptions());
|
|
2081
|
+
}
|
|
2082
|
+
return session;
|
|
2083
|
+
}
|
|
2084
|
+
function grab(focus, cause) {
|
|
2085
|
+
if (focus.kind !== "event") {
|
|
2086
|
+
if (cause !== "create") return false;
|
|
2087
|
+
const session = startCreate(focus);
|
|
2088
|
+
const next = {
|
|
2089
|
+
cell: focus,
|
|
2090
|
+
check: checkOf(session),
|
|
2091
|
+
event: null,
|
|
2092
|
+
origin: focus,
|
|
2093
|
+
session
|
|
2094
|
+
};
|
|
2095
|
+
keyboard.set(next);
|
|
2096
|
+
moveFocus(focusOfSession(session));
|
|
2097
|
+
announce(next, { phase: "start" });
|
|
2098
|
+
return true;
|
|
2099
|
+
}
|
|
2100
|
+
if (cause === "create") return false;
|
|
2101
|
+
const event = view().events.get(focus.eventId);
|
|
2102
|
+
const cell = cellOf(navigate("exit", focus));
|
|
2103
|
+
if (event === void 0 || cell === null) return false;
|
|
2104
|
+
const next = {
|
|
2105
|
+
cell,
|
|
2106
|
+
check: null,
|
|
2107
|
+
event,
|
|
2108
|
+
origin: focus,
|
|
2109
|
+
session: startKeyboardSession({
|
|
2110
|
+
cause,
|
|
2111
|
+
cell,
|
|
2112
|
+
event
|
|
2113
|
+
}, interactionOptions())
|
|
2114
|
+
};
|
|
2115
|
+
if (event.isReadOnly) {
|
|
2116
|
+
announce(next, {
|
|
2117
|
+
phase: "reject",
|
|
2118
|
+
reason: "read-only"
|
|
2119
|
+
});
|
|
2120
|
+
return true;
|
|
2121
|
+
}
|
|
2122
|
+
keyboard.set(next);
|
|
2123
|
+
announce(next, { phase: "start" });
|
|
2124
|
+
return true;
|
|
2125
|
+
}
|
|
2126
|
+
function step(current, command) {
|
|
2127
|
+
const cursor = cellOf(navigate(command, current.session.cursor));
|
|
2128
|
+
if (cursor === null) return;
|
|
2129
|
+
const session = moveKeyboardCursor(current.session, cursor, interactionOptions());
|
|
2130
|
+
if (session === current.session) return;
|
|
2131
|
+
const next = {
|
|
2132
|
+
...current,
|
|
2133
|
+
check: checkOf(session),
|
|
2134
|
+
session
|
|
2135
|
+
};
|
|
2136
|
+
keyboard.set(next);
|
|
2137
|
+
moveFocus(focusOfSession(session));
|
|
2138
|
+
announce(next, { phase: "step" });
|
|
2139
|
+
}
|
|
2140
|
+
/** Grabs the other edge, starting the resize over from the event as it was. */
|
|
2141
|
+
function switchEdge(current) {
|
|
2142
|
+
const { cell, event, session } = current;
|
|
2143
|
+
if (event === null || !session.cause.startsWith("resize")) return;
|
|
2144
|
+
const cause = session.cause === "resize-end" ? "resize-start" : "resize-end";
|
|
2145
|
+
const restarted = startKeyboardSession({
|
|
2146
|
+
cause,
|
|
2147
|
+
cell,
|
|
2148
|
+
event
|
|
2149
|
+
}, interactionOptions());
|
|
2150
|
+
const next = {
|
|
2151
|
+
...current,
|
|
2152
|
+
check: null,
|
|
2153
|
+
session: restarted
|
|
2154
|
+
};
|
|
2155
|
+
keyboard.set(next);
|
|
2156
|
+
moveFocus(focusOfSession(restarted));
|
|
2157
|
+
announce(next, { phase: "start" });
|
|
2158
|
+
}
|
|
2159
|
+
function cancel(current) {
|
|
2160
|
+
keyboard.set(null);
|
|
2161
|
+
moveFocus(current.origin);
|
|
2162
|
+
announce(current, { phase: "cancel" });
|
|
2163
|
+
}
|
|
2164
|
+
function commit(current) {
|
|
2165
|
+
const proposal = keyboardSessionProposal(current.session);
|
|
2166
|
+
if (proposal === null) {
|
|
2167
|
+
cancel(current);
|
|
2168
|
+
return;
|
|
2169
|
+
}
|
|
2170
|
+
keyboard.set(null);
|
|
2171
|
+
const focused = read().focus;
|
|
2172
|
+
const { definition } = view();
|
|
2173
|
+
const owned = () => keyboard.get() === null && getView()?.definition === definition && sameFocus(read().focus, focused);
|
|
2174
|
+
actions.proposeEventChange(proposal, keyboardInput).then((result) => {
|
|
2175
|
+
if (result.status === "committed") {
|
|
2176
|
+
const { eventId, proposed } = result.change;
|
|
2177
|
+
if (eventId !== null && proposed !== null && owned()) {
|
|
2178
|
+
const { cursor } = current.session;
|
|
2179
|
+
moveFocus({
|
|
2180
|
+
date: dateOn(proposed, cursor.date),
|
|
2181
|
+
eventId,
|
|
2182
|
+
kind: "event",
|
|
2183
|
+
resourceId: resourceOn(proposed, cursor.resourceId)
|
|
2184
|
+
});
|
|
2185
|
+
}
|
|
2186
|
+
announce(current, {
|
|
2187
|
+
phase: "commit",
|
|
2188
|
+
proposed,
|
|
2189
|
+
warnings: result.change.warnings
|
|
2190
|
+
});
|
|
2191
|
+
} else {
|
|
2192
|
+
if (owned()) moveFocus(current.origin);
|
|
2193
|
+
announce(current, {
|
|
2194
|
+
phase: "reject",
|
|
2195
|
+
reason: result.reason,
|
|
2196
|
+
...result.error === void 0 ? {} : { error: result.error }
|
|
2197
|
+
});
|
|
2198
|
+
}
|
|
2199
|
+
});
|
|
2200
|
+
}
|
|
2201
|
+
/** `date` when `placement` covers it, else the placement's first date. */
|
|
2202
|
+
function dateOn(placement, date) {
|
|
2203
|
+
const { timeZone } = view().environment;
|
|
2204
|
+
const wall = (point) => point instanceof Temporal.Instant ? point.toZonedDateTimeISO(timeZone).toPlainDateTime() : point;
|
|
2205
|
+
const [first, last] = placement.kind === "all-day" ? [placement.start, placement.end.subtract({ days: 1 })] : [wall(placement.start).toPlainDate(), wall(placement.end).subtract({ nanoseconds: 1 }).toPlainDate()];
|
|
2206
|
+
return Temporal.PlainDate.compare(first, date) <= 0 && Temporal.PlainDate.compare(date, last) <= 0 ? date : first;
|
|
2207
|
+
}
|
|
2208
|
+
/**
|
|
2209
|
+
* The resource focus follows a placement into: `resourceId` when the placement shows there, else
|
|
2210
|
+
* the first resource it books that is visible, so the copy focus moves to renders, even scrolled
|
|
2211
|
+
* out of view, and the unassigned bucket when it books none.
|
|
2212
|
+
*/
|
|
2213
|
+
function resourceOn(placement, resourceId) {
|
|
2214
|
+
const booked = placement.resourceIds;
|
|
2215
|
+
if (resourceId === void 0 || showsInResource(booked, resourceId)) return resourceId;
|
|
2216
|
+
if (booked.length === 0) return null;
|
|
2217
|
+
const tree = getResources();
|
|
2218
|
+
const visible = tree === null ? [] : visibleResources(tree, read().expandedResourceIds);
|
|
2219
|
+
return booked.find((id) => visible.some((row) => row.id === id));
|
|
2220
|
+
}
|
|
2221
|
+
function onGrabbedKey(current, event) {
|
|
2222
|
+
const command = navigationKeys[event.key];
|
|
2223
|
+
if (command !== void 0) {
|
|
2224
|
+
step(current, command);
|
|
2225
|
+
return true;
|
|
2226
|
+
}
|
|
2227
|
+
switch (event.key) {
|
|
2228
|
+
case "Enter":
|
|
2229
|
+
commit(current);
|
|
2230
|
+
return true;
|
|
2231
|
+
case " ":
|
|
2232
|
+
if (event.shiftKey) switchEdge(current);
|
|
2233
|
+
else commit(current);
|
|
2234
|
+
return true;
|
|
2235
|
+
case "Escape":
|
|
2236
|
+
cancel(current);
|
|
2237
|
+
return true;
|
|
2238
|
+
case "Tab":
|
|
2239
|
+
cancel(current);
|
|
2240
|
+
return false;
|
|
2241
|
+
default: return false;
|
|
2242
|
+
}
|
|
2243
|
+
}
|
|
2244
|
+
function onIdleKey(focus, event) {
|
|
2245
|
+
const command = navigationKeys[event.key];
|
|
2246
|
+
if (command !== void 0) return !event.shiftKey && apply(navigate(command, focus));
|
|
2247
|
+
if (focus === null) return false;
|
|
2248
|
+
switch (event.key) {
|
|
2249
|
+
case "Enter": return focus.kind !== "event" && !event.shiftKey && apply(navigate("enter", focus));
|
|
2250
|
+
case "Escape": return focus.kind === "event" && apply(navigate("exit", focus));
|
|
2251
|
+
case " ": return !isReadOnly && grab(focus, focus.kind !== "event" ? "create" : event.shiftKey ? "resize-end" : "move");
|
|
2252
|
+
default: return false;
|
|
2253
|
+
}
|
|
2254
|
+
}
|
|
2255
|
+
return Object.freeze({
|
|
2256
|
+
onBlur(event) {
|
|
2257
|
+
if (keyboard.get() === null) return;
|
|
2258
|
+
const region = event.currentTarget;
|
|
2259
|
+
const next = event.relatedTarget;
|
|
2260
|
+
if (next !== null && region.contains(next)) return;
|
|
2261
|
+
setTimeout(() => {
|
|
2262
|
+
const current = keyboard.get();
|
|
2263
|
+
if (current !== null && !region.contains(document.activeElement)) cancel(current);
|
|
2264
|
+
});
|
|
2265
|
+
},
|
|
2266
|
+
onKeyDown(event) {
|
|
2267
|
+
if (event.defaultPrevented || event.nativeEvent.isComposing) return;
|
|
2268
|
+
if (event.altKey || event.ctrlKey || event.metaKey) return;
|
|
2269
|
+
const current = keyboard.get();
|
|
2270
|
+
if (!(current === null ? onIdleKey(roving.focusAt(event.target), event) : onGrabbedKey(current, event))) return;
|
|
2271
|
+
event.preventDefault();
|
|
2272
|
+
if (event.key === "Escape") event.stopPropagation();
|
|
2273
|
+
}
|
|
2274
|
+
});
|
|
2275
|
+
}
|
|
2276
|
+
/**
|
|
2277
|
+
* Keyboard navigation and keyboard move, resize, and create for a view; spread the handlers on
|
|
2278
|
+
* the element around its focusable cells and events (see `useRovingFocus`).
|
|
2279
|
+
*
|
|
2280
|
+
* - Arrow keys, Home, End, Page Up, and Page Down move focus through the view's
|
|
2281
|
+
* `getSpatialNavigation`, navigating the view when focus leaves it. Enter moves into a cell's
|
|
2282
|
+
* events and Escape back out.
|
|
2283
|
+
* - Space grabs the focused event to move it, or the focused cell to create an event there;
|
|
2284
|
+
* Shift+Space grabs an event's end to resize it, and again switches to its start. Navigation
|
|
2285
|
+
* keys then step the gesture, Enter or Space commits it through `proposeEventChange`, and
|
|
2286
|
+
* Escape, Tab, or leaving the view cancels it. On a root without `onEventChange`, Space grabs
|
|
2287
|
+
* nothing.
|
|
2288
|
+
*
|
|
2289
|
+
* Every phase is announced through the root's `Announcer`.
|
|
2290
|
+
*/
|
|
2291
|
+
function useCalendarKeyboard(options = {}) {
|
|
2292
|
+
const interaction = useInteractionRuntime();
|
|
2293
|
+
const view = useViewRuntime();
|
|
2294
|
+
const resources = useContext(CalendarResourcesContext);
|
|
2295
|
+
const latest = useRef({
|
|
2296
|
+
options,
|
|
2297
|
+
resources
|
|
2298
|
+
});
|
|
2299
|
+
useInsertionEffect(() => {
|
|
2300
|
+
latest.current = {
|
|
2301
|
+
options,
|
|
2302
|
+
resources
|
|
2303
|
+
};
|
|
2304
|
+
});
|
|
2305
|
+
const handlers = useMemo(() => createKeyboardHandlers(interaction, view, () => latest.current.options, () => latest.current.resources), [interaction, view]);
|
|
2306
|
+
const { keyboard } = interaction;
|
|
2307
|
+
useEffect(() => () => keyboard.set(null), [keyboard]);
|
|
2308
|
+
return handlers;
|
|
2309
|
+
}
|
|
2310
|
+
const selectSession = (session) => session;
|
|
2311
|
+
function useCalendarInteraction(selector = selectSession, options) {
|
|
2312
|
+
return useStateSelector(useInteractionRuntime().keyboard.grabs, (grab) => selector(grab?.session ?? null, grab?.check ?? null), options);
|
|
2313
|
+
}
|
|
2314
|
+
//#endregion
|
|
2315
|
+
//#region src/selectors.ts
|
|
2316
|
+
/**
|
|
2317
|
+
* Selects from the calendar's focus for a view's item, such as whether a slot cursor sits on this
|
|
2318
|
+
* column. A component re-renders only when its result changes.
|
|
2319
|
+
*/
|
|
2320
|
+
function useCalendarFocus(selector, options) {
|
|
2321
|
+
return useStateSelector(useInteractionRuntime().source, (state) => selector(state.focus), options);
|
|
2322
|
+
}
|
|
2323
|
+
/**
|
|
2324
|
+
* Selects from the calendar's selection, as `useCalendarFocus` does from its focus:
|
|
2325
|
+
* `useCalendarSelection((selection) => selection?.kind === "event" && selection.eventId === id)`.
|
|
2326
|
+
*/
|
|
2327
|
+
function useCalendarSelection(selector, options) {
|
|
2328
|
+
return useStateSelector(useInteractionRuntime().source, (state) => selector(state.selection), options);
|
|
2329
|
+
}
|
|
2330
|
+
//#endregion
|
|
2331
|
+
//#region src/requests.ts
|
|
2332
|
+
/**
|
|
2333
|
+
* Calls `listener` whenever something asks the calendar for an anchor date: Previous, Next,
|
|
2334
|
+
* Today, keys paging past the view, or `setAnchorDate`, even a date that is already the anchor.
|
|
2335
|
+
* `range` is what the view on screen shows for that date, so a view can tell a request for the
|
|
2336
|
+
* range it has, as Today in this week, from one that moves it. A view whose scroll position can
|
|
2337
|
+
* run ahead of the anchor, as a scrolling view's does while a controlled anchor catches up, uses
|
|
2338
|
+
* it to show its range again when asked.
|
|
2339
|
+
*/
|
|
2340
|
+
function useAnchorDateRequests(listener) {
|
|
2341
|
+
const { rangeOf, requests } = useInteractionRuntime();
|
|
2342
|
+
const latest = useRef(listener);
|
|
2343
|
+
useInsertionEffect(() => {
|
|
2344
|
+
latest.current = listener;
|
|
2345
|
+
});
|
|
2346
|
+
useLayoutEffect(() => requests((slice, value) => {
|
|
2347
|
+
if (slice !== "anchorDate") return;
|
|
2348
|
+
const date = value;
|
|
2349
|
+
latest.current(date, rangeOf(date));
|
|
2350
|
+
}), [rangeOf, requests]);
|
|
2351
|
+
}
|
|
2352
|
+
//#endregion
|
|
2353
|
+
export { createCalendar, createCalendarStore, defineCalendarView, useAnchorDateRequests, useBusyResources, useCalendarAnnotations, useCalendarAnnouncer, useCalendarAvailability, useCalendarDraft, useCalendarDraftReporter, useCalendarFocus, useCalendarHistory, useCalendarHistoryShortcuts, useCalendarInteraction, useCalendarKeyboard, useCalendarSelection, useClosedDates, useDraftBusy, useNow, useResourceExpansion, useResourceStatus, useRovingFocus, useTimeGridAnnotations, useTimeGridAvailability, useTimelineAvailability, useVisibleResources };
|