@moltenship/calendar-react 1.0.0-rc.2 → 2.0.0-beta.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/dist/index.mjs CHANGED
@@ -1,8 +1,10 @@
1
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";
2
+ import { anchorShowingDate, busyResources, closedDates, fitsAvailability, keyboardSessionProposal, moveKeyboardCursor, projectTimeGridAnnotations, projectTimeGridAvailability, projectTimelineAvailability, resourceStatusAt, sameFocus, showsInResource, slotDuration, startKeyboardSession, visibleResources } from "@moltenship/calendar-core";
3
3
  import { createContext, createElement, createRef, useCallback, useContext, useEffect, useId, useInsertionEffect, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
4
+ import { TODAY_SAMPLE_INTERVAL_MS, clockOf, createCalendarPartIds, createCalendarPrimitive, createCalendarRuntime, createCalendarStore, createClockTicker, reportCallbackError, resolveCalendarStoreDefaults, sameElements } from "@moltenship/calendar-primitives";
5
+ import { usePart, usePrimitive } from "@ui-sdk/react/primitive";
4
6
  import { createSystemClock, plainDateIntervalContains } from "@moltenship/calendar-temporal";
5
- //#region src/annotations.ts
7
+ // src/annotations.ts
6
8
  /** The nearest root's annotations, shared by every factory so annotation hooks work in any view. */
7
9
  const CalendarAnnotationsContext = createContext(null);
8
10
  function useCalendarAnnotations() {
@@ -31,8 +33,7 @@ function useTimeGridAnnotations(columns, { layout, maxLanes, minGap, minHeight }
31
33
  sources
32
34
  ]);
33
35
  }
34
- //#endregion
35
- //#region src/interaction.ts
36
+ // src/interaction.ts
36
37
  /** Time-grid slots when a view does not choose its own, as in the pointer layer. */
37
38
  const DEFAULT_SNAP = Object.freeze({
38
39
  increment: 15,
@@ -50,56 +51,7 @@ function useViewRuntime() {
50
51
  if (runtime === null) throw new Error("calendar-view-hook-outside-active-view");
51
52
  return runtime;
52
53
  }
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
- }
54
+ // src/announcer.ts
103
55
  /** Hidden from view but read by screen readers. */
104
56
  const visuallyHidden = {
105
57
  border: 0,
@@ -149,8 +101,7 @@ function Announcer({ messages, style, ...props }) {
149
101
  function useCalendarAnnouncer() {
150
102
  return useInteractionRuntime().announcements.announcer;
151
103
  }
152
- //#endregion
153
- //#region src/availability.ts
104
+ // src/availability.ts
154
105
  /** The nearest root's working hours, shared by every factory so the hooks work in any view. */
155
106
  const CalendarAvailabilityContext = createContext(null);
156
107
  /** The root's working hours: the calendar's, and each resource's on its time zone. */
@@ -190,13 +141,13 @@ function useClosedDates(range, resourceId) {
190
141
  timeZone
191
142
  ]);
192
143
  }
193
- //#endregion
194
- //#region src/context.ts
144
+ // src/context.ts
195
145
  /** Each factory owns its contexts, so its hooks resolve its own root inside another calendar. */
196
146
  function createCalendarContexts() {
197
147
  return Object.freeze({
198
148
  actions: createContext(null),
199
149
  changes: createContext(null),
150
+ handle: createContext(null),
200
151
  meta: createContext(null),
201
152
  source: createContext(null),
202
153
  state: createContext(null),
@@ -215,288 +166,7 @@ function useActiveViewContext(context) {
215
166
  if (view === void 0) throw new Error("calendar-hook-outside-root");
216
167
  return view;
217
168
  }
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
- }
169
+ // src/state-binding.ts
500
170
  /** Subscribes once per source; inline selectors and `isEqual` callbacks are read per render. */
501
171
  function useStateSelector(source, selector, { isEqual = Object.is } = {}) {
502
172
  const committed = useRef(null);
@@ -527,8 +197,7 @@ function useStateSelector(source, selector, { isEqual = Object.is } = {}) {
527
197
  });
528
198
  return selected;
529
199
  }
530
- //#endregion
531
- //#region src/roving-focus.ts
200
+ // src/roving-focus.ts
532
201
  /** Whether `focus` is on an element that shows `target` across `days` dates. */
533
202
  function focusLandsOn(focus, target, days) {
534
203
  if (focus.kind === "event" && target.kind === "event") {
@@ -768,7 +437,10 @@ function useRovingFocus(target, { days = 1 } = {}) {
768
437
  if (event.target !== event.currentTarget) return;
769
438
  const focus = read().focus;
770
439
  const landed = focus === null ? null : landOn(focus, latest.current, days);
771
- if (landed === null || landed !== focus) actions.setFocus(landed ?? latest.current);
440
+ if (landed === null || landed !== focus) actions.setFocus(landed ?? latest.current, {
441
+ event: event.nativeEvent,
442
+ reason: "focus-change"
443
+ });
772
444
  }, [
773
445
  actions,
774
446
  days,
@@ -778,17 +450,30 @@ function useRovingFocus(target, { days = 1 } = {}) {
778
450
  tabIndex: tabStop ? 0 : -1
779
451
  };
780
452
  }
781
- //#endregion
782
- //#region src/parts.ts
453
+ // src/parts.ts
783
454
  const selectView = (state) => state.view;
455
+ /**
456
+ * The elements of the copies of a part still mounted, by the root's ref they share. An application
457
+ * may render two copies of a part: the ref holds the latest one, and a copy that unmounts gives it
458
+ * back to the other instead of emptying it.
459
+ */
460
+ const mountedByRef = /* @__PURE__ */ new WeakMap();
784
461
  function useComposedRef(internalRef, externalRef) {
785
462
  return useCallback((node) => {
786
- internalRef.current = node;
463
+ if (node !== null) {
464
+ const mounted = mountedByRef.get(internalRef) ?? [];
465
+ mountedByRef.set(internalRef, mounted);
466
+ mounted.push(node);
467
+ internalRef.current = node;
468
+ }
787
469
  const externalCleanup = typeof externalRef === "function" ? externalRef(node) : void 0;
788
470
  if (externalRef !== null && externalRef !== void 0 && typeof externalRef !== "function") externalRef.current = node;
789
471
  if (node === null) return void 0;
790
472
  return () => {
791
- internalRef.current = null;
473
+ const mounted = mountedByRef.get(internalRef) ?? [];
474
+ const index = mounted.lastIndexOf(node);
475
+ if (index !== -1) mounted.splice(index, 1);
476
+ internalRef.current = mounted.at(-1) ?? null;
792
477
  if (typeof externalRef === "function") {
793
478
  if (typeof externalCleanup === "function") externalCleanup();
794
479
  else externalRef(null);
@@ -799,87 +484,96 @@ function useComposedRef(internalRef, externalRef) {
799
484
  /** Builds the compound parts that read one factory's root. */
800
485
  function createCalendarParts(contexts) {
801
486
  function Frame({ children, ref, ...props }) {
487
+ const handle = useRootContext(contexts.handle);
802
488
  const meta = useRootContext(contexts.meta);
803
489
  const composedRef = useComposedRef(meta.refs.frame, ref);
804
- return createElement("section", {
805
- "aria-labelledby": meta.ids.title,
490
+ const elementProps = {
491
+ ...meta.label === void 0 ? { "aria-labelledby": meta.ids.title } : { "aria-label": meta.label },
806
492
  ...props,
493
+ children,
807
494
  "data-calendar-instance": meta.instanceId,
808
495
  "data-calendar-part": "frame",
809
496
  id: meta.ids.frame,
810
497
  ref: composedRef
811
- }, children);
498
+ };
499
+ return usePart(handle, "root", {}, elementProps, "section");
812
500
  }
813
501
  function Toolbar({ children, ref, ...props }) {
502
+ const handle = useRootContext(contexts.handle);
814
503
  const composedRef = useComposedRef(useRootContext(contexts.meta).refs.toolbar, ref);
815
- return createElement("header", {
504
+ return usePart(handle, "toolbar", {}, {
816
505
  ...props,
506
+ children,
817
507
  "data-calendar-part": "toolbar",
818
508
  ref: composedRef
819
- }, children);
509
+ }, "header");
820
510
  }
821
511
  function Viewport({ children, ref, ...props }) {
512
+ const handle = useRootContext(contexts.handle);
822
513
  const meta = useRootContext(contexts.meta);
823
514
  const composedRef = useComposedRef(meta.refs.viewport, ref);
824
- return createElement("div", {
515
+ return usePart(handle, "viewport", {}, {
825
516
  ...props,
517
+ children,
826
518
  "data-calendar-part": "viewport",
827
519
  id: meta.ids.viewport,
828
520
  ref: composedRef
829
- }, children);
521
+ }, "div");
830
522
  }
831
523
  function Title({ children, ref, ...props }) {
524
+ const handle = useRootContext(contexts.handle);
832
525
  const meta = useRootContext(contexts.meta);
833
526
  const activeView = useActiveViewContext(contexts.view);
834
527
  const composedRef = useComposedRef(meta.refs.title, ref);
835
528
  const title = useMemo(() => activeView?.definition.strategy.getTitle(activeView.range, activeView.environment, activeView.options) ?? "", [activeView]);
836
- return createElement("span", {
529
+ return usePart(handle, "title", {}, {
837
530
  ...props,
531
+ children: children ?? title,
838
532
  "data-calendar-part": "title",
839
533
  id: meta.ids.title,
840
534
  ref: composedRef
841
- }, children ?? title);
535
+ }, "span");
842
536
  }
843
- function createTrigger(part, command) {
844
- return function Trigger({ children, disabled, ref, type = "button", ...props }) {
845
- const actions = useRootContext(contexts.actions);
537
+ function createTrigger(part, requiresView) {
538
+ return function Trigger({ children, disabled, type = "button", ...props }) {
539
+ const handle = useRootContext(contexts.handle);
846
540
  const meta = useRootContext(contexts.meta);
847
- const requiresView = command !== "navigateToday";
848
- return createElement("button", {
541
+ const elementProps = {
849
542
  ...props,
850
543
  "aria-controls": props["aria-controls"] ?? meta.ids.viewport,
544
+ children,
851
545
  "data-calendar-part": part,
852
546
  disabled: disabled ?? (requiresView && meta.activeView === void 0),
853
- onClick: (event) => {
854
- props.onClick?.(event);
855
- if (!event.defaultPrevented) actions[command]();
856
- },
857
- ref,
858
547
  type
859
- }, children);
548
+ };
549
+ return usePart(handle, part, {}, elementProps, "button");
860
550
  };
861
551
  }
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);
552
+ const PreviousTrigger = createTrigger("previous-trigger", true);
553
+ const NextTrigger = createTrigger("next-trigger", true);
554
+ const TodayTrigger = createTrigger("today-trigger", false);
555
+ function ViewSwitcher({ getViewLabel, onChange, ...props }) {
556
+ const handle = useRootContext(contexts.handle);
867
557
  const meta = useRootContext(contexts.meta);
868
558
  const view = useStateSelector(useRootContext(contexts.source), selectView);
869
- return createElement("select", {
559
+ const elementProps = {
870
560
  ...props,
561
+ children: meta.views.map(({ name }) => createElement("option", {
562
+ key: name,
563
+ value: name
564
+ }, getViewLabel(name))),
871
565
  "data-calendar-part": "view-switcher",
872
566
  onChange: (event) => {
873
567
  onChange?.(event);
874
- const next = event.currentTarget.value;
875
- if (!event.defaultPrevented && meta.views.some((candidate) => candidate.name === next)) actions.setView(next);
568
+ if (event.defaultPrevented) return;
569
+ handle.api.selectView(event.currentTarget.value, {
570
+ event: event.nativeEvent,
571
+ reason: "input-change"
572
+ });
876
573
  },
877
- ref,
878
574
  value: view
879
- }, meta.views.map(({ name }) => createElement("option", {
880
- key: name,
881
- value: name
882
- }, getViewLabel(name))));
575
+ };
576
+ return usePart(handle, "view-switcher", {}, elementProps, "select");
883
577
  }
884
578
  function ActiveView({ fallback = null }) {
885
579
  const actions = useRootContext(contexts.actions);
@@ -931,227 +625,9 @@ function createCalendarParts(contexts) {
931
625
  Viewport
932
626
  });
933
627
  }
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
628
+ // src/event-input.ts
1153
629
  const readNothing = () => null;
1154
- const subscribeToNothing$1 = () => () => void 0;
630
+ const subscribeToNothing$2 = () => () => void 0;
1155
631
  function isEventSource(input) {
1156
632
  return !Array.isArray(input);
1157
633
  }
@@ -1165,7 +641,7 @@ function useEventInput(input) {
1165
641
  const { read, readServer, subscribe } = useMemo(() => source === void 0 ? {
1166
642
  read: readNothing,
1167
643
  readServer: readNothing,
1168
- subscribe: subscribeToNothing$1
644
+ subscribe: subscribeToNothing$2
1169
645
  } : {
1170
646
  read: () => source.getSnapshot(),
1171
647
  readServer: () => source.getServerSnapshot(),
@@ -1174,47 +650,23 @@ function useEventInput(input) {
1174
650
  const sourced = useSyncExternalStore(subscribe, read, readServer);
1175
651
  return source === void 0 ? input : sourced;
1176
652
  }
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
653
+ // src/resources.ts
1216
654
  /** The nearest root's resource tree, shared by every factory so resource hooks work in any view. */
1217
655
  const CalendarResourcesContext = createContext(null);
656
+ /** A command's options from what a toggle got: the click a person made, or a caller's options. */
657
+ function commandOf(cause) {
658
+ if (typeof cause !== "object" || cause === null) return { reason: "resource-toggle" };
659
+ if ("nativeEvent" in cause && cause.nativeEvent instanceof Event) return {
660
+ event: cause.nativeEvent,
661
+ reason: "resource-toggle"
662
+ };
663
+ const { event, reason, source } = cause;
664
+ return {
665
+ reason: typeof reason === "string" ? reason : "resource-toggle",
666
+ ...event instanceof Event ? { event } : {},
667
+ ...typeof source === "string" ? { source } : {}
668
+ };
669
+ }
1218
670
  const selectExpanded = (state) => state.expandedResourceIds;
1219
671
  /**
1220
672
  * The root's resources as a view shows them: depth first, with collapsed resources' descendants
@@ -1240,16 +692,16 @@ function useResourceExpansion(resourceId) {
1240
692
  const { actions, read, source } = useInteractionRuntime();
1241
693
  const expanded = useStateSelector(source, (state) => state.expandedResourceIds.includes(resourceId));
1242
694
  return useMemo(() => {
1243
- const set = (next) => {
695
+ const set = (next, cause) => {
1244
696
  const current = read().expandedResourceIds;
1245
697
  if (current.includes(resourceId) === next) return;
1246
- actions.setExpandedResourceIds(next ? [...current, resourceId] : current.filter((id) => id !== resourceId));
698
+ actions.setExpandedResourceIds(next ? [...current, resourceId] : current.filter((id) => id !== resourceId), commandOf(cause));
1247
699
  };
1248
700
  return Object.freeze({
1249
- collapse: () => set(false),
1250
- expand: () => set(true),
701
+ collapse: (cause) => set(false, cause),
702
+ expand: (cause) => set(true, cause),
1251
703
  expanded,
1252
- toggle: () => set(!read().expandedResourceIds.includes(resourceId))
704
+ toggle: (cause) => set(!read().expandedResourceIds.includes(resourceId), cause)
1253
705
  });
1254
706
  }, [
1255
707
  actions,
@@ -1258,31 +710,94 @@ function useResourceExpansion(resourceId) {
1258
710
  resourceId
1259
711
  ]);
1260
712
  }
1261
- //#endregion
1262
- //#region src/use-now.ts
1263
- const systemClock$1 = createSystemClock();
713
+ // src/status.ts
714
+ /** The nearest root's events, pending changes included, for hooks that work in any factory. */
715
+ const CalendarEventsContext = createContext(null);
716
+ const systemClock = createSystemClock();
717
+ /** How often the clock is sampled between changes, in case it jumps. */
718
+ const SAMPLE_MS = 6e4;
719
+ const serverSnapshot$2 = () => null;
720
+ const subscribeToNothing$1 = () => () => void 0;
721
+ function sameInstant(left, right) {
722
+ return left === right || left !== null && right !== null && left.equals(right);
723
+ }
724
+ function sameStatus(left, right) {
725
+ const [a, b] = [left.availability, right.availability];
726
+ const [c, d] = [left.busy, right.busy];
727
+ 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));
728
+ }
729
+ /**
730
+ * The status on the clock: it samples when the status next changes, and every minute in case the
731
+ * clock jumps, and tells subscribers only when the status differs.
732
+ */
733
+ function createStatusClock(source, compute) {
734
+ const clock = source?.clock ?? systemClock;
735
+ let current;
736
+ return {
737
+ getSnapshot: () => current ??= compute(clock.instant()),
738
+ subscribe: (onChange) => {
739
+ let timer;
740
+ const sample = () => {
741
+ const now = clock.instant();
742
+ const next = compute(now);
743
+ if (current === void 0 || !sameStatus(current, next)) {
744
+ current = next;
745
+ onChange();
746
+ }
747
+ const until = next.changesAt === null ? SAMPLE_MS : now.until(next.changesAt).total("milliseconds");
748
+ timer = setTimeout(sample, Math.max(0, Math.min(SAMPLE_MS, until)));
749
+ };
750
+ sample();
751
+ return () => clearTimeout(timer);
752
+ }
753
+ };
754
+ }
755
+ /**
756
+ * Whether a resource is within its working hours and whether its events occupy it, `at` an
757
+ * instant or now on the calendar's clock; see `resourceStatusAt`. Without `resourceId` it is the
758
+ * calendar's hours and every event. All-day and floating events count on the display time zone,
759
+ * as the views show them. On the clock it re-renders only when the status changes, and is `null`
760
+ * while server rendering unless the calendar fixes `now`. A `null` resource turns it off, such as
761
+ * for the Unassigned column, with nothing computed or scheduled.
762
+ */
763
+ /** The root's events, pending changes included, for hooks that work in any factory. */
764
+ function useCalendarEvents() {
765
+ const events = useContext(CalendarEventsContext);
766
+ if (events === null) throw new Error("calendar-hook-outside-root");
767
+ return events;
768
+ }
769
+ function useResourceStatus(resourceId, at) {
770
+ const availability = useCalendarAvailability();
771
+ const events = useCalendarEvents();
772
+ const source = useContext(CalendarNowSourceContext);
773
+ const fixed = at ?? source?.now;
774
+ const { timeZone } = availability;
775
+ const compute = useCallback((instant) => resourceStatusAt(availability, events, instant, {
776
+ resourceId: resourceId ?? void 0,
777
+ timeZone
778
+ }), [
779
+ availability,
780
+ events,
781
+ resourceId,
782
+ timeZone
783
+ ]);
784
+ const off = resourceId === null;
785
+ const onClock = fixed === void 0 && !off;
786
+ const store = useMemo(() => onClock ? createStatusClock(source, compute) : null, [
787
+ compute,
788
+ onClock,
789
+ source
790
+ ]);
791
+ const sampled = useSyncExternalStore(store?.subscribe ?? subscribeToNothing$1, store?.getSnapshot ?? serverSnapshot$2, serverSnapshot$2);
792
+ const pinnedAt = off ? void 0 : fixed?.epochNanoseconds;
793
+ return useMemo(() => pinnedAt === void 0 ? null : compute(Temporal.Instant.fromEpochNanoseconds(pinnedAt)), [compute, pinnedAt]) ?? sampled;
794
+ }
795
+ // src/use-now.ts
1264
796
  const serverSnapshot$1 = () => null;
1265
797
  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
798
  /** Samples `source`; `null` while server rendering and hydrating unless `now` is fixed. */
1284
799
  function useNowFrom(source, intervalMs) {
1285
- const clock = source?.clock ?? systemClock$1;
800
+ const clock = clockOf(source);
1286
801
  const ticker = useMemo(() => createClockTicker(clock, intervalMs), [clock, intervalMs]);
1287
802
  const fixed = source?.now;
1288
803
  const sampled = useSyncExternalStore(fixed === void 0 ? ticker.subscribe : subscribeToNothing, ticker.getSnapshot, serverSnapshot$1);
@@ -1295,163 +810,23 @@ function useNowFrom(source, intervalMs) {
1295
810
  function useNow({ intervalMs = 6e4 } = {}) {
1296
811
  return useNowFrom(useContext(CalendarNowSourceContext), intervalMs);
1297
812
  }
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
- }
813
+ // src/root.ts
814
+ /**
815
+ * The React adapter of the calendar kernel: it creates the root's runtime once, feeds it each
816
+ * render's props and what it subscribes to, runs the runtime's effects at their moments, and
817
+ * hands the derived model to the same contexts views and hooks always read.
818
+ */
1433
819
  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 }) {
820
+ const runtimeConfig = {
821
+ eventAdapter: config.eventAdapter,
822
+ invalidEventPolicy: config.invalidEventPolicy,
823
+ views: config.views
824
+ };
825
+ return function Root({ allowAgentDelete, anchorDate, annotationSources, annotations, availability, children, clock, defaultAnchorDate, defaultExpandedResourceIds, defaultFocus, defaultSelection, defaultTimeZone, defaultView, direction, disambiguation, events, expandedResourceIds, focus, formatAgentEventLabel, id, label, locale, now, onAnchorDateChange, onDiagnosticsChange, onEventChange, onEventChangeResult, onExpandedResourceIdsChange, onFocusChange, onSelectionChange, onTimeZoneChange, onViewChange, onVisibleRangeChange, policies, resources, secondaryTimeZones, selection, store, timeZone, view, viewOptions, weekRules }) {
1437
826
  const reactId = useId();
1438
827
  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
- }, {
828
+ const [runtime] = useState(() => createCalendarRuntime(runtimeConfig));
829
+ const connection = runtime.connect({
1455
830
  controlled: {
1456
831
  anchorDate,
1457
832
  expandedResourceIds,
@@ -1460,6 +835,38 @@ function createCalendarRoot(config, contexts) {
1460
835
  timeZone,
1461
836
  view
1462
837
  },
838
+ defaults: () => resolveCalendarStoreDefaults({
839
+ anchorDate,
840
+ defaultAnchorDate,
841
+ defaultExpandedResourceIds,
842
+ defaultFocus,
843
+ defaultSelection,
844
+ defaultTimeZone,
845
+ defaultView,
846
+ timeZone,
847
+ view
848
+ }, config.views),
849
+ store
850
+ });
851
+ const { binding, source } = connection;
852
+ const state = useSyncExternalStore(source.subscribe, source.getSnapshot, source.getSnapshot);
853
+ const { overlay } = runtime;
854
+ const overlaid = useSyncExternalStore(overlay.subscribe, overlay.getSnapshot, overlay.getSnapshot);
855
+ const resolvedEvents = useEventInput(events);
856
+ const instant = useNowFrom({
857
+ clock,
858
+ now
859
+ }, TODAY_SAMPLE_INTERVAL_MS);
860
+ const inputs = {
861
+ allowAgentDelete,
862
+ annotationSources,
863
+ annotations,
864
+ availability,
865
+ clock,
866
+ connection,
867
+ direction,
868
+ disambiguation,
869
+ events: resolvedEvents,
1463
870
  handlers: {
1464
871
  onAnchorDateChange,
1465
872
  onExpandedResourceIdsChange,
@@ -1467,209 +874,51 @@ function createCalendarRoot(config, contexts) {
1467
874
  onSelectionChange,
1468
875
  onTimeZoneChange,
1469
876
  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,
877
+ },
878
+ instant,
879
+ locale,
880
+ now,
1609
881
  onDiagnosticsChange,
1610
882
  onEventChange,
1611
883
  onEventChangeResult,
1612
884
  onVisibleRangeChange,
885
+ overlay: overlaid,
1613
886
  policies,
1614
- resourceTree,
1615
- viewOptions: viewOverrides
887
+ resources,
888
+ secondaryTimeZones,
889
+ state,
890
+ viewOptions,
891
+ weekRules
1616
892
  };
1617
- const committed = useRef(committedInputs);
1618
- useInsertionEffect(() => {
1619
- committed.current = committedInputs;
893
+ const model = runtime.derive(inputs);
894
+ useInsertionEffect(() => runtime.commit(model, inputs));
895
+ useInsertionEffect(() => binding.attach(), [binding]);
896
+ const { diagnostics, eventSnapshot, visibleRange } = model;
897
+ useLayoutEffect(() => runtime.reconcile(eventSnapshot), [eventSnapshot, runtime]);
898
+ useEffect(() => runtime.reportDiagnostics(diagnostics), [diagnostics, runtime]);
899
+ useEffect(() => runtime.reportVisibleRange(visibleRange), [runtime, visibleRange]);
900
+ const handle = usePrimitive(config.primitive, {
901
+ allowAgentDelete,
902
+ formatAgentEventLabel,
903
+ runtime,
904
+ ...state
1620
905
  });
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
906
  const [refs] = useState(() => Object.freeze({
1656
907
  frame: createRef(),
1657
908
  title: createRef(),
1658
909
  toolbar: createRef(),
1659
910
  viewport: createRef()
1660
911
  }));
1661
- const ids = useMemo(() => Object.freeze({
1662
- frame: `${instanceId}-frame`,
1663
- title: `${instanceId}-title`,
1664
- viewport: `${instanceId}-viewport`
1665
- }), [instanceId]);
912
+ const ids = useMemo(() => createCalendarPartIds(instanceId), [instanceId]);
913
+ const { activeDefinition, environment, resources: stableResources, visibleEvents } = model;
1666
914
  const meta = useMemo(() => Object.freeze({
1667
915
  activeView: activeDefinition,
1668
916
  diagnostics,
1669
917
  environment,
1670
- eventSnapshot: visibleSnapshot,
918
+ eventSnapshot: visibleEvents,
1671
919
  ids,
1672
920
  instanceId,
921
+ label,
1673
922
  refs,
1674
923
  resources: stableResources,
1675
924
  views: config.views
@@ -1677,17 +926,17 @@ function createCalendarRoot(config, contexts) {
1677
926
  activeDefinition,
1678
927
  diagnostics,
1679
928
  environment,
1680
- visibleSnapshot,
929
+ visibleEvents,
1681
930
  ids,
1682
931
  instanceId,
932
+ label,
1683
933
  refs,
1684
934
  stableResources
1685
935
  ]);
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))))))))))));
936
+ return createElement(CalendarNowSourceContext, { value: environment }, createElement(contexts.source, { value: source }, createElement(contexts.actions, { value: model.actions }, createElement(contexts.changes, { value: runtime.pendingChanges }, createElement(contexts.meta, { value: meta }, createElement(contexts.state, { value: state }, createElement(contexts.view, { value: model.activeView }, createElement(contexts.handle, { value: handle }, createElement(CalendarResourcesContext, { value: model.resourceTree }, createElement(CalendarAnnotationsContext, { value: model.annotations }, createElement(CalendarAvailabilityContext, { value: model.availability }, createElement(CalendarEventsContext, { value: visibleEvents }, createElement(CalendarInteractionContext, { value: model.interaction }, children)))))))))))));
1687
937
  };
1688
938
  }
1689
- //#endregion
1690
- //#region src/calendar.ts
939
+ // src/calendar.ts
1691
940
  /** `useCalendarPendingChanges` without a selector: the map itself. */
1692
941
  const allChanges = (changes) => changes;
1693
942
  /**
@@ -1707,10 +956,12 @@ function createCalendar() {
1707
956
  names.add(view.name);
1708
957
  }
1709
958
  const contexts = createCalendarContexts();
959
+ const primitive = createCalendarPrimitive({ views });
1710
960
  const { EventPart, ViewSwitcher, ...parts } = createCalendarParts(contexts);
1711
961
  const Root = createCalendarRoot({
1712
962
  eventAdapter: options.eventAdapter,
1713
963
  invalidEventPolicy: options.invalidEventPolicy,
964
+ primitive,
1714
965
  views
1715
966
  }, contexts);
1716
967
  const useCalendarActions = () => useRootContext(contexts.actions);
@@ -1751,8 +1002,132 @@ function createCalendar() {
1751
1002
  });
1752
1003
  };
1753
1004
  }
1754
- //#endregion
1755
- //#region src/history.ts
1005
+ // src/use-stable-value.ts
1006
+ /** Returns the previous value while `isEqual` considers the next one equivalent. */
1007
+ function useStableValue(value, isEqual) {
1008
+ const [stable, setStable] = useState(value);
1009
+ if (stable === value || isEqual(stable, value)) return stable;
1010
+ setStable(() => value);
1011
+ return value;
1012
+ }
1013
+ // src/draft.ts
1014
+ function sameIds(left, right) {
1015
+ return left === right || left !== void 0 && right !== void 0 && sameElements(left, right);
1016
+ }
1017
+ function sameInterval(left, right) {
1018
+ 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();
1019
+ }
1020
+ const nothingBusy = /* @__PURE__ */ new Map();
1021
+ /**
1022
+ * The resources busy during `range`, such as a meeting being placed, with their events; free
1023
+ * ones are absent. It queries the root's events, pending changes included, once per change of
1024
+ * events or range, however many components ask. `exclude` leaves out an event, such as the one
1025
+ * being moved; `null` asks nothing.
1026
+ */
1027
+ function useBusyResources(range, { exclude, resourceIds } = {}) {
1028
+ const events = useCalendarEvents();
1029
+ const { timeZone } = useCalendarAvailability();
1030
+ const stableRange = useStableValue(range, sameInterval);
1031
+ const ids = useStableValue(resourceIds, sameIds);
1032
+ return useMemo(() => stableRange === null ? nothingBusy : busyResources(events, stableRange, {
1033
+ ...exclude == null ? {} : { exclude },
1034
+ ...ids === void 0 ? {} : { resourceIds: ids },
1035
+ timeZone
1036
+ }), [
1037
+ events,
1038
+ exclude,
1039
+ ids,
1040
+ stableRange,
1041
+ timeZone
1042
+ ]);
1043
+ }
1044
+ /** Each draft's busy resources, worked out once for every header that asks. */
1045
+ const draftBusy = /* @__PURE__ */ new WeakMap();
1046
+ function busyFor(draft, events, timeZone) {
1047
+ const cached = draftBusy.get(draft);
1048
+ if (cached?.events === events) return cached.busy;
1049
+ const busy = busyResources(events, draft.proposed, {
1050
+ ...draft.eventId === null ? {} : { exclude: draft.eventId },
1051
+ timeZone
1052
+ });
1053
+ draftBusy.set(draft, {
1054
+ busy,
1055
+ events
1056
+ });
1057
+ return busy;
1058
+ }
1059
+ /** Each keyboard session as a draft, the same object for as long as the session is. */
1060
+ const sessionDrafts = /* @__PURE__ */ new WeakMap();
1061
+ function draftOf(session) {
1062
+ let draft = sessionDrafts.get(session);
1063
+ if (draft === void 0) {
1064
+ draft = Object.freeze({
1065
+ eventId: session.eventId,
1066
+ proposed: session.proposed
1067
+ });
1068
+ sessionDrafts.set(session, draft);
1069
+ }
1070
+ return draft;
1071
+ }
1072
+ /** Subscribes to the keyboard's and the pointer's drafts. */
1073
+ function useDraftSource() {
1074
+ const { keyboard, pointerDraft } = useInteractionRuntime();
1075
+ return useMemo(() => ({
1076
+ getSnapshot: () => {
1077
+ const session = keyboard.grabs.getSnapshot()?.session;
1078
+ return session === void 0 ? pointerDraft.getSnapshot() : draftOf(session);
1079
+ },
1080
+ subscribe: (listener) => {
1081
+ const stops = [keyboard.grabs.subscribe(listener), pointerDraft.subscribe(listener)];
1082
+ return () => {
1083
+ for (const stop of stops) stop();
1084
+ };
1085
+ }
1086
+ }), [keyboard, pointerDraft]);
1087
+ }
1088
+ /** Reports the pointer's draft to the root, for `onPreview` of `useCalendarPointer`. */
1089
+ function useCalendarDraftReporter() {
1090
+ return useInteractionRuntime().pointerDraft.set;
1091
+ }
1092
+ /**
1093
+ * The change being drafted, by pointer or keyboard: the event it changes (`null` when creating)
1094
+ * and where it would land; `null` without one. It changes once a slot step, so pass its
1095
+ * `proposed` to `useBusyResources` for any "who's busy" UI of your own.
1096
+ */
1097
+ function useCalendarDraft() {
1098
+ const source = useDraftSource();
1099
+ return useSyncExternalStore(source.subscribe, source.getSnapshot, () => null);
1100
+ }
1101
+ const noEvents = Object.freeze([]);
1102
+ function sameBusy(left, right) {
1103
+ 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]);
1104
+ }
1105
+ /**
1106
+ * A resource during the draft's time while one is being made, by pointer or keyboard: the busy
1107
+ * events that overlap it (the draft's own event aside; see `isBusy` on the event adapter), and
1108
+ * whether the time falls outside its hours. `null` without a draft, or for a `null` resource.
1109
+ * The draft's busy resources are worked out once a step for every component that asks, and a
1110
+ * component re-renders only when its own resource's answer changes.
1111
+ */
1112
+ function useDraftBusy(resourceId) {
1113
+ const source = useDraftSource();
1114
+ const events = useCalendarEvents();
1115
+ const availability = useCalendarAvailability();
1116
+ const last = useRef(null);
1117
+ const read = () => {
1118
+ const draft = source.getSnapshot();
1119
+ if (draft === null || resourceId === null) return last.current = null;
1120
+ const { timeZone } = availability;
1121
+ const next = {
1122
+ events: busyFor(draft, events, timeZone).get(resourceId) ?? noEvents,
1123
+ outsideHours: !fitsAvailability(draft.proposed, availability.forResource(resourceId), timeZone)
1124
+ };
1125
+ if (!sameBusy(last.current, next)) last.current = next;
1126
+ return last.current;
1127
+ };
1128
+ return useSyncExternalStore(source.subscribe, read, () => null);
1129
+ }
1130
+ // src/history.ts
1756
1131
  /**
1757
1132
  * What the server and hydration read: nothing recorded yet. A plain literal, so a bundler drops
1758
1133
  * it from a calendar that doesn't use the history.
@@ -1861,8 +1236,7 @@ function useCalendarHistory(history, options = {}) {
1861
1236
  canUndo: snapshot.past.length > 0
1862
1237
  }), [commands, snapshot]);
1863
1238
  }
1864
- //#endregion
1865
- //#region src/history-shortcuts.ts
1239
+ // src/history-shortcuts.ts
1866
1240
  const defaultUndo = ["Mod+Z"];
1867
1241
  const defaultRedo = ["Shift+Mod+Z", "Ctrl+Y"];
1868
1242
  const keyboardInput$1 = { input: "keyboard" };
@@ -1965,9 +1339,18 @@ function useCalendarHistoryShortcuts(history, options) {
1965
1339
  pointerDraft
1966
1340
  ]);
1967
1341
  }
1968
- //#endregion
1969
- //#region src/keyboard.ts
1342
+ // src/keyboard.ts
1970
1343
  const DEFAULT_CREATE_DURATION = { hours: 1 };
1344
+ /**
1345
+ * What a key tells the state handlers it changes: its reason, and the key itself, from which the
1346
+ * store works out the source, the keyboard's, or the agent's while an agent's step presses it.
1347
+ */
1348
+ function keyCommand(event) {
1349
+ return {
1350
+ event: event.nativeEvent,
1351
+ reason: "keyboard-navigation"
1352
+ };
1353
+ }
1971
1354
  const keyboardInput = Object.freeze({ input: "keyboard" });
1972
1355
  const navigationKeys = {
1973
1356
  ArrowDown: "down",
@@ -2004,32 +1387,35 @@ function createKeyboardHandlers({ actions, announcements, isReadOnly, keyboard,
2004
1387
  timeZone: view().environment.timeZone
2005
1388
  };
2006
1389
  }
2007
- /** Navigates the view by whole ranges until it shows `date`. */
2008
- function reveal(date) {
1390
+ /**
1391
+ * Navigates the view by whole ranges until it shows `date`. `command` carries the key, or the
1392
+ * focus change, behind it, so the state handlers hear a person's keys as the keyboard's.
1393
+ */
1394
+ function reveal(date, command) {
2009
1395
  const { definition, environment, options, range } = view();
2010
1396
  if (plainDateIntervalContains(range, date)) return;
2011
1397
  const { anchorDate } = read();
2012
- actions.setAnchorDate(anchorShowingDate(definition.strategy, anchorDate, date, environment, options));
1398
+ actions.setAnchorDate(anchorShowingDate(definition.strategy, anchorDate, date, environment, options), command);
2013
1399
  }
2014
1400
  /** Moves the calendar's focus and, once the view renders it, DOM focus. */
2015
- function moveFocus(focus) {
1401
+ function moveFocus(focus, command) {
2016
1402
  if (sameFocus(focus, read().focus)) {
2017
1403
  roving.focusTabStop("now");
2018
1404
  return;
2019
1405
  }
2020
1406
  roving.focusTabStop("after-update");
2021
- actions.setFocus(focus);
2022
- if (focus !== null) reveal(focus.date);
1407
+ actions.setFocus(focus, command);
1408
+ if (focus !== null) reveal(focus.date, command);
2023
1409
  }
2024
- function apply(result) {
1410
+ function apply(result, command) {
2025
1411
  if (result === null) return false;
2026
- if ("focus" in result) moveFocus(result.focus);
1412
+ if ("focus" in result) moveFocus(result.focus, command);
2027
1413
  else {
2028
1414
  const { definition, options } = view();
2029
1415
  roving.focusTabStop("after-update");
2030
1416
  if (result.page < 0) roving.enterFromEnd();
2031
- actions.setAnchorDate(definition.strategy.navigate(read().anchorDate, result.page, options));
2032
- actions.setFocus(null);
1417
+ actions.setAnchorDate(definition.strategy.navigate(read().anchorDate, result.page, options), command);
1418
+ actions.setFocus(null, command);
2033
1419
  }
2034
1420
  return true;
2035
1421
  }
@@ -2048,7 +1434,7 @@ function createKeyboardHandlers({ actions, announcements, isReadOnly, keyboard,
2048
1434
  /** What the root's policies would say to committing `session` now, as its preview shows. */
2049
1435
  function checkOf(session) {
2050
1436
  const proposal = keyboardSessionProposal(session);
2051
- return proposal === null ? null : actions.checkEventChange(proposal);
1437
+ return proposal === null ? null : actions.checkEventChange(proposal, keyboardInput);
2052
1438
  }
2053
1439
  /**
2054
1440
  * Follows the grabbed event into the cursor's date and resource, or a create's cell. A move out
@@ -2081,7 +1467,7 @@ function createKeyboardHandlers({ actions, announcements, isReadOnly, keyboard,
2081
1467
  }
2082
1468
  return session;
2083
1469
  }
2084
- function grab(focus, cause) {
1470
+ function grab(focus, cause, command) {
2085
1471
  if (focus.kind !== "event") {
2086
1472
  if (cause !== "create") return false;
2087
1473
  const session = startCreate(focus);
@@ -2093,7 +1479,7 @@ function createKeyboardHandlers({ actions, announcements, isReadOnly, keyboard,
2093
1479
  session
2094
1480
  };
2095
1481
  keyboard.set(next);
2096
- moveFocus(focusOfSession(session));
1482
+ moveFocus(focusOfSession(session), command);
2097
1483
  announce(next, { phase: "start" });
2098
1484
  return true;
2099
1485
  }
@@ -2123,8 +1509,8 @@ function createKeyboardHandlers({ actions, announcements, isReadOnly, keyboard,
2123
1509
  announce(next, { phase: "start" });
2124
1510
  return true;
2125
1511
  }
2126
- function step(current, command) {
2127
- const cursor = cellOf(navigate(command, current.session.cursor));
1512
+ function step(current, key, command) {
1513
+ const cursor = cellOf(navigate(key, current.session.cursor));
2128
1514
  if (cursor === null) return;
2129
1515
  const session = moveKeyboardCursor(current.session, cursor, interactionOptions());
2130
1516
  if (session === current.session) return;
@@ -2134,11 +1520,11 @@ function createKeyboardHandlers({ actions, announcements, isReadOnly, keyboard,
2134
1520
  session
2135
1521
  };
2136
1522
  keyboard.set(next);
2137
- moveFocus(focusOfSession(session));
1523
+ moveFocus(focusOfSession(session), command);
2138
1524
  announce(next, { phase: "step" });
2139
1525
  }
2140
1526
  /** Grabs the other edge, starting the resize over from the event as it was. */
2141
- function switchEdge(current) {
1527
+ function switchEdge(current, command) {
2142
1528
  const { cell, event, session } = current;
2143
1529
  if (event === null || !session.cause.startsWith("resize")) return;
2144
1530
  const cause = session.cause === "resize-end" ? "resize-start" : "resize-end";
@@ -2153,18 +1539,18 @@ function createKeyboardHandlers({ actions, announcements, isReadOnly, keyboard,
2153
1539
  session: restarted
2154
1540
  };
2155
1541
  keyboard.set(next);
2156
- moveFocus(focusOfSession(restarted));
1542
+ moveFocus(focusOfSession(restarted), command);
2157
1543
  announce(next, { phase: "start" });
2158
1544
  }
2159
- function cancel(current) {
1545
+ function cancel(current, command) {
2160
1546
  keyboard.set(null);
2161
- moveFocus(current.origin);
1547
+ moveFocus(current.origin, command);
2162
1548
  announce(current, { phase: "cancel" });
2163
1549
  }
2164
- function commit(current) {
1550
+ function commit(current, command) {
2165
1551
  const proposal = keyboardSessionProposal(current.session);
2166
1552
  if (proposal === null) {
2167
- cancel(current);
1553
+ cancel(current, command);
2168
1554
  return;
2169
1555
  }
2170
1556
  keyboard.set(null);
@@ -2181,7 +1567,7 @@ function createKeyboardHandlers({ actions, announcements, isReadOnly, keyboard,
2181
1567
  eventId,
2182
1568
  kind: "event",
2183
1569
  resourceId: resourceOn(proposed, cursor.resourceId)
2184
- });
1570
+ }, command);
2185
1571
  }
2186
1572
  announce(current, {
2187
1573
  phase: "commit",
@@ -2189,7 +1575,7 @@ function createKeyboardHandlers({ actions, announcements, isReadOnly, keyboard,
2189
1575
  warnings: result.change.warnings
2190
1576
  });
2191
1577
  } else {
2192
- if (owned()) moveFocus(current.origin);
1578
+ if (owned()) moveFocus(current.origin, command);
2193
1579
  announce(current, {
2194
1580
  phase: "reject",
2195
1581
  reason: result.reason,
@@ -2219,36 +1605,38 @@ function createKeyboardHandlers({ actions, announcements, isReadOnly, keyboard,
2219
1605
  return booked.find((id) => visible.some((row) => row.id === id));
2220
1606
  }
2221
1607
  function onGrabbedKey(current, event) {
2222
- const command = navigationKeys[event.key];
2223
- if (command !== void 0) {
2224
- step(current, command);
1608
+ const key = navigationKeys[event.key];
1609
+ const command = keyCommand(event);
1610
+ if (key !== void 0) {
1611
+ step(current, key, command);
2225
1612
  return true;
2226
1613
  }
2227
1614
  switch (event.key) {
2228
1615
  case "Enter":
2229
- commit(current);
1616
+ commit(current, command);
2230
1617
  return true;
2231
1618
  case " ":
2232
- if (event.shiftKey) switchEdge(current);
2233
- else commit(current);
1619
+ if (event.shiftKey) switchEdge(current, command);
1620
+ else commit(current, command);
2234
1621
  return true;
2235
1622
  case "Escape":
2236
- cancel(current);
1623
+ cancel(current, command);
2237
1624
  return true;
2238
1625
  case "Tab":
2239
- cancel(current);
1626
+ cancel(current, command);
2240
1627
  return false;
2241
1628
  default: return false;
2242
1629
  }
2243
1630
  }
2244
1631
  function onIdleKey(focus, event) {
2245
- const command = navigationKeys[event.key];
2246
- if (command !== void 0) return !event.shiftKey && apply(navigate(command, focus));
1632
+ const key = navigationKeys[event.key];
1633
+ const command = keyCommand(event);
1634
+ if (key !== void 0) return !event.shiftKey && apply(navigate(key, focus), command);
2247
1635
  if (focus === null) return false;
2248
1636
  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");
1637
+ case "Enter": return focus.kind !== "event" && !event.shiftKey && apply(navigate("enter", focus), command);
1638
+ case "Escape": return focus.kind === "event" && apply(navigate("exit", focus), command);
1639
+ case " ": return !isReadOnly && grab(focus, focus.kind !== "event" ? "create" : event.shiftKey ? "resize-end" : "move", command);
2252
1640
  default: return false;
2253
1641
  }
2254
1642
  }
@@ -2258,9 +1646,13 @@ function createKeyboardHandlers({ actions, announcements, isReadOnly, keyboard,
2258
1646
  const region = event.currentTarget;
2259
1647
  const next = event.relatedTarget;
2260
1648
  if (next !== null && region.contains(next)) return;
1649
+ const command = {
1650
+ event: event.nativeEvent,
1651
+ reason: "focus-change"
1652
+ };
2261
1653
  setTimeout(() => {
2262
1654
  const current = keyboard.get();
2263
- if (current !== null && !region.contains(document.activeElement)) cancel(current);
1655
+ if (current !== null && !region.contains(document.activeElement)) cancel(current, command);
2264
1656
  });
2265
1657
  },
2266
1658
  onKeyDown(event) {
@@ -2311,8 +1703,7 @@ const selectSession = (session) => session;
2311
1703
  function useCalendarInteraction(selector = selectSession, options) {
2312
1704
  return useStateSelector(useInteractionRuntime().keyboard.grabs, (grab) => selector(grab?.session ?? null, grab?.check ?? null), options);
2313
1705
  }
2314
- //#endregion
2315
- //#region src/selectors.ts
1706
+ // src/selectors.ts
2316
1707
  /**
2317
1708
  * Selects from the calendar's focus for a view's item, such as whether a slot cursor sits on this
2318
1709
  * column. A component re-renders only when its result changes.
@@ -2327,8 +1718,7 @@ function useCalendarFocus(selector, options) {
2327
1718
  function useCalendarSelection(selector, options) {
2328
1719
  return useStateSelector(useInteractionRuntime().source, (state) => selector(state.selection), options);
2329
1720
  }
2330
- //#endregion
2331
- //#region src/requests.ts
1721
+ // src/requests.ts
2332
1722
  /**
2333
1723
  * Calls `listener` whenever something asks the calendar for an anchor date: Previous, Next,
2334
1724
  * Today, keys paging past the view, or `setAnchorDate`, even a date that is already the anchor.
@@ -2349,5 +1739,13 @@ function useAnchorDateRequests(listener) {
2349
1739
  latest.current(date, rangeOf(date));
2350
1740
  }), [rangeOf, requests]);
2351
1741
  }
2352
- //#endregion
1742
+ // src/views.ts
1743
+ function defineCalendarView(view) {
1744
+ return Object.freeze({
1745
+ defaultOptions: view.defaultOptions,
1746
+ name: view.name,
1747
+ Renderer: view.Renderer,
1748
+ strategy: view.strategy
1749
+ });
1750
+ }
2353
1751
  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 };