@moltenship/calendar-react 1.0.0-rc.2 → 2.0.0

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 { closedDates, projectTimeGridAnnotations, projectTimeGridAvailability, projectTimelineAvailability, resourceStatusAt, 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 { createSystemClock, plainDateIntervalContains } from "@moltenship/calendar-temporal";
5
- //#region src/annotations.ts
4
+ import { TODAY_SAMPLE_INTERVAL_MS, attachCalendarHistoryShortcuts, bindCalendarHistory, calendarFocusKey, calendarViewEntry, clockOf, createAnnouncerLiveText, createBusyResourcesQuery, createCalendarKeyboard, createCalendarPartIds, createCalendarPrimitive, createCalendarRuntime, createCalendarStore, createCalendarViewRuntime, createClockTicker, createDraftBusyQuery, createResourceExpansionCommands, createResourceStatusClock, focusRovingTarget, resolveCalendarStoreDefaults, sameElements, subscribeAnchorDateRequests } from "@moltenship/calendar-primitives";
5
+ import { usePart, usePrimitive } from "@ui-sdk/react/primitive";
6
+ import { attachCalendarPointer } from "@moltenship/calendar-dnd";
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,13 +33,7 @@ function useTimeGridAnnotations(columns, { layout, maxLanes, minGap, minHeight }
31
33
  sources
32
34
  ]);
33
35
  }
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
- });
36
+ // src/interaction.ts
41
37
  const CalendarInteractionContext = createContext(null);
42
38
  const CalendarViewRuntimeContext = createContext(null);
43
39
  function useInteractionRuntime() {
@@ -50,56 +46,7 @@ function useViewRuntime() {
50
46
  if (runtime === null) throw new Error("calendar-view-hook-outside-active-view");
51
47
  return runtime;
52
48
  }
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
- }
49
+ // src/announcer.ts
103
50
  /** Hidden from view but read by screen readers. */
104
51
  const visuallyHidden = {
105
52
  border: 0,
@@ -122,14 +69,9 @@ function Announcer({ messages, style, ...props }) {
122
69
  useInsertionEffect(() => {
123
70
  latest.current = messages;
124
71
  });
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]);
72
+ const [live] = useState(createAnnouncerLiveText);
73
+ const spoken = useSyncExternalStore(live.subscribe, live.getSnapshot, live.getServerSnapshot);
74
+ useLayoutEffect(() => announcements.mount(() => latest.current, live.speak), [announcements, live]);
133
75
  return createElement("div", {
134
76
  "aria-atomic": true,
135
77
  "aria-live": "polite",
@@ -140,7 +82,7 @@ function Announcer({ messages, style, ...props }) {
140
82
  ...visuallyHidden,
141
83
  ...style
142
84
  }
143
- }, spoken.repeat ? `${spoken.text}\u00a0` : spoken.text);
85
+ }, spoken);
144
86
  }
145
87
  /**
146
88
  * The announcer views pass to the pointer layer (`useCalendarPointer({ announcer })`), so pointer
@@ -149,8 +91,7 @@ function Announcer({ messages, style, ...props }) {
149
91
  function useCalendarAnnouncer() {
150
92
  return useInteractionRuntime().announcements.announcer;
151
93
  }
152
- //#endregion
153
- //#region src/availability.ts
94
+ // src/availability.ts
154
95
  /** The nearest root's working hours, shared by every factory so the hooks work in any view. */
155
96
  const CalendarAvailabilityContext = createContext(null);
156
97
  /** The root's working hours: the calendar's, and each resource's on its time zone. */
@@ -190,13 +131,13 @@ function useClosedDates(range, resourceId) {
190
131
  timeZone
191
132
  ]);
192
133
  }
193
- //#endregion
194
- //#region src/context.ts
134
+ // src/context.ts
195
135
  /** Each factory owns its contexts, so its hooks resolve its own root inside another calendar. */
196
136
  function createCalendarContexts() {
197
137
  return Object.freeze({
198
138
  actions: createContext(null),
199
139
  changes: createContext(null),
140
+ handle: createContext(null),
200
141
  meta: createContext(null),
201
142
  source: createContext(null),
202
143
  state: createContext(null),
@@ -215,288 +156,7 @@ function useActiveViewContext(context) {
215
156
  if (view === void 0) throw new Error("calendar-hook-outside-root");
216
157
  return view;
217
158
  }
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
- }
159
+ // src/state-binding.ts
500
160
  /** Subscribes once per source; inline selectors and `isEqual` callbacks are read per render. */
501
161
  function useStateSelector(source, selector, { isEqual = Object.is } = {}) {
502
162
  const committed = useRef(null);
@@ -527,205 +187,15 @@ function useStateSelector(source, selector, { isEqual = Object.is } = {}) {
527
187
  });
528
188
  return selected;
529
189
  }
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
- }
190
+ // src/roving-focus.ts
704
191
  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
192
  /**
723
193
  * Keeps the active view's roving store on the root's focus. Rendered after the view, so the
724
194
  * elements of a commit are registered before focus moves to one of them.
725
195
  */
726
196
  function RovingFocusSync({ roving, source, view }) {
727
197
  const focus = useStateSelector(source, selectFocus);
728
- const entry = useMemo(() => viewEntry(view), [view]);
198
+ const entry = useMemo(() => calendarViewEntry(view), [view]);
729
199
  useLayoutEffect(() => roving.update(focus, entry), [
730
200
  entry,
731
201
  focus,
@@ -733,15 +203,6 @@ function RovingFocusSync({ roving, source, view }) {
733
203
  ]);
734
204
  return null;
735
205
  }
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
206
  /**
746
207
  * Props for one focusable element of a view: a day cell, a slot, or an event. The view's one tab
747
208
  * stop gets `tabIndex={0}`; focusing an element makes it the calendar's focus, and keyboard
@@ -757,7 +218,7 @@ function useRovingFocus(target, { days = 1 } = {}) {
757
218
  });
758
219
  const isTabStop = () => roving.isTabStop(target, days);
759
220
  const tabStop = useSyncExternalStore(roving.subscribe, isTabStop, isTabStop);
760
- const key = focusKey(target);
221
+ const key = calendarFocusKey(target);
761
222
  const ref = useCallback((element) => element === null ? void 0 : roving.register(element, latest.current, days), [
762
223
  days,
763
224
  key,
@@ -766,9 +227,10 @@ function useRovingFocus(target, { days = 1 } = {}) {
766
227
  return {
767
228
  onFocus: useCallback((event) => {
768
229
  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);
230
+ focusRovingTarget({
231
+ actions,
232
+ read
233
+ }, latest.current, days, event.nativeEvent);
772
234
  }, [
773
235
  actions,
774
236
  days,
@@ -778,17 +240,30 @@ function useRovingFocus(target, { days = 1 } = {}) {
778
240
  tabIndex: tabStop ? 0 : -1
779
241
  };
780
242
  }
781
- //#endregion
782
- //#region src/parts.ts
243
+ // src/parts.ts
783
244
  const selectView = (state) => state.view;
245
+ /**
246
+ * The elements of the copies of a part still mounted, by the root's ref they share. An application
247
+ * may render two copies of a part: the ref holds the latest one, and a copy that unmounts gives it
248
+ * back to the other instead of emptying it.
249
+ */
250
+ const mountedByRef = /* @__PURE__ */ new WeakMap();
784
251
  function useComposedRef(internalRef, externalRef) {
785
252
  return useCallback((node) => {
786
- internalRef.current = node;
253
+ if (node !== null) {
254
+ const mounted = mountedByRef.get(internalRef) ?? [];
255
+ mountedByRef.set(internalRef, mounted);
256
+ mounted.push(node);
257
+ internalRef.current = node;
258
+ }
787
259
  const externalCleanup = typeof externalRef === "function" ? externalRef(node) : void 0;
788
260
  if (externalRef !== null && externalRef !== void 0 && typeof externalRef !== "function") externalRef.current = node;
789
261
  if (node === null) return void 0;
790
262
  return () => {
791
- internalRef.current = null;
263
+ const mounted = mountedByRef.get(internalRef) ?? [];
264
+ const index = mounted.lastIndexOf(node);
265
+ if (index !== -1) mounted.splice(index, 1);
266
+ internalRef.current = mounted.at(-1) ?? null;
792
267
  if (typeof externalRef === "function") {
793
268
  if (typeof externalCleanup === "function") externalCleanup();
794
269
  else externalRef(null);
@@ -799,87 +274,96 @@ function useComposedRef(internalRef, externalRef) {
799
274
  /** Builds the compound parts that read one factory's root. */
800
275
  function createCalendarParts(contexts) {
801
276
  function Frame({ children, ref, ...props }) {
277
+ const handle = useRootContext(contexts.handle);
802
278
  const meta = useRootContext(contexts.meta);
803
279
  const composedRef = useComposedRef(meta.refs.frame, ref);
804
- return createElement("section", {
805
- "aria-labelledby": meta.ids.title,
280
+ const elementProps = {
281
+ ...meta.label === void 0 ? { "aria-labelledby": meta.ids.title } : { "aria-label": meta.label },
806
282
  ...props,
283
+ children,
807
284
  "data-calendar-instance": meta.instanceId,
808
285
  "data-calendar-part": "frame",
809
286
  id: meta.ids.frame,
810
287
  ref: composedRef
811
- }, children);
288
+ };
289
+ return usePart(handle, "root", {}, elementProps, "section");
812
290
  }
813
291
  function Toolbar({ children, ref, ...props }) {
292
+ const handle = useRootContext(contexts.handle);
814
293
  const composedRef = useComposedRef(useRootContext(contexts.meta).refs.toolbar, ref);
815
- return createElement("header", {
294
+ return usePart(handle, "toolbar", {}, {
816
295
  ...props,
296
+ children,
817
297
  "data-calendar-part": "toolbar",
818
298
  ref: composedRef
819
- }, children);
299
+ }, "header");
820
300
  }
821
301
  function Viewport({ children, ref, ...props }) {
302
+ const handle = useRootContext(contexts.handle);
822
303
  const meta = useRootContext(contexts.meta);
823
304
  const composedRef = useComposedRef(meta.refs.viewport, ref);
824
- return createElement("div", {
305
+ return usePart(handle, "viewport", {}, {
825
306
  ...props,
307
+ children,
826
308
  "data-calendar-part": "viewport",
827
309
  id: meta.ids.viewport,
828
310
  ref: composedRef
829
- }, children);
311
+ }, "div");
830
312
  }
831
313
  function Title({ children, ref, ...props }) {
314
+ const handle = useRootContext(contexts.handle);
832
315
  const meta = useRootContext(contexts.meta);
833
316
  const activeView = useActiveViewContext(contexts.view);
834
317
  const composedRef = useComposedRef(meta.refs.title, ref);
835
318
  const title = useMemo(() => activeView?.definition.strategy.getTitle(activeView.range, activeView.environment, activeView.options) ?? "", [activeView]);
836
- return createElement("span", {
319
+ return usePart(handle, "title", {}, {
837
320
  ...props,
321
+ children: children ?? title,
838
322
  "data-calendar-part": "title",
839
323
  id: meta.ids.title,
840
324
  ref: composedRef
841
- }, children ?? title);
325
+ }, "span");
842
326
  }
843
- function createTrigger(part, command) {
844
- return function Trigger({ children, disabled, ref, type = "button", ...props }) {
845
- const actions = useRootContext(contexts.actions);
327
+ function createTrigger(part, requiresView) {
328
+ return function Trigger({ children, disabled, type = "button", ...props }) {
329
+ const handle = useRootContext(contexts.handle);
846
330
  const meta = useRootContext(contexts.meta);
847
- const requiresView = command !== "navigateToday";
848
- return createElement("button", {
331
+ const elementProps = {
849
332
  ...props,
850
333
  "aria-controls": props["aria-controls"] ?? meta.ids.viewport,
334
+ children,
851
335
  "data-calendar-part": part,
852
336
  disabled: disabled ?? (requiresView && meta.activeView === void 0),
853
- onClick: (event) => {
854
- props.onClick?.(event);
855
- if (!event.defaultPrevented) actions[command]();
856
- },
857
- ref,
858
337
  type
859
- }, children);
338
+ };
339
+ return usePart(handle, part, {}, elementProps, "button");
860
340
  };
861
341
  }
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);
342
+ const PreviousTrigger = createTrigger("previous-trigger", true);
343
+ const NextTrigger = createTrigger("next-trigger", true);
344
+ const TodayTrigger = createTrigger("today-trigger", false);
345
+ function ViewSwitcher({ getViewLabel, onChange, ...props }) {
346
+ const handle = useRootContext(contexts.handle);
867
347
  const meta = useRootContext(contexts.meta);
868
348
  const view = useStateSelector(useRootContext(contexts.source), selectView);
869
- return createElement("select", {
349
+ const elementProps = {
870
350
  ...props,
351
+ children: meta.views.map(({ name }) => createElement("option", {
352
+ key: name,
353
+ value: name
354
+ }, getViewLabel(name))),
871
355
  "data-calendar-part": "view-switcher",
872
356
  onChange: (event) => {
873
357
  onChange?.(event);
874
- const next = event.currentTarget.value;
875
- if (!event.defaultPrevented && meta.views.some((candidate) => candidate.name === next)) actions.setView(next);
358
+ if (event.defaultPrevented) return;
359
+ handle.api.selectView(event.currentTarget.value, {
360
+ event: event.nativeEvent,
361
+ reason: "input-change"
362
+ });
876
363
  },
877
- ref,
878
364
  value: view
879
- }, meta.views.map(({ name }) => createElement("option", {
880
- key: name,
881
- value: name
882
- }, getViewLabel(name))));
365
+ };
366
+ return usePart(handle, "view-switcher", {}, elementProps, "select");
883
367
  }
884
368
  function ActiveView({ fallback = null }) {
885
369
  const actions = useRootContext(contexts.actions);
@@ -889,11 +373,7 @@ function createCalendarParts(contexts) {
889
373
  useInsertionEffect(() => {
890
374
  latest.current = activeView;
891
375
  });
892
- const [roving] = useState(() => createRovingFocusStore(viewEntry(activeView)));
893
- const runtime = useMemo(() => Object.freeze({
894
- getView: () => latest.current,
895
- roving
896
- }), [roving]);
376
+ const [runtime] = useState(() => createCalendarViewRuntime(() => latest.current));
897
377
  if (activeView === null) return fallback;
898
378
  const { definition, environment, events, loadRange, options, projection, range } = activeView;
899
379
  return createElement(CalendarViewRuntimeContext, { value: runtime }, createElement(definition.Renderer, {
@@ -906,7 +386,7 @@ function createCalendarParts(contexts) {
906
386
  projection,
907
387
  range
908
388
  }), createElement(RovingFocusSync, {
909
- roving,
389
+ roving: runtime.roving,
910
390
  source,
911
391
  view: activeView
912
392
  }));
@@ -931,227 +411,9 @@ function createCalendarParts(contexts) {
931
411
  Viewport
932
412
  });
933
413
  }
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
414
+ // src/event-input.ts
1153
415
  const readNothing = () => null;
1154
- const subscribeToNothing$1 = () => () => void 0;
416
+ const subscribeToNothing$2 = () => () => void 0;
1155
417
  function isEventSource(input) {
1156
418
  return !Array.isArray(input);
1157
419
  }
@@ -1165,7 +427,7 @@ function useEventInput(input) {
1165
427
  const { read, readServer, subscribe } = useMemo(() => source === void 0 ? {
1166
428
  read: readNothing,
1167
429
  readServer: readNothing,
1168
- subscribe: subscribeToNothing$1
430
+ subscribe: subscribeToNothing$2
1169
431
  } : {
1170
432
  read: () => source.getSnapshot(),
1171
433
  readServer: () => source.getServerSnapshot(),
@@ -1174,47 +436,13 @@ function useEventInput(input) {
1174
436
  const sourced = useSyncExternalStore(subscribe, read, readServer);
1175
437
  return source === void 0 ? input : sourced;
1176
438
  }
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
439
+ // src/resources.ts
1216
440
  /** The nearest root's resource tree, shared by every factory so resource hooks work in any view. */
1217
441
  const CalendarResourcesContext = createContext(null);
442
+ /** What a toggle got, with a React event in place of the DOM event it wraps. */
443
+ function causeOf(cause) {
444
+ return typeof cause === "object" && cause !== null && "nativeEvent" in cause && cause.nativeEvent instanceof Event ? cause.nativeEvent : cause;
445
+ }
1218
446
  const selectExpanded = (state) => state.expandedResourceIds;
1219
447
  /**
1220
448
  * The root's resources as a view shows them: depth first, with collapsed resources' descendants
@@ -1239,53 +467,75 @@ function useVisibleResources(options = {}) {
1239
467
  function useResourceExpansion(resourceId) {
1240
468
  const { actions, read, source } = useInteractionRuntime();
1241
469
  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
- }, [
470
+ const commands = useMemo(() => createResourceExpansionCommands({
471
+ actions,
472
+ read
473
+ }, resourceId), [
1255
474
  actions,
1256
- expanded,
1257
475
  read,
1258
476
  resourceId
1259
477
  ]);
478
+ return useMemo(() => Object.freeze({
479
+ collapse: (cause) => commands.collapse(causeOf(cause)),
480
+ expand: (cause) => commands.expand(causeOf(cause)),
481
+ expanded,
482
+ toggle: (cause) => commands.toggle(causeOf(cause))
483
+ }), [commands, expanded]);
1260
484
  }
1261
- //#endregion
1262
- //#region src/use-now.ts
1263
- const systemClock$1 = createSystemClock();
485
+ // src/status.ts
486
+ /** The nearest root's events, pending changes included, for hooks that work in any factory. */
487
+ const CalendarEventsContext = createContext(null);
1264
488
  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
- };
489
+ const subscribeToNothing$1 = () => () => void 0;
490
+ /** The root's events, pending changes included, for hooks that work in any factory. */
491
+ function useCalendarEvents() {
492
+ const events = useContext(CalendarEventsContext);
493
+ if (events === null) throw new Error("calendar-hook-outside-root");
494
+ return events;
495
+ }
496
+ /**
497
+ * Whether a resource is within its working hours and whether its events occupy it, `at` an
498
+ * instant or now on the calendar's clock; see `resourceStatusAt`. Without `resourceId` it is the
499
+ * calendar's hours and every event. All-day and floating events count on the display time zone,
500
+ * as the views show them. On the clock it re-renders only when the status changes, and is `null`
501
+ * while server rendering unless the calendar fixes `now`. A `null` resource turns it off, such as
502
+ * for the Unassigned column, with nothing computed or scheduled.
503
+ */
504
+ function useResourceStatus(resourceId, at) {
505
+ const availability = useCalendarAvailability();
506
+ const events = useCalendarEvents();
507
+ const source = useContext(CalendarNowSourceContext);
508
+ const fixed = at ?? source?.now;
509
+ const { timeZone } = availability;
510
+ const compute = useCallback((instant) => resourceStatusAt(availability, events, instant, {
511
+ resourceId: resourceId ?? void 0,
512
+ timeZone
513
+ }), [
514
+ availability,
515
+ events,
516
+ resourceId,
517
+ timeZone
518
+ ]);
519
+ const off = resourceId === null;
520
+ const onClock = fixed === void 0 && !off;
521
+ const store = useMemo(() => onClock ? createResourceStatusClock(source, compute) : null, [
522
+ compute,
523
+ onClock,
524
+ source
525
+ ]);
526
+ const sampled = useSyncExternalStore(store?.subscribe ?? subscribeToNothing$1, store?.getSnapshot ?? serverSnapshot$1, store?.getServerSnapshot ?? serverSnapshot$1);
527
+ const pinnedAt = off ? void 0 : fixed?.epochNanoseconds;
528
+ return useMemo(() => pinnedAt === void 0 ? null : compute(Temporal.Instant.fromEpochNanoseconds(pinnedAt)), [compute, pinnedAt]) ?? sampled;
1282
529
  }
530
+ // src/use-now.ts
531
+ const serverSnapshot = () => null;
532
+ const subscribeToNothing = () => () => void 0;
1283
533
  /** Samples `source`; `null` while server rendering and hydrating unless `now` is fixed. */
1284
534
  function useNowFrom(source, intervalMs) {
1285
- const clock = source?.clock ?? systemClock$1;
535
+ const clock = clockOf(source);
1286
536
  const ticker = useMemo(() => createClockTicker(clock, intervalMs), [clock, intervalMs]);
1287
537
  const fixed = source?.now;
1288
- const sampled = useSyncExternalStore(fixed === void 0 ? ticker.subscribe : subscribeToNothing, ticker.getSnapshot, serverSnapshot$1);
538
+ const sampled = useSyncExternalStore(fixed === void 0 ? ticker.subscribe : subscribeToNothing, ticker.getSnapshot, serverSnapshot);
1289
539
  return fixed ?? sampled;
1290
540
  }
1291
541
  /**
@@ -1295,163 +545,23 @@ function useNowFrom(source, intervalMs) {
1295
545
  function useNow({ intervalMs = 6e4 } = {}) {
1296
546
  return useNowFrom(useContext(CalendarNowSourceContext), intervalMs);
1297
547
  }
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
- }
548
+ // src/root.ts
549
+ /**
550
+ * The React adapter of the calendar kernel: it creates the root's runtime once, feeds it each
551
+ * render's props and what it subscribes to, runs the runtime's effects at their moments, and
552
+ * hands the derived model to the same contexts views and hooks always read.
553
+ */
1433
554
  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 }) {
555
+ const runtimeConfig = {
556
+ eventAdapter: config.eventAdapter,
557
+ invalidEventPolicy: config.invalidEventPolicy,
558
+ views: config.views
559
+ };
560
+ 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
561
  const reactId = useId();
1438
562
  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
- }, {
563
+ const [runtime] = useState(() => createCalendarRuntime(runtimeConfig));
564
+ const connection = runtime.connect({
1455
565
  controlled: {
1456
566
  anchorDate,
1457
567
  expandedResourceIds,
@@ -1460,6 +570,38 @@ function createCalendarRoot(config, contexts) {
1460
570
  timeZone,
1461
571
  view
1462
572
  },
573
+ defaults: () => resolveCalendarStoreDefaults({
574
+ anchorDate,
575
+ defaultAnchorDate,
576
+ defaultExpandedResourceIds,
577
+ defaultFocus,
578
+ defaultSelection,
579
+ defaultTimeZone,
580
+ defaultView,
581
+ timeZone,
582
+ view
583
+ }, config.views),
584
+ store
585
+ });
586
+ const { binding, source } = connection;
587
+ const state = useSyncExternalStore(source.subscribe, source.getSnapshot, source.getSnapshot);
588
+ const { overlay } = runtime;
589
+ const overlaid = useSyncExternalStore(overlay.subscribe, overlay.getSnapshot, overlay.getSnapshot);
590
+ const resolvedEvents = useEventInput(events);
591
+ const instant = useNowFrom({
592
+ clock,
593
+ now
594
+ }, TODAY_SAMPLE_INTERVAL_MS);
595
+ const inputs = {
596
+ allowAgentDelete,
597
+ annotationSources,
598
+ annotations,
599
+ availability,
600
+ clock,
601
+ connection,
602
+ direction,
603
+ disambiguation,
604
+ events: resolvedEvents,
1463
605
  handlers: {
1464
606
  onAnchorDateChange,
1465
607
  onExpandedResourceIdsChange,
@@ -1467,209 +609,51 @@ function createCalendarRoot(config, contexts) {
1467
609
  onSelectionChange,
1468
610
  onTimeZoneChange,
1469
611
  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,
612
+ },
613
+ instant,
614
+ locale,
615
+ now,
1609
616
  onDiagnosticsChange,
1610
617
  onEventChange,
1611
618
  onEventChangeResult,
1612
619
  onVisibleRangeChange,
620
+ overlay: overlaid,
1613
621
  policies,
1614
- resourceTree,
1615
- viewOptions: viewOverrides
622
+ resources,
623
+ secondaryTimeZones,
624
+ state,
625
+ viewOptions,
626
+ weekRules
1616
627
  };
1617
- const committed = useRef(committedInputs);
1618
- useInsertionEffect(() => {
1619
- committed.current = committedInputs;
628
+ const model = runtime.derive(inputs);
629
+ useInsertionEffect(() => runtime.commit(model, inputs));
630
+ useInsertionEffect(() => binding.attach(), [binding]);
631
+ const { diagnostics, eventSnapshot, visibleRange } = model;
632
+ useLayoutEffect(() => runtime.reconcile(eventSnapshot), [eventSnapshot, runtime]);
633
+ useEffect(() => runtime.reportDiagnostics(diagnostics), [diagnostics, runtime]);
634
+ useEffect(() => runtime.reportVisibleRange(visibleRange), [runtime, visibleRange]);
635
+ const handle = usePrimitive(config.primitive, {
636
+ allowAgentDelete,
637
+ formatAgentEventLabel,
638
+ runtime,
639
+ ...state
1620
640
  });
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
641
  const [refs] = useState(() => Object.freeze({
1656
642
  frame: createRef(),
1657
643
  title: createRef(),
1658
644
  toolbar: createRef(),
1659
645
  viewport: createRef()
1660
646
  }));
1661
- const ids = useMemo(() => Object.freeze({
1662
- frame: `${instanceId}-frame`,
1663
- title: `${instanceId}-title`,
1664
- viewport: `${instanceId}-viewport`
1665
- }), [instanceId]);
647
+ const ids = useMemo(() => createCalendarPartIds(instanceId), [instanceId]);
648
+ const { activeDefinition, environment, resources: stableResources, visibleEvents } = model;
1666
649
  const meta = useMemo(() => Object.freeze({
1667
650
  activeView: activeDefinition,
1668
651
  diagnostics,
1669
652
  environment,
1670
- eventSnapshot: visibleSnapshot,
653
+ eventSnapshot: visibleEvents,
1671
654
  ids,
1672
655
  instanceId,
656
+ label,
1673
657
  refs,
1674
658
  resources: stableResources,
1675
659
  views: config.views
@@ -1677,17 +661,17 @@ function createCalendarRoot(config, contexts) {
1677
661
  activeDefinition,
1678
662
  diagnostics,
1679
663
  environment,
1680
- visibleSnapshot,
664
+ visibleEvents,
1681
665
  ids,
1682
666
  instanceId,
667
+ label,
1683
668
  refs,
1684
669
  stableResources
1685
670
  ]);
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))))))))))));
671
+ 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
672
  };
1688
673
  }
1689
- //#endregion
1690
- //#region src/calendar.ts
674
+ // src/calendar.ts
1691
675
  /** `useCalendarPendingChanges` without a selector: the map itself. */
1692
676
  const allChanges = (changes) => changes;
1693
677
  /**
@@ -1707,10 +691,12 @@ function createCalendar() {
1707
691
  names.add(view.name);
1708
692
  }
1709
693
  const contexts = createCalendarContexts();
694
+ const primitive = createCalendarPrimitive({ views });
1710
695
  const { EventPart, ViewSwitcher, ...parts } = createCalendarParts(contexts);
1711
696
  const Root = createCalendarRoot({
1712
697
  eventAdapter: options.eventAdapter,
1713
698
  invalidEventPolicy: options.invalidEventPolicy,
699
+ primitive,
1714
700
  views
1715
701
  }, contexts);
1716
702
  const useCalendarActions = () => useRootContext(contexts.actions);
@@ -1751,25 +737,54 @@ function createCalendar() {
1751
737
  });
1752
738
  };
1753
739
  }
1754
- //#endregion
1755
- //#region src/history.ts
740
+ // src/draft.ts
741
+ const serverDraft = () => null;
1756
742
  /**
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.
743
+ * The resources busy during `range`, such as a meeting being placed, with their events; free
744
+ * ones are absent. It queries the root's events, pending changes included, once per change of
745
+ * events or range, however many components ask. `exclude` leaves out an event, such as the one
746
+ * being moved; `null` asks nothing.
1759
747
  */
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;
748
+ function useBusyResources(range, { exclude, resourceIds } = {}) {
749
+ const events = useCalendarEvents();
750
+ const { timeZone } = useCalendarAvailability();
751
+ const [query] = useState(createBusyResourcesQuery);
752
+ return query(events, range, {
753
+ exclude,
754
+ resourceIds,
755
+ timeZone
756
+ });
757
+ }
758
+ /** Reports the pointer's draft to the root, for `onPreview` of `useCalendarPointer`. */
759
+ function useCalendarDraftReporter() {
760
+ return useInteractionRuntime().pointerDraft.set;
1771
761
  }
1772
762
  /**
763
+ * The change being drafted, by pointer or keyboard: the event it changes (`null` when creating)
764
+ * and where it would land; `null` without one. It changes once a slot step, so pass its
765
+ * `proposed` to `useBusyResources` for any "who's busy" UI of your own.
766
+ */
767
+ function useCalendarDraft() {
768
+ const { draft } = useInteractionRuntime();
769
+ return useSyncExternalStore(draft.subscribe, draft.getSnapshot, serverDraft);
770
+ }
771
+ /**
772
+ * A resource during the draft's time while one is being made, by pointer or keyboard: the busy
773
+ * events that overlap it (the draft's own event aside; see `isBusy` on the event adapter), and
774
+ * whether the time falls outside its hours. `null` without a draft, or for a `null` resource.
775
+ * The draft's busy resources are worked out once a step for every component that asks, and a
776
+ * component re-renders only when its own resource's answer changes.
777
+ */
778
+ function useDraftBusy(resourceId) {
779
+ const { draft } = useInteractionRuntime();
780
+ const events = useCalendarEvents();
781
+ const availability = useCalendarAvailability();
782
+ const [query] = useState(createDraftBusyQuery);
783
+ const read = () => query(draft.getSnapshot(), events, availability, resourceId);
784
+ return useSyncExternalStore(draft.subscribe, read, serverDraft);
785
+ }
786
+ // src/history.ts
787
+ /**
1773
788
  * Binds an event history to the nearest `Root`: undo and redo propose the inverse through the
1774
789
  * root's `proposeEventChange`, against the events the user sees, and with `messages` their
1775
790
  * outcomes are spoken through the root's `Announcer`. The history records through `Root`'s
@@ -1790,128 +805,27 @@ function useCalendarHistory(history, options = {}) {
1790
805
  const events = useContext(CalendarEventsContext);
1791
806
  const latest = useRef({
1792
807
  events,
1793
- options
808
+ messages: options.messages
1794
809
  });
1795
810
  useInsertionEffect(() => {
1796
811
  latest.current = {
1797
812
  events,
1798
- options
813
+ messages: options.messages
1799
814
  };
1800
815
  });
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
- }, [
816
+ const bound = useMemo(() => bindCalendarHistory({
817
+ actions,
818
+ announcements,
819
+ changes
820
+ }, history, () => latest.current), [
1852
821
  actions,
1853
822
  announcements,
1854
823
  changes,
1855
824
  history
1856
825
  ]);
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;
826
+ return useSyncExternalStore(bound.subscribe, bound.getSnapshot, bound.getServerSnapshot);
1914
827
  }
828
+ // src/history-shortcuts.ts
1915
829
  /**
1916
830
  * Undo and redo keys for a calendar: Mod+Z undoes, and Shift+Mod+Z or Ctrl+Y redoes, where Mod is
1917
831
  * ⌘ on Apple platforms and Ctrl elsewhere. While the hook is mounted and enabled, one `keydown`
@@ -1939,340 +853,26 @@ function useCalendarHistoryShortcuts(history, options) {
1939
853
  });
1940
854
  const { disabled = false } = options;
1941
855
  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);
856
+ if (disabled) return void 0;
857
+ return attachCalendarHistoryShortcuts({
858
+ keyboard,
859
+ pointerDraft
860
+ }, () => {
861
+ const { history: target, options: current } = latest.current;
862
+ return {
863
+ history: target,
864
+ redo: current.redo,
865
+ scope: current.scope.current,
866
+ undo: current.undo
867
+ };
868
+ });
1962
869
  }, [
1963
870
  disabled,
1964
871
  keyboard,
1965
872
  pointerDraft
1966
873
  ]);
1967
874
  }
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
- }
875
+ // src/keyboard.ts
2276
876
  /**
2277
877
  * Keyboard navigation and keyboard move, resize, and create for a view; spread the handlers on
2278
878
  * the element around its focusable cells and events (see `useRovingFocus`).
@@ -2302,17 +902,36 @@ function useCalendarKeyboard(options = {}) {
2302
902
  resources
2303
903
  };
2304
904
  });
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;
905
+ const keyboard = useMemo(() => createCalendarKeyboard(interaction, view, () => latest.current.options, () => latest.current.resources), [interaction, view]);
906
+ const { keyboard: session } = interaction;
907
+ useEffect(() => () => session.set(null), [session]);
908
+ return useMemo(() => Object.freeze({
909
+ onBlur: (event) => keyboard.focusOut(event.nativeEvent, event.currentTarget),
910
+ onKeyDown: (event) => keyboard.keyDown(event.nativeEvent, event)
911
+ }), [keyboard]);
2309
912
  }
2310
913
  const selectSession = (session) => session;
2311
914
  function useCalendarInteraction(selector = selectSession, options) {
2312
915
  return useStateSelector(useInteractionRuntime().keyboard.grabs, (grab) => selector(grab?.session ?? null, grab?.check ?? null), options);
2313
916
  }
2314
- //#endregion
2315
- //#region src/selectors.ts
917
+ // src/pointer.ts
918
+ /**
919
+ * Pointer move, resize, and create for a view region; see `attachCalendarPointer` for the data
920
+ * attributes the view renders. Returns a ref for the region element. Options are read when a
921
+ * gesture starts, and `columns` again as it moves, so changing them never re-attaches listeners,
922
+ * and dragging never re-renders. `disabled` is the exception: a disabled region doesn't listen for
923
+ * touch moves, so a read-only calendar's swipes never wait for its listener, and changing it
924
+ * attaches the listeners again.
925
+ */
926
+ function useCalendarPointer(options) {
927
+ const latest = useRef(options);
928
+ useInsertionEffect(() => {
929
+ latest.current = options;
930
+ });
931
+ const disabled = options.disabled === true;
932
+ return useCallback((element) => element === null ? void 0 : attachCalendarPointer(element, () => latest.current), [disabled]);
933
+ }
934
+ // src/selectors.ts
2316
935
  /**
2317
936
  * Selects from the calendar's focus for a view's item, such as whether a slot cursor sits on this
2318
937
  * column. A component re-renders only when its result changes.
@@ -2327,8 +946,7 @@ function useCalendarFocus(selector, options) {
2327
946
  function useCalendarSelection(selector, options) {
2328
947
  return useStateSelector(useInteractionRuntime().source, (state) => selector(state.selection), options);
2329
948
  }
2330
- //#endregion
2331
- //#region src/requests.ts
949
+ // src/requests.ts
2332
950
  /**
2333
951
  * Calls `listener` whenever something asks the calendar for an anchor date: Previous, Next,
2334
952
  * Today, keys paging past the view, or `setAnchorDate`, even a date that is already the anchor.
@@ -2343,11 +961,18 @@ function useAnchorDateRequests(listener) {
2343
961
  useInsertionEffect(() => {
2344
962
  latest.current = listener;
2345
963
  });
2346
- useLayoutEffect(() => requests((slice, value) => {
2347
- if (slice !== "anchorDate") return;
2348
- const date = value;
2349
- latest.current(date, rangeOf(date));
2350
- }), [rangeOf, requests]);
964
+ useLayoutEffect(() => subscribeAnchorDateRequests({
965
+ rangeOf,
966
+ requests
967
+ }, (date, range) => latest.current(date, range)), [rangeOf, requests]);
968
+ }
969
+ // src/views.ts
970
+ function defineCalendarView(view) {
971
+ return Object.freeze({
972
+ defaultOptions: view.defaultOptions,
973
+ name: view.name,
974
+ Renderer: view.Renderer,
975
+ strategy: view.strategy
976
+ });
2351
977
  }
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 };
978
+ export { createCalendar, createCalendarStore, defineCalendarView, useAnchorDateRequests, useBusyResources, useCalendarAnnotations, useCalendarAnnouncer, useCalendarAvailability, useCalendarDraft, useCalendarDraftReporter, useCalendarFocus, useCalendarHistory, useCalendarHistoryShortcuts, useCalendarInteraction, useCalendarKeyboard, useCalendarPointer, useCalendarSelection, useClosedDates, useDraftBusy, useNow, useResourceExpansion, useResourceStatus, useRovingFocus, useTimeGridAnnotations, useTimeGridAvailability, useTimelineAvailability, useVisibleResources };