@moltenship/calendar-react 2.0.0-beta.1 → 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,9 +1,9 @@
1
1
  "use client";
2
- import { anchorShowingDate, busyResources, closedDates, fitsAvailability, keyboardSessionProposal, moveKeyboardCursor, projectTimeGridAnnotations, projectTimeGridAvailability, projectTimelineAvailability, 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 { TODAY_SAMPLE_INTERVAL_MS, clockOf, createCalendarPartIds, createCalendarPrimitive, createCalendarRuntime, createCalendarStore, createClockTicker, reportCallbackError, resolveCalendarStoreDefaults, sameElements } from "@moltenship/calendar-primitives";
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
5
  import { usePart, usePrimitive } from "@ui-sdk/react/primitive";
6
- import { createSystemClock, plainDateIntervalContains } from "@moltenship/calendar-temporal";
6
+ import { attachCalendarPointer } from "@moltenship/calendar-dnd";
7
7
  // src/annotations.ts
8
8
  /** The nearest root's annotations, shared by every factory so annotation hooks work in any view. */
9
9
  const CalendarAnnotationsContext = createContext(null);
@@ -34,11 +34,6 @@ function useTimeGridAnnotations(columns, { layout, maxLanes, minGap, minHeight }
34
34
  ]);
35
35
  }
36
36
  // src/interaction.ts
37
- /** Time-grid slots when a view does not choose its own, as in the pointer layer. */
38
- const DEFAULT_SNAP = Object.freeze({
39
- increment: 15,
40
- smallestUnit: "minute"
41
- });
42
37
  const CalendarInteractionContext = createContext(null);
43
38
  const CalendarViewRuntimeContext = createContext(null);
44
39
  function useInteractionRuntime() {
@@ -74,14 +69,9 @@ function Announcer({ messages, style, ...props }) {
74
69
  useInsertionEffect(() => {
75
70
  latest.current = messages;
76
71
  });
77
- const [spoken, setSpoken] = useState({
78
- repeat: false,
79
- text: ""
80
- });
81
- useLayoutEffect(() => announcements.mount(() => latest.current, (text) => setSpoken((last) => ({
82
- repeat: last.text === text && !last.repeat,
83
- text
84
- }))), [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]);
85
75
  return createElement("div", {
86
76
  "aria-atomic": true,
87
77
  "aria-live": "polite",
@@ -92,7 +82,7 @@ function Announcer({ messages, style, ...props }) {
92
82
  ...visuallyHidden,
93
83
  ...style
94
84
  }
95
- }, spoken.repeat ? `${spoken.text}\u00a0` : spoken.text);
85
+ }, spoken);
96
86
  }
97
87
  /**
98
88
  * The announcer views pass to the pointer layer (`useCalendarPointer({ announcer })`), so pointer
@@ -198,203 +188,14 @@ function useStateSelector(source, selector, { isEqual = Object.is } = {}) {
198
188
  return selected;
199
189
  }
200
190
  // src/roving-focus.ts
201
- /** Whether `focus` is on an element that shows `target` across `days` dates. */
202
- function focusLandsOn(focus, target, days) {
203
- if (focus.kind === "event" && target.kind === "event") {
204
- const offset = target.date.until(focus.date).days;
205
- return focus.eventId === target.eventId && focus.resourceId === target.resourceId && offset >= 0 && offset < days;
206
- }
207
- return sameFocus(focus, target);
208
- }
209
- /**
210
- * `focus` as it lands on an element showing `target` across `days` dates, or `null` when it does
211
- * not. A resource on only one side matches, so focus carries over between views with and without
212
- * resources, and then takes the element's resource, keeping its date: one copy is the tab stop,
213
- * and keys act in the resource it shows.
214
- */
215
- function landOn(focus, target, days) {
216
- const { resourceId } = target;
217
- if (focus.resourceId === resourceId) return focusLandsOn(focus, target, days) ? focus : null;
218
- if (focus.resourceId !== void 0 && resourceId !== void 0) return null;
219
- const landed = {
220
- ...focus,
221
- resourceId
222
- };
223
- return focusLandsOn(landed, target, days) ? landed : null;
224
- }
225
- function createRovingFocusStore(initialEntry) {
226
- const items = /* @__PURE__ */ new Map();
227
- const listeners = /* @__PURE__ */ new Set();
228
- let focus = null;
229
- let getEntry = initialEntry;
230
- let entryCommand = "home";
231
- let resolved = null;
232
- /**
233
- * DOM focus owed after the next update: to the tab stop, as keyboard navigation asks, or only
234
- * to the focused target once it renders, after the element holding DOM focus went away.
235
- */
236
- let owed = null;
237
- /**
238
- * The last element let go while it held DOM focus. It can stay in the document, as a scrolling
239
- * view keeps days around the visible ones, and focus on it is still the view's to move.
240
- */
241
- let released = null;
242
- function find(target) {
243
- if (target === null) return void 0;
244
- let compatible;
245
- for (const [element, item] of items) {
246
- const landed = landOn(target, item.target, item.days);
247
- if (landed === target) return {
248
- element,
249
- target
250
- };
251
- if (landed !== null) compatible ??= {
252
- element,
253
- target: landed
254
- };
255
- }
256
- return compatible;
257
- }
258
- function resolve() {
259
- if (resolved !== null) return resolved;
260
- const entry = getEntry(entryCommand);
261
- if (items.size === 0) return resolved = { target: entry ?? focus };
262
- const found = find(focus);
263
- if (found !== void 0) return resolved = {
264
- ...found,
265
- isFocus: true
266
- };
267
- const entered = find(entry);
268
- if (entered !== void 0) return resolved = entered;
269
- const [element] = [...items.keys()].sort((left, right) => left.compareDocumentPosition(right) & Node.DOCUMENT_POSITION_FOLLOWING ? -1 : 1);
270
- return resolved = {
271
- element,
272
- target: element === void 0 ? null : items.get(element).target
273
- };
274
- }
275
- function changed() {
276
- resolved = null;
277
- for (const listener of listeners) listener();
278
- }
279
- let notifying = false;
280
- /**
281
- * `changed` for elements coming and going: a commit registers them one by one, hundreds in a
282
- * year of days, so their elements hear once, after it, rather than once per element.
283
- */
284
- function changedLater() {
285
- resolved = null;
286
- if (notifying) return;
287
- notifying = true;
288
- queueMicrotask(() => {
289
- notifying = false;
290
- changed();
291
- });
292
- }
293
- function itemAt(node) {
294
- for (let current = node; current !== null; current = current.parentNode) {
295
- const item = items.get(current);
296
- if (item !== void 0) return item;
297
- }
298
- }
299
- /** Focuses the tab stop unless focus has moved elsewhere on the page in the meantime. */
300
- function focusNow() {
301
- const { element, isFocus = false } = resolve();
302
- if (owed === "focus" && !isFocus) return;
303
- owed = null;
304
- const active = document.activeElement;
305
- if (element === void 0 || element === active) return;
306
- const ours = itemAt(active) !== void 0 || released?.contains(active) === true;
307
- if (active !== null && active !== document.body && !ours) return;
308
- released = null;
309
- element.focus();
310
- }
311
- let retrying = false;
312
- /**
313
- * Retries owed focus once the commit that registered an element is done. By then this commit's
314
- * focus has reached the store, so a newer focus wins over the element that came back.
315
- */
316
- function retryOwedFocus() {
317
- if (retrying) return;
318
- retrying = true;
319
- queueMicrotask(() => {
320
- retrying = false;
321
- if (owed === "focus") focusNow();
322
- });
323
- }
324
- return Object.freeze({
325
- enterFromEnd() {
326
- entryCommand = "end";
327
- },
328
- focusAt(node) {
329
- const item = itemAt(node);
330
- if (item === void 0) return focus;
331
- return (focus === null ? null : landOn(focus, item.target, item.days)) ?? item.target;
332
- },
333
- focusTabStop(when) {
334
- owed = "tab-stop";
335
- if (when === "now") focusNow();
336
- },
337
- isTabStop(target, days) {
338
- const stop = resolve().target;
339
- return stop !== null && focusLandsOn(stop, target, days);
340
- },
341
- register(element, target, days) {
342
- items.set(element, {
343
- days,
344
- target
345
- });
346
- changedLater();
347
- if (owed === "focus") retryOwedFocus();
348
- return () => {
349
- if (items.get(element)?.target !== target) return;
350
- if (element.contains(document.activeElement)) {
351
- owed ??= "focus";
352
- released = element;
353
- }
354
- items.delete(element);
355
- changedLater();
356
- };
357
- },
358
- subscribe(listener) {
359
- listeners.add(listener);
360
- return () => {
361
- listeners.delete(listener);
362
- };
363
- },
364
- update(nextFocus, nextEntry) {
365
- focus = nextFocus;
366
- getEntry = nextEntry;
367
- if (nextFocus !== null) entryCommand = "home";
368
- changed();
369
- if (owed !== null) focusNow();
370
- }
371
- });
372
- }
373
191
  const selectFocus = (state) => state.focus;
374
- /** The active view's entry points, from its navigation with no focus. */
375
- function viewEntry(view) {
376
- return (command) => {
377
- if (view === null) return null;
378
- const { definition, environment, options, projection, range } = view;
379
- const result = definition.strategy.getSpatialNavigation?.({
380
- command,
381
- environment,
382
- focus: null,
383
- options,
384
- projection,
385
- range,
386
- snap: DEFAULT_SNAP
387
- });
388
- return result != null && "focus" in result ? result.focus : null;
389
- };
390
- }
391
192
  /**
392
193
  * Keeps the active view's roving store on the root's focus. Rendered after the view, so the
393
194
  * elements of a commit are registered before focus moves to one of them.
394
195
  */
395
196
  function RovingFocusSync({ roving, source, view }) {
396
197
  const focus = useStateSelector(source, selectFocus);
397
- const entry = useMemo(() => viewEntry(view), [view]);
198
+ const entry = useMemo(() => calendarViewEntry(view), [view]);
398
199
  useLayoutEffect(() => roving.update(focus, entry), [
399
200
  entry,
400
201
  focus,
@@ -402,15 +203,6 @@ function RovingFocusSync({ roving, source, view }) {
402
203
  ]);
403
204
  return null;
404
205
  }
405
- function focusKey(target) {
406
- const { resourceId } = target;
407
- const resource = resourceId === void 0 ? "" : resourceId === null ? "|unassigned" : `|${typeof resourceId}:${resourceId}`;
408
- switch (target.kind) {
409
- case "day": return `day:${target.date.toString()}${resource}`;
410
- case "slot": return `slot:${target.date.toString()}T${target.time.toString()}${resource}`;
411
- case "event": return `event:${typeof target.eventId}:${target.eventId}@${target.date.toString()}${resource}`;
412
- }
413
- }
414
206
  /**
415
207
  * Props for one focusable element of a view: a day cell, a slot, or an event. The view's one tab
416
208
  * stop gets `tabIndex={0}`; focusing an element makes it the calendar's focus, and keyboard
@@ -426,7 +218,7 @@ function useRovingFocus(target, { days = 1 } = {}) {
426
218
  });
427
219
  const isTabStop = () => roving.isTabStop(target, days);
428
220
  const tabStop = useSyncExternalStore(roving.subscribe, isTabStop, isTabStop);
429
- const key = focusKey(target);
221
+ const key = calendarFocusKey(target);
430
222
  const ref = useCallback((element) => element === null ? void 0 : roving.register(element, latest.current, days), [
431
223
  days,
432
224
  key,
@@ -435,12 +227,10 @@ function useRovingFocus(target, { days = 1 } = {}) {
435
227
  return {
436
228
  onFocus: useCallback((event) => {
437
229
  if (event.target !== event.currentTarget) return;
438
- const focus = read().focus;
439
- const landed = focus === null ? null : landOn(focus, latest.current, days);
440
- if (landed === null || landed !== focus) actions.setFocus(landed ?? latest.current, {
441
- event: event.nativeEvent,
442
- reason: "focus-change"
443
- });
230
+ focusRovingTarget({
231
+ actions,
232
+ read
233
+ }, latest.current, days, event.nativeEvent);
444
234
  }, [
445
235
  actions,
446
236
  days,
@@ -583,11 +373,7 @@ function createCalendarParts(contexts) {
583
373
  useInsertionEffect(() => {
584
374
  latest.current = activeView;
585
375
  });
586
- const [roving] = useState(() => createRovingFocusStore(viewEntry(activeView)));
587
- const runtime = useMemo(() => Object.freeze({
588
- getView: () => latest.current,
589
- roving
590
- }), [roving]);
376
+ const [runtime] = useState(() => createCalendarViewRuntime(() => latest.current));
591
377
  if (activeView === null) return fallback;
592
378
  const { definition, environment, events, loadRange, options, projection, range } = activeView;
593
379
  return createElement(CalendarViewRuntimeContext, { value: runtime }, createElement(definition.Renderer, {
@@ -600,7 +386,7 @@ function createCalendarParts(contexts) {
600
386
  projection,
601
387
  range
602
388
  }), createElement(RovingFocusSync, {
603
- roving,
389
+ roving: runtime.roving,
604
390
  source,
605
391
  view: activeView
606
392
  }));
@@ -653,19 +439,9 @@ function useEventInput(input) {
653
439
  // src/resources.ts
654
440
  /** The nearest root's resource tree, shared by every factory so resource hooks work in any view. */
655
441
  const CalendarResourcesContext = createContext(null);
656
- /** A command's options from what a toggle got: the click a person made, or a caller's options. */
657
- function commandOf(cause) {
658
- if (typeof cause !== "object" || cause === null) return { reason: "resource-toggle" };
659
- if ("nativeEvent" in cause && cause.nativeEvent instanceof Event) return {
660
- event: cause.nativeEvent,
661
- reason: "resource-toggle"
662
- };
663
- const { event, reason, source } = cause;
664
- return {
665
- reason: typeof reason === "string" ? reason : "resource-toggle",
666
- ...event instanceof Event ? { event } : {},
667
- ...typeof source === "string" ? { source } : {}
668
- };
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;
669
445
  }
670
446
  const selectExpanded = (state) => state.expandedResourceIds;
671
447
  /**
@@ -691,66 +467,31 @@ function useVisibleResources(options = {}) {
691
467
  function useResourceExpansion(resourceId) {
692
468
  const { actions, read, source } = useInteractionRuntime();
693
469
  const expanded = useStateSelector(source, (state) => state.expandedResourceIds.includes(resourceId));
694
- return useMemo(() => {
695
- const set = (next, cause) => {
696
- const current = read().expandedResourceIds;
697
- if (current.includes(resourceId) === next) return;
698
- actions.setExpandedResourceIds(next ? [...current, resourceId] : current.filter((id) => id !== resourceId), commandOf(cause));
699
- };
700
- return Object.freeze({
701
- collapse: (cause) => set(false, cause),
702
- expand: (cause) => set(true, cause),
703
- expanded,
704
- toggle: (cause) => set(!read().expandedResourceIds.includes(resourceId), cause)
705
- });
706
- }, [
470
+ const commands = useMemo(() => createResourceExpansionCommands({
471
+ actions,
472
+ read
473
+ }, resourceId), [
707
474
  actions,
708
- expanded,
709
475
  read,
710
476
  resourceId
711
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]);
712
484
  }
713
485
  // src/status.ts
714
486
  /** The nearest root's events, pending changes included, for hooks that work in any factory. */
715
487
  const CalendarEventsContext = createContext(null);
716
- const systemClock = createSystemClock();
717
- /** How often the clock is sampled between changes, in case it jumps. */
718
- const SAMPLE_MS = 6e4;
719
- const serverSnapshot$2 = () => null;
488
+ const serverSnapshot$1 = () => null;
720
489
  const subscribeToNothing$1 = () => () => void 0;
721
- function sameInstant(left, right) {
722
- return left === right || left !== null && right !== null && left.equals(right);
723
- }
724
- function sameStatus(left, right) {
725
- const [a, b] = [left.availability, right.availability];
726
- const [c, d] = [left.busy, right.busy];
727
- return sameInstant(left.changesAt, right.changesAt) && (a.available ? b.available && sameInstant(a.closesAt, b.closesAt) : !b.available && a.reason === b.reason && a.label === b.label && sameInstant(a.opensAt, b.opensAt)) && (c.busy ? d.busy && sameInstant(c.freeAt, d.freeAt) && c.events.length === d.events.length && c.events.every((event, index) => event === d.events[index]) : !d.busy && sameInstant(c.nextEventAt, d.nextEventAt));
728
- }
729
- /**
730
- * The status on the clock: it samples when the status next changes, and every minute in case the
731
- * clock jumps, and tells subscribers only when the status differs.
732
- */
733
- function createStatusClock(source, compute) {
734
- const clock = source?.clock ?? systemClock;
735
- let current;
736
- return {
737
- getSnapshot: () => current ??= compute(clock.instant()),
738
- subscribe: (onChange) => {
739
- let timer;
740
- const sample = () => {
741
- const now = clock.instant();
742
- const next = compute(now);
743
- if (current === void 0 || !sameStatus(current, next)) {
744
- current = next;
745
- onChange();
746
- }
747
- const until = next.changesAt === null ? SAMPLE_MS : now.until(next.changesAt).total("milliseconds");
748
- timer = setTimeout(sample, Math.max(0, Math.min(SAMPLE_MS, until)));
749
- };
750
- sample();
751
- return () => clearTimeout(timer);
752
- }
753
- };
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;
754
495
  }
755
496
  /**
756
497
  * Whether a resource is within its working hours and whether its events occupy it, `at` an
@@ -760,12 +501,6 @@ function createStatusClock(source, compute) {
760
501
  * while server rendering unless the calendar fixes `now`. A `null` resource turns it off, such as
761
502
  * for the Unassigned column, with nothing computed or scheduled.
762
503
  */
763
- /** The root's events, pending changes included, for hooks that work in any factory. */
764
- function useCalendarEvents() {
765
- const events = useContext(CalendarEventsContext);
766
- if (events === null) throw new Error("calendar-hook-outside-root");
767
- return events;
768
- }
769
504
  function useResourceStatus(resourceId, at) {
770
505
  const availability = useCalendarAvailability();
771
506
  const events = useCalendarEvents();
@@ -783,24 +518,24 @@ function useResourceStatus(resourceId, at) {
783
518
  ]);
784
519
  const off = resourceId === null;
785
520
  const onClock = fixed === void 0 && !off;
786
- const store = useMemo(() => onClock ? createStatusClock(source, compute) : null, [
521
+ const store = useMemo(() => onClock ? createResourceStatusClock(source, compute) : null, [
787
522
  compute,
788
523
  onClock,
789
524
  source
790
525
  ]);
791
- const sampled = useSyncExternalStore(store?.subscribe ?? subscribeToNothing$1, store?.getSnapshot ?? serverSnapshot$2, serverSnapshot$2);
526
+ const sampled = useSyncExternalStore(store?.subscribe ?? subscribeToNothing$1, store?.getSnapshot ?? serverSnapshot$1, store?.getServerSnapshot ?? serverSnapshot$1);
792
527
  const pinnedAt = off ? void 0 : fixed?.epochNanoseconds;
793
528
  return useMemo(() => pinnedAt === void 0 ? null : compute(Temporal.Instant.fromEpochNanoseconds(pinnedAt)), [compute, pinnedAt]) ?? sampled;
794
529
  }
795
530
  // src/use-now.ts
796
- const serverSnapshot$1 = () => null;
531
+ const serverSnapshot = () => null;
797
532
  const subscribeToNothing = () => () => void 0;
798
533
  /** Samples `source`; `null` while server rendering and hydrating unless `now` is fixed. */
799
534
  function useNowFrom(source, intervalMs) {
800
535
  const clock = clockOf(source);
801
536
  const ticker = useMemo(() => createClockTicker(clock, intervalMs), [clock, intervalMs]);
802
537
  const fixed = source?.now;
803
- 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);
804
539
  return fixed ?? sampled;
805
540
  }
806
541
  /**
@@ -1002,22 +737,8 @@ function createCalendar() {
1002
737
  });
1003
738
  };
1004
739
  }
1005
- // src/use-stable-value.ts
1006
- /** Returns the previous value while `isEqual` considers the next one equivalent. */
1007
- function useStableValue(value, isEqual) {
1008
- const [stable, setStable] = useState(value);
1009
- if (stable === value || isEqual(stable, value)) return stable;
1010
- setStable(() => value);
1011
- return value;
1012
- }
1013
740
  // src/draft.ts
1014
- function sameIds(left, right) {
1015
- return left === right || left !== void 0 && right !== void 0 && sameElements(left, right);
1016
- }
1017
- function sameInterval(left, right) {
1018
- return left === right || left !== null && right !== null && ("kind" in left ? left.kind : "timed") === ("kind" in right ? right.kind : "timed") && left.start.toString() === right.start.toString() && left.end.toString() === right.end.toString();
1019
- }
1020
- const nothingBusy = /* @__PURE__ */ new Map();
741
+ const serverDraft = () => null;
1021
742
  /**
1022
743
  * The resources busy during `range`, such as a meeting being placed, with their events; free
1023
744
  * ones are absent. It queries the root's events, pending changes included, once per change of
@@ -1027,63 +748,12 @@ const nothingBusy = /* @__PURE__ */ new Map();
1027
748
  function useBusyResources(range, { exclude, resourceIds } = {}) {
1028
749
  const events = useCalendarEvents();
1029
750
  const { timeZone } = useCalendarAvailability();
1030
- const stableRange = useStableValue(range, sameInterval);
1031
- const ids = useStableValue(resourceIds, sameIds);
1032
- return useMemo(() => stableRange === null ? nothingBusy : busyResources(events, stableRange, {
1033
- ...exclude == null ? {} : { exclude },
1034
- ...ids === void 0 ? {} : { resourceIds: ids },
1035
- timeZone
1036
- }), [
1037
- events,
751
+ const [query] = useState(createBusyResourcesQuery);
752
+ return query(events, range, {
1038
753
  exclude,
1039
- ids,
1040
- stableRange,
1041
- timeZone
1042
- ]);
1043
- }
1044
- /** Each draft's busy resources, worked out once for every header that asks. */
1045
- const draftBusy = /* @__PURE__ */ new WeakMap();
1046
- function busyFor(draft, events, timeZone) {
1047
- const cached = draftBusy.get(draft);
1048
- if (cached?.events === events) return cached.busy;
1049
- const busy = busyResources(events, draft.proposed, {
1050
- ...draft.eventId === null ? {} : { exclude: draft.eventId },
754
+ resourceIds,
1051
755
  timeZone
1052
756
  });
1053
- draftBusy.set(draft, {
1054
- busy,
1055
- events
1056
- });
1057
- return busy;
1058
- }
1059
- /** Each keyboard session as a draft, the same object for as long as the session is. */
1060
- const sessionDrafts = /* @__PURE__ */ new WeakMap();
1061
- function draftOf(session) {
1062
- let draft = sessionDrafts.get(session);
1063
- if (draft === void 0) {
1064
- draft = Object.freeze({
1065
- eventId: session.eventId,
1066
- proposed: session.proposed
1067
- });
1068
- sessionDrafts.set(session, draft);
1069
- }
1070
- return draft;
1071
- }
1072
- /** Subscribes to the keyboard's and the pointer's drafts. */
1073
- function useDraftSource() {
1074
- const { keyboard, pointerDraft } = useInteractionRuntime();
1075
- return useMemo(() => ({
1076
- getSnapshot: () => {
1077
- const session = keyboard.grabs.getSnapshot()?.session;
1078
- return session === void 0 ? pointerDraft.getSnapshot() : draftOf(session);
1079
- },
1080
- subscribe: (listener) => {
1081
- const stops = [keyboard.grabs.subscribe(listener), pointerDraft.subscribe(listener)];
1082
- return () => {
1083
- for (const stop of stops) stop();
1084
- };
1085
- }
1086
- }), [keyboard, pointerDraft]);
1087
757
  }
1088
758
  /** Reports the pointer's draft to the root, for `onPreview` of `useCalendarPointer`. */
1089
759
  function useCalendarDraftReporter() {
@@ -1095,12 +765,8 @@ function useCalendarDraftReporter() {
1095
765
  * `proposed` to `useBusyResources` for any "who's busy" UI of your own.
1096
766
  */
1097
767
  function useCalendarDraft() {
1098
- const source = useDraftSource();
1099
- return useSyncExternalStore(source.subscribe, source.getSnapshot, () => null);
1100
- }
1101
- const noEvents = Object.freeze([]);
1102
- function sameBusy(left, right) {
1103
- return left === right || left !== null && right !== null && left.outsideHours === right.outsideHours && left.events.length === right.events.length && left.events.every((event, index) => event === right.events[index]);
768
+ const { draft } = useInteractionRuntime();
769
+ return useSyncExternalStore(draft.subscribe, draft.getSnapshot, serverDraft);
1104
770
  }
1105
771
  /**
1106
772
  * A resource during the draft's time while one is being made, by pointer or keyboard: the busy
@@ -1110,41 +776,15 @@ function sameBusy(left, right) {
1110
776
  * component re-renders only when its own resource's answer changes.
1111
777
  */
1112
778
  function useDraftBusy(resourceId) {
1113
- const source = useDraftSource();
779
+ const { draft } = useInteractionRuntime();
1114
780
  const events = useCalendarEvents();
1115
781
  const availability = useCalendarAvailability();
1116
- const last = useRef(null);
1117
- const read = () => {
1118
- const draft = source.getSnapshot();
1119
- if (draft === null || resourceId === null) return last.current = null;
1120
- const { timeZone } = availability;
1121
- const next = {
1122
- events: busyFor(draft, events, timeZone).get(resourceId) ?? noEvents,
1123
- outsideHours: !fitsAvailability(draft.proposed, availability.forResource(resourceId), timeZone)
1124
- };
1125
- if (!sameBusy(last.current, next)) last.current = next;
1126
- return last.current;
1127
- };
1128
- return useSyncExternalStore(source.subscribe, read, () => null);
782
+ const [query] = useState(createDraftBusyQuery);
783
+ const read = () => query(draft.getSnapshot(), events, availability, resourceId);
784
+ return useSyncExternalStore(draft.subscribe, read, serverDraft);
1129
785
  }
1130
786
  // src/history.ts
1131
787
  /**
1132
- * What the server and hydration read: nothing recorded yet. A plain literal, so a bundler drops
1133
- * it from a calendar that doesn't use the history.
1134
- */
1135
- const serverSnapshot = {
1136
- future: [],
1137
- latest: null,
1138
- past: [],
1139
- pending: null
1140
- };
1141
- const getServerSnapshot = () => serverSnapshot;
1142
- /** Whether a change is still validating or saving: a saved one waiting for events is done. */
1143
- function isUnsettled(changes) {
1144
- for (const { phase } of changes.values()) if (phase !== "awaiting-events") return true;
1145
- return false;
1146
- }
1147
- /**
1148
788
  * Binds an event history to the nearest `Root`: undo and redo propose the inverse through the
1149
789
  * root's `proposeEventChange`, against the events the user sees, and with `messages` their
1150
790
  * outcomes are spoken through the root's `Announcer`. The history records through `Root`'s
@@ -1165,127 +805,27 @@ function useCalendarHistory(history, options = {}) {
1165
805
  const events = useContext(CalendarEventsContext);
1166
806
  const latest = useRef({
1167
807
  events,
1168
- options
808
+ messages: options.messages
1169
809
  });
1170
810
  useInsertionEffect(() => {
1171
811
  latest.current = {
1172
812
  events,
1173
- options
813
+ messages: options.messages
1174
814
  };
1175
815
  });
1176
- const snapshot = useSyncExternalStore(history.subscribe, history.getSnapshot, getServerSnapshot);
1177
- const commands = useMemo(() => {
1178
- /**
1179
- * Resolves once no change is validating or saving, after the turn in which the last one ended,
1180
- * so its result has reached `onEventChangeResult` and the history.
1181
- */
1182
- function whenSettled() {
1183
- if (!isUnsettled(changes.getSnapshot())) return void 0;
1184
- return new Promise((resolve) => {
1185
- const unsubscribe = changes.subscribe(() => {
1186
- if (isUnsettled(changes.getSnapshot())) return;
1187
- unsubscribe();
1188
- setTimeout(resolve);
1189
- });
1190
- });
1191
- }
1192
- function run(direction, { input } = {}) {
1193
- let checked;
1194
- const getEvents = () => {
1195
- const { events } = latest.current;
1196
- checked ??= events;
1197
- return events;
1198
- };
1199
- const context = {
1200
- getEvents,
1201
- input,
1202
- propose: actions.proposeEventChange,
1203
- whenSettled
1204
- };
1205
- return history[direction](context).then((outcome) => {
1206
- const build = latest.current.options.messages?.[direction];
1207
- if (build !== void 0) {
1208
- const eventId = outcome.status === "empty" ? null : outcome.step.eventId;
1209
- const event = eventId === null ? void 0 : latest.current.events.get(eventId) ?? checked?.get(eventId);
1210
- try {
1211
- announcements.say((where) => build(outcome, {
1212
- ...where,
1213
- event
1214
- }));
1215
- } catch (error) {
1216
- reportCallbackError(error);
1217
- }
1218
- }
1219
- return outcome;
1220
- });
1221
- }
1222
- return {
1223
- redo: (commandOptions) => run("redo", commandOptions),
1224
- undo: (commandOptions) => run("undo", commandOptions)
1225
- };
1226
- }, [
816
+ const bound = useMemo(() => bindCalendarHistory({
817
+ actions,
818
+ announcements,
819
+ changes
820
+ }, history, () => latest.current), [
1227
821
  actions,
1228
822
  announcements,
1229
823
  changes,
1230
824
  history
1231
825
  ]);
1232
- return useMemo(() => Object.freeze({
1233
- ...snapshot,
1234
- ...commands,
1235
- canRedo: snapshot.future.length > 0,
1236
- canUndo: snapshot.past.length > 0
1237
- }), [commands, snapshot]);
826
+ return useSyncExternalStore(bound.subscribe, bound.getSnapshot, bound.getServerSnapshot);
1238
827
  }
1239
828
  // src/history-shortcuts.ts
1240
- const defaultUndo = ["Mod+Z"];
1241
- const defaultRedo = ["Shift+Mod+Z", "Ctrl+Y"];
1242
- const keyboardInput$1 = { input: "keyboard" };
1243
- /**
1244
- * Where a key belongs to something else: text the browser undoes in its own field, and dialogs,
1245
- * menus and lists inside the calendar, which handle their own keys.
1246
- */
1247
- const ownKeys = "input, textarea, select, [contenteditable]:not([contenteditable=\"false\"]), [role=\"textbox\"], [role=\"dialog\"], [role=\"alertdialog\"], [role=\"menu\"], [role=\"listbox\"]";
1248
- function isApplePlatform() {
1249
- const { platform, userAgentData } = navigator;
1250
- return /mac|iphone|ipad|ipod/i.test(userAgentData?.platform ?? platform);
1251
- }
1252
- /** Whether `event` is `binding`: exactly its modifiers, and its key by name or position. */
1253
- function matches(event, binding, apple) {
1254
- const parts = binding.split("+").map((part) => part.trim().toLowerCase());
1255
- const key = parts.pop();
1256
- if (key === void 0 || key === "") return false;
1257
- let ctrl = false;
1258
- let meta = false;
1259
- let shift = false;
1260
- let alt = false;
1261
- for (const modifier of parts) if (modifier === "mod") {
1262
- if (apple) meta = true;
1263
- else ctrl = true;
1264
- } else if (modifier === "ctrl" || modifier === "control") ctrl = true;
1265
- else if (modifier === "meta" || modifier === "cmd" || modifier === "command") meta = true;
1266
- else if (modifier === "shift") shift = true;
1267
- else if (modifier === "alt" || modifier === "option") alt = true;
1268
- else return false;
1269
- if (event.ctrlKey !== ctrl || event.metaKey !== meta || event.shiftKey !== shift || event.altKey !== alt) return false;
1270
- const typed = event.key.toLowerCase();
1271
- if (typed === key) return true;
1272
- if (/^[a-z0-9]$/.test(typed)) return false;
1273
- if (/^[a-z]$/.test(key)) return event.code === `Key${key.toUpperCase()}`;
1274
- return /^[0-9]$/.test(key) && event.code === `Digit${key}`;
1275
- }
1276
- /**
1277
- * Whether something on the key's path inside `scope`, from its target out, handles keys of its
1278
- * own: a field, also inside a web component's shadow root, or a dialog, menu or list. A dialog
1279
- * around the whole calendar doesn't count.
1280
- */
1281
- function ownsKeys(path, scope) {
1282
- for (const node of path) {
1283
- if (node === scope) return false;
1284
- if (!(node instanceof Element)) continue;
1285
- if (node instanceof HTMLElement && node.isContentEditable || node.matches(ownKeys)) return true;
1286
- }
1287
- return false;
1288
- }
1289
829
  /**
1290
830
  * Undo and redo keys for a calendar: Mod+Z undoes, and Shift+Mod+Z or Ctrl+Y redoes, where Mod is
1291
831
  * ⌘ on Apple platforms and Ctrl elsewhere. While the hook is mounted and enabled, one `keydown`
@@ -1313,26 +853,19 @@ function useCalendarHistoryShortcuts(history, options) {
1313
853
  });
1314
854
  const { disabled = false } = options;
1315
855
  useEffect(() => {
1316
- if (disabled) return;
1317
- const apple = isApplePlatform();
1318
- const listener = (event) => {
1319
- const scope = latest.current.options.scope.current;
1320
- if (event.defaultPrevented || event.isComposing || scope === null) return;
1321
- const path = event.composedPath();
1322
- if (!path.includes(scope)) return;
1323
- const { undo = defaultUndo, redo = defaultRedo } = latest.current.options;
1324
- const direction = undo.some((binding) => matches(event, binding, apple)) ? "undo" : redo.some((binding) => matches(event, binding, apple)) ? "redo" : null;
1325
- if (direction === null || ownsKeys(path, scope)) return;
1326
- if (keyboard.get() !== null || pointerDraft.getSnapshot() !== null) return;
1327
- event.preventDefault();
1328
- try {
1329
- Promise.resolve(latest.current.history[direction](keyboardInput$1)).catch(reportCallbackError);
1330
- } catch (error) {
1331
- reportCallbackError(error);
1332
- }
1333
- };
1334
- document.addEventListener("keydown", listener);
1335
- 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
+ });
1336
869
  }, [
1337
870
  disabled,
1338
871
  keyboard,
@@ -1340,331 +873,6 @@ function useCalendarHistoryShortcuts(history, options) {
1340
873
  ]);
1341
874
  }
1342
875
  // src/keyboard.ts
1343
- const DEFAULT_CREATE_DURATION = { hours: 1 };
1344
- /**
1345
- * What a key tells the state handlers it changes: its reason, and the key itself, from which the
1346
- * store works out the source, the keyboard's, or the agent's while an agent's step presses it.
1347
- */
1348
- function keyCommand(event) {
1349
- return {
1350
- event: event.nativeEvent,
1351
- reason: "keyboard-navigation"
1352
- };
1353
- }
1354
- const keyboardInput = Object.freeze({ input: "keyboard" });
1355
- const navigationKeys = {
1356
- ArrowDown: "down",
1357
- ArrowLeft: "left",
1358
- ArrowRight: "right",
1359
- ArrowUp: "up",
1360
- End: "end",
1361
- Home: "home",
1362
- PageDown: "page-down",
1363
- PageUp: "page-up"
1364
- };
1365
- function createKeyboardHandlers({ actions, announcements, isReadOnly, keyboard, read }, { getView, roving }, getOptions, getResources) {
1366
- const getSnap = () => getOptions().snap ?? DEFAULT_SNAP;
1367
- const view = () => getView();
1368
- function navigate(command, focus) {
1369
- const { definition, environment, options, projection, range } = view();
1370
- return definition.strategy.getSpatialNavigation?.({
1371
- command,
1372
- environment,
1373
- focus,
1374
- options,
1375
- projection,
1376
- range,
1377
- snap: getSnap()
1378
- }) ?? null;
1379
- }
1380
- /** The cell a navigation result names, for keys that move a cell. */
1381
- function cellOf(result) {
1382
- return result !== null && "focus" in result && result.focus.kind !== "event" ? result.focus : null;
1383
- }
1384
- function interactionOptions() {
1385
- return {
1386
- snap: getSnap(),
1387
- timeZone: view().environment.timeZone
1388
- };
1389
- }
1390
- /**
1391
- * Navigates the view by whole ranges until it shows `date`. `command` carries the key, or the
1392
- * focus change, behind it, so the state handlers hear a person's keys as the keyboard's.
1393
- */
1394
- function reveal(date, command) {
1395
- const { definition, environment, options, range } = view();
1396
- if (plainDateIntervalContains(range, date)) return;
1397
- const { anchorDate } = read();
1398
- actions.setAnchorDate(anchorShowingDate(definition.strategy, anchorDate, date, environment, options), command);
1399
- }
1400
- /** Moves the calendar's focus and, once the view renders it, DOM focus. */
1401
- function moveFocus(focus, command) {
1402
- if (sameFocus(focus, read().focus)) {
1403
- roving.focusTabStop("now");
1404
- return;
1405
- }
1406
- roving.focusTabStop("after-update");
1407
- actions.setFocus(focus, command);
1408
- if (focus !== null) reveal(focus.date, command);
1409
- }
1410
- function apply(result, command) {
1411
- if (result === null) return false;
1412
- if ("focus" in result) moveFocus(result.focus, command);
1413
- else {
1414
- const { definition, options } = view();
1415
- roving.focusTabStop("after-update");
1416
- if (result.page < 0) roving.enterFromEnd();
1417
- actions.setAnchorDate(definition.strategy.navigate(read().anchorDate, result.page, options), command);
1418
- actions.setFocus(null, command);
1419
- }
1420
- return true;
1421
- }
1422
- function announce(grab, detail) {
1423
- const { check, session } = grab;
1424
- announcements.announcer.announce({
1425
- cause: session.cause,
1426
- event: grab.event,
1427
- input: "keyboard",
1428
- original: session.original,
1429
- proposed: session.proposed,
1430
- ...detail.phase === "start" || detail.phase === "step" ? { check } : void 0,
1431
- ...detail
1432
- });
1433
- }
1434
- /** What the root's policies would say to committing `session` now, as its preview shows. */
1435
- function checkOf(session) {
1436
- const proposal = keyboardSessionProposal(session);
1437
- return proposal === null ? null : actions.checkEventChange(proposal, keyboardInput);
1438
- }
1439
- /**
1440
- * Follows the grabbed event into the cursor's date and resource, or a create's cell. A move out
1441
- * of the event's last copy in a resource, as into the unassigned bucket, follows it to a resource
1442
- * it still shows in.
1443
- */
1444
- function focusOfSession(session) {
1445
- const { cursor, eventId, proposed } = session;
1446
- return eventId === null ? cursor : {
1447
- date: cursor.date,
1448
- eventId,
1449
- kind: "event",
1450
- resourceId: resourceOn(proposed, cursor.resourceId)
1451
- };
1452
- }
1453
- /** A slot create starts `createDuration` long: its cursor steps later, as a drag would. */
1454
- function startCreate(cell) {
1455
- let session = startKeyboardSession({
1456
- cause: "create",
1457
- cell
1458
- }, interactionOptions());
1459
- if (cell.kind !== "slot") return session;
1460
- const later = getOptions().axis !== "inline" ? "down" : view().environment.direction === "rtl" ? "left" : "right";
1461
- const duration = Temporal.Duration.from(getOptions().createDuration ?? DEFAULT_CREATE_DURATION);
1462
- const slots = Math.round(duration.total({ unit: "minutes" }) / slotDuration(getSnap()).total({ unit: "minutes" }));
1463
- for (let step = 1; step < slots; step += 1) {
1464
- const cursor = cellOf(navigate(later, session.cursor));
1465
- if (cursor === null) break;
1466
- session = moveKeyboardCursor(session, cursor, interactionOptions());
1467
- }
1468
- return session;
1469
- }
1470
- function grab(focus, cause, command) {
1471
- if (focus.kind !== "event") {
1472
- if (cause !== "create") return false;
1473
- const session = startCreate(focus);
1474
- const next = {
1475
- cell: focus,
1476
- check: checkOf(session),
1477
- event: null,
1478
- origin: focus,
1479
- session
1480
- };
1481
- keyboard.set(next);
1482
- moveFocus(focusOfSession(session), command);
1483
- announce(next, { phase: "start" });
1484
- return true;
1485
- }
1486
- if (cause === "create") return false;
1487
- const event = view().events.get(focus.eventId);
1488
- const cell = cellOf(navigate("exit", focus));
1489
- if (event === void 0 || cell === null) return false;
1490
- const next = {
1491
- cell,
1492
- check: null,
1493
- event,
1494
- origin: focus,
1495
- session: startKeyboardSession({
1496
- cause,
1497
- cell,
1498
- event
1499
- }, interactionOptions())
1500
- };
1501
- if (event.isReadOnly) {
1502
- announce(next, {
1503
- phase: "reject",
1504
- reason: "read-only"
1505
- });
1506
- return true;
1507
- }
1508
- keyboard.set(next);
1509
- announce(next, { phase: "start" });
1510
- return true;
1511
- }
1512
- function step(current, key, command) {
1513
- const cursor = cellOf(navigate(key, current.session.cursor));
1514
- if (cursor === null) return;
1515
- const session = moveKeyboardCursor(current.session, cursor, interactionOptions());
1516
- if (session === current.session) return;
1517
- const next = {
1518
- ...current,
1519
- check: checkOf(session),
1520
- session
1521
- };
1522
- keyboard.set(next);
1523
- moveFocus(focusOfSession(session), command);
1524
- announce(next, { phase: "step" });
1525
- }
1526
- /** Grabs the other edge, starting the resize over from the event as it was. */
1527
- function switchEdge(current, command) {
1528
- const { cell, event, session } = current;
1529
- if (event === null || !session.cause.startsWith("resize")) return;
1530
- const cause = session.cause === "resize-end" ? "resize-start" : "resize-end";
1531
- const restarted = startKeyboardSession({
1532
- cause,
1533
- cell,
1534
- event
1535
- }, interactionOptions());
1536
- const next = {
1537
- ...current,
1538
- check: null,
1539
- session: restarted
1540
- };
1541
- keyboard.set(next);
1542
- moveFocus(focusOfSession(restarted), command);
1543
- announce(next, { phase: "start" });
1544
- }
1545
- function cancel(current, command) {
1546
- keyboard.set(null);
1547
- moveFocus(current.origin, command);
1548
- announce(current, { phase: "cancel" });
1549
- }
1550
- function commit(current, command) {
1551
- const proposal = keyboardSessionProposal(current.session);
1552
- if (proposal === null) {
1553
- cancel(current, command);
1554
- return;
1555
- }
1556
- keyboard.set(null);
1557
- const focused = read().focus;
1558
- const { definition } = view();
1559
- const owned = () => keyboard.get() === null && getView()?.definition === definition && sameFocus(read().focus, focused);
1560
- actions.proposeEventChange(proposal, keyboardInput).then((result) => {
1561
- if (result.status === "committed") {
1562
- const { eventId, proposed } = result.change;
1563
- if (eventId !== null && proposed !== null && owned()) {
1564
- const { cursor } = current.session;
1565
- moveFocus({
1566
- date: dateOn(proposed, cursor.date),
1567
- eventId,
1568
- kind: "event",
1569
- resourceId: resourceOn(proposed, cursor.resourceId)
1570
- }, command);
1571
- }
1572
- announce(current, {
1573
- phase: "commit",
1574
- proposed,
1575
- warnings: result.change.warnings
1576
- });
1577
- } else {
1578
- if (owned()) moveFocus(current.origin, command);
1579
- announce(current, {
1580
- phase: "reject",
1581
- reason: result.reason,
1582
- ...result.error === void 0 ? {} : { error: result.error }
1583
- });
1584
- }
1585
- });
1586
- }
1587
- /** `date` when `placement` covers it, else the placement's first date. */
1588
- function dateOn(placement, date) {
1589
- const { timeZone } = view().environment;
1590
- const wall = (point) => point instanceof Temporal.Instant ? point.toZonedDateTimeISO(timeZone).toPlainDateTime() : point;
1591
- 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()];
1592
- return Temporal.PlainDate.compare(first, date) <= 0 && Temporal.PlainDate.compare(date, last) <= 0 ? date : first;
1593
- }
1594
- /**
1595
- * The resource focus follows a placement into: `resourceId` when the placement shows there, else
1596
- * the first resource it books that is visible, so the copy focus moves to renders, even scrolled
1597
- * out of view, and the unassigned bucket when it books none.
1598
- */
1599
- function resourceOn(placement, resourceId) {
1600
- const booked = placement.resourceIds;
1601
- if (resourceId === void 0 || showsInResource(booked, resourceId)) return resourceId;
1602
- if (booked.length === 0) return null;
1603
- const tree = getResources();
1604
- const visible = tree === null ? [] : visibleResources(tree, read().expandedResourceIds);
1605
- return booked.find((id) => visible.some((row) => row.id === id));
1606
- }
1607
- function onGrabbedKey(current, event) {
1608
- const key = navigationKeys[event.key];
1609
- const command = keyCommand(event);
1610
- if (key !== void 0) {
1611
- step(current, key, command);
1612
- return true;
1613
- }
1614
- switch (event.key) {
1615
- case "Enter":
1616
- commit(current, command);
1617
- return true;
1618
- case " ":
1619
- if (event.shiftKey) switchEdge(current, command);
1620
- else commit(current, command);
1621
- return true;
1622
- case "Escape":
1623
- cancel(current, command);
1624
- return true;
1625
- case "Tab":
1626
- cancel(current, command);
1627
- return false;
1628
- default: return false;
1629
- }
1630
- }
1631
- function onIdleKey(focus, event) {
1632
- const key = navigationKeys[event.key];
1633
- const command = keyCommand(event);
1634
- if (key !== void 0) return !event.shiftKey && apply(navigate(key, focus), command);
1635
- if (focus === null) return false;
1636
- switch (event.key) {
1637
- case "Enter": return focus.kind !== "event" && !event.shiftKey && apply(navigate("enter", focus), command);
1638
- case "Escape": return focus.kind === "event" && apply(navigate("exit", focus), command);
1639
- case " ": return !isReadOnly && grab(focus, focus.kind !== "event" ? "create" : event.shiftKey ? "resize-end" : "move", command);
1640
- default: return false;
1641
- }
1642
- }
1643
- return Object.freeze({
1644
- onBlur(event) {
1645
- if (keyboard.get() === null) return;
1646
- const region = event.currentTarget;
1647
- const next = event.relatedTarget;
1648
- if (next !== null && region.contains(next)) return;
1649
- const command = {
1650
- event: event.nativeEvent,
1651
- reason: "focus-change"
1652
- };
1653
- setTimeout(() => {
1654
- const current = keyboard.get();
1655
- if (current !== null && !region.contains(document.activeElement)) cancel(current, command);
1656
- });
1657
- },
1658
- onKeyDown(event) {
1659
- if (event.defaultPrevented || event.nativeEvent.isComposing) return;
1660
- if (event.altKey || event.ctrlKey || event.metaKey) return;
1661
- const current = keyboard.get();
1662
- if (!(current === null ? onIdleKey(roving.focusAt(event.target), event) : onGrabbedKey(current, event))) return;
1663
- event.preventDefault();
1664
- if (event.key === "Escape") event.stopPropagation();
1665
- }
1666
- });
1667
- }
1668
876
  /**
1669
877
  * Keyboard navigation and keyboard move, resize, and create for a view; spread the handlers on
1670
878
  * the element around its focusable cells and events (see `useRovingFocus`).
@@ -1694,15 +902,35 @@ function useCalendarKeyboard(options = {}) {
1694
902
  resources
1695
903
  };
1696
904
  });
1697
- const handlers = useMemo(() => createKeyboardHandlers(interaction, view, () => latest.current.options, () => latest.current.resources), [interaction, view]);
1698
- const { keyboard } = interaction;
1699
- useEffect(() => () => keyboard.set(null), [keyboard]);
1700
- 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]);
1701
912
  }
1702
913
  const selectSession = (session) => session;
1703
914
  function useCalendarInteraction(selector = selectSession, options) {
1704
915
  return useStateSelector(useInteractionRuntime().keyboard.grabs, (grab) => selector(grab?.session ?? null, grab?.check ?? null), options);
1705
916
  }
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
+ }
1706
934
  // src/selectors.ts
1707
935
  /**
1708
936
  * Selects from the calendar's focus for a view's item, such as whether a slot cursor sits on this
@@ -1733,11 +961,10 @@ function useAnchorDateRequests(listener) {
1733
961
  useInsertionEffect(() => {
1734
962
  latest.current = listener;
1735
963
  });
1736
- useLayoutEffect(() => requests((slice, value) => {
1737
- if (slice !== "anchorDate") return;
1738
- const date = value;
1739
- latest.current(date, rangeOf(date));
1740
- }), [rangeOf, requests]);
964
+ useLayoutEffect(() => subscribeAnchorDateRequests({
965
+ rangeOf,
966
+ requests
967
+ }, (date, range) => latest.current(date, range)), [rangeOf, requests]);
1741
968
  }
1742
969
  // src/views.ts
1743
970
  function defineCalendarView(view) {
@@ -1748,4 +975,4 @@ function defineCalendarView(view) {
1748
975
  strategy: view.strategy
1749
976
  });
1750
977
  }
1751
- export { createCalendar, createCalendarStore, defineCalendarView, useAnchorDateRequests, useBusyResources, useCalendarAnnotations, useCalendarAnnouncer, useCalendarAvailability, useCalendarDraft, useCalendarDraftReporter, useCalendarFocus, useCalendarHistory, useCalendarHistoryShortcuts, useCalendarInteraction, useCalendarKeyboard, useCalendarSelection, useClosedDates, useDraftBusy, useNow, useResourceExpansion, useResourceStatus, useRovingFocus, useTimeGridAnnotations, useTimeGridAvailability, useTimelineAvailability, useVisibleResources };
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 };