@moltenship/calendar-primitives 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,5 +1,5 @@
1
- import { createSystemClock, instantInterval, plainDateInterval, plainDateTimeInterval } from "@moltenship/calendar-temporal";
2
- import { applyEventOverlay, createAnnotationSnapshot, createAvailabilitySnapshot, createEventSnapshotCache, createEventTransactions, createResourceTree, formatPlacementRange, readOnlyPolicy, resolveSecondaryTimeZones, resolveViewInstantRange, resolveViewLoadRange } from "@moltenship/calendar-core";
1
+ import { createSystemClock, instantInterval, plainDateInterval, plainDateIntervalContains, plainDateTimeInterval } from "@moltenship/calendar-temporal";
2
+ import { anchorShowingDate, applyEventOverlay, busyResources, createAnnotationSnapshot, createAvailabilitySnapshot, createEventSnapshotCache, createEventTransactions, createResourceTree, fitsAvailability, formatPlacementRange, keyboardSessionProposal, moveKeyboardCursor, readOnlyPolicy, resolveSecondaryTimeZones, resolveViewInstantRange, resolveViewLoadRange, sameFocus, showsInResource, slotDuration, startKeyboardSession, visibleResources } from "@moltenship/calendar-core";
3
3
  import { definePrimitive, dispatch } from "@ui-sdk/core";
4
4
  // src/agent.ts
5
5
  function describe(value) {
@@ -242,6 +242,47 @@ function agentEventLabel(event, timeZone) {
242
242
  function eventLabel(event, environment) {
243
243
  return agentEventLabel(describeAgentEvent(event, environment), environment.timeZone);
244
244
  }
245
+ // src/anchor-requests.ts
246
+ /**
247
+ * Calls `listener` whenever something asks the root for an anchor date, until the returned
248
+ * cleanup runs: Previous, Next, Today, keys paging past the view, or `setAnchorDate`, even a date
249
+ * that is already the anchor. `range` is what the view on screen shows for that date (`null`
250
+ * without one), so a view can tell a request for the range it has, as Today in this week, from
251
+ * one that moves it.
252
+ */
253
+ function subscribeAnchorDateRequests({ rangeOf, requests }, listener) {
254
+ return requests((slice, value) => {
255
+ if (slice !== "anchorDate") return;
256
+ const date = value;
257
+ listener(date, rangeOf(date));
258
+ });
259
+ }
260
+ // src/report-error.ts
261
+ /** Reports an application callback's error without failing what it was told about. */
262
+ function reportCallbackError(error) {
263
+ if (typeof reportError === "function") reportError(error);
264
+ else console.error(error);
265
+ }
266
+ // src/listeners.ts
267
+ function createListeners() {
268
+ const entries = /* @__PURE__ */ new Set();
269
+ return Object.freeze({
270
+ notify() {
271
+ for (const entry of entries) try {
272
+ entry.listener();
273
+ } catch (error) {
274
+ reportCallbackError(error);
275
+ }
276
+ },
277
+ subscribe(listener) {
278
+ const entry = { listener };
279
+ entries.add(entry);
280
+ return () => {
281
+ entries.delete(entry);
282
+ };
283
+ }
284
+ });
285
+ }
245
286
  // src/announcer-channel.ts
246
287
  function buildMessage(messages, update, context) {
247
288
  const build = messages[update.phase];
@@ -291,67 +332,23 @@ function createAnnouncerChannel(getEnvironment, getResources) {
291
332
  say
292
333
  });
293
334
  }
294
- // src/calendar-types.ts
295
- /** The ids a root's chrome parts point at each other with. */
296
- function createCalendarPartIds(instanceId) {
297
- return Object.freeze({
298
- frame: `${instanceId}-frame`,
299
- title: `${instanceId}-title`,
300
- viewport: `${instanceId}-viewport`
301
- });
302
- }
303
- // src/clock.ts
304
- /** The clock a root reads when it has neither `now` nor `clock`. */
305
- const systemClock = createSystemClock();
306
- /** How often a root samples its clock for `today`. */
307
- const TODAY_SAMPLE_INTERVAL_MS = 6e4;
308
- /** Samples `clock` every `intervalMs` while subscribed. */
309
- function createClockTicker(clock, intervalMs) {
310
- let current;
311
- return Object.freeze({
312
- getSnapshot: () => current ??= clock.instant(),
313
- subscribe: (onChange) => {
314
- const sample = () => {
315
- const next = clock.instant();
316
- if (current?.equals(next) === true) return;
317
- current = next;
318
- onChange();
319
- };
320
- sample();
321
- const timer = setInterval(sample, intervalMs);
322
- return () => clearInterval(timer);
323
- }
324
- });
325
- }
326
- /** The clock a source samples: its own, or the system's. */
327
- function clockOf(source) {
328
- return source?.clock ?? systemClock;
329
- }
330
- // src/listeners.ts
331
- function createListeners() {
332
- const entries = /* @__PURE__ */ new Set();
333
- return Object.freeze({
334
- notify() {
335
- for (const entry of entries) entry.listener();
336
- },
337
- subscribe(listener) {
338
- const entry = { listener };
339
- entries.add(entry);
340
- return () => {
341
- entries.delete(entry);
342
- };
343
- }
344
- });
345
- }
346
- // src/draft-store.ts
347
- function createDraftStore() {
348
- let draft = null;
335
+ /** Creates the text of one mounted live region; see `AnnouncerLiveText`. */
336
+ function createAnnouncerLiveText() {
337
+ let spoken = {
338
+ repeat: false,
339
+ text: ""
340
+ };
341
+ let snapshot = "";
349
342
  const listeners = createListeners();
350
343
  return Object.freeze({
351
- getSnapshot: () => draft,
352
- set(next) {
353
- if (next === draft) return;
354
- draft = next;
344
+ getServerSnapshot: () => "",
345
+ getSnapshot: () => snapshot,
346
+ speak(text) {
347
+ spoken = {
348
+ repeat: spoken.text === text && !spoken.repeat,
349
+ text
350
+ };
351
+ snapshot = spoken.repeat ? `${text}\u00a0` : text;
355
352
  listeners.notify();
356
353
  },
357
354
  subscribe: listeners.subscribe
@@ -417,6 +414,703 @@ const sameZone = (left, right) => Object.is(left, right) || isRecord(left) && is
417
414
  function sameSecondaryTimeZones(left, right) {
418
415
  return Array.isArray(left) && Array.isArray(right) ? sameList(left, right, sameZone) : sameZone(left, right);
419
416
  }
417
+ // src/busy.ts
418
+ function sameIds(left, right) {
419
+ return left === right || left !== void 0 && right !== void 0 && sameElements(left, right);
420
+ }
421
+ function sameInterval(left, right) {
422
+ 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();
423
+ }
424
+ const nothingBusy = /* @__PURE__ */ new Map();
425
+ /**
426
+ * A memoized query for the resources busy during a range, with their events; free ones are
427
+ * absent. Call it with the root's events, pending changes included, as often as a framework
428
+ * renders: it queries again only when the events, the range or the query change, the range and
429
+ * the resource IDs by value, so ones made inline cost nothing. A `null` range asks nothing.
430
+ */
431
+ function createBusyResourcesQuery() {
432
+ let held;
433
+ return (events, range, { exclude, resourceIds, timeZone }) => {
434
+ if (held !== void 0 && held.events === events && held.exclude === exclude && held.timeZone === timeZone && sameInterval(held.range, range) && sameIds(held.resourceIds, resourceIds)) return held.busy;
435
+ const busy = range === null ? nothingBusy : busyResources(events, range, {
436
+ ...exclude == null ? {} : { exclude },
437
+ ...resourceIds === void 0 ? {} : { resourceIds },
438
+ timeZone
439
+ });
440
+ held = {
441
+ busy,
442
+ events,
443
+ exclude,
444
+ range,
445
+ resourceIds,
446
+ timeZone
447
+ };
448
+ return busy;
449
+ };
450
+ }
451
+ /** Each draft's busy resources, worked out once for every resource that asks. */
452
+ const draftBusy = /* @__PURE__ */ new WeakMap();
453
+ function busyFor(draft, events, timeZone) {
454
+ const cached = draftBusy.get(draft);
455
+ if (cached?.events === events) return cached.busy;
456
+ const busy = busyResources(events, draft.proposed, {
457
+ ...draft.eventId === null ? {} : { exclude: draft.eventId },
458
+ timeZone
459
+ });
460
+ draftBusy.set(draft, {
461
+ busy,
462
+ events
463
+ });
464
+ return busy;
465
+ }
466
+ const noEvents = Object.freeze([]);
467
+ function sameBusy(left, right) {
468
+ 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]);
469
+ }
470
+ /**
471
+ * One resource's query of the draft (`CalendarInteractionRuntime.draft`): the busy events that
472
+ * overlap the draft's time, the draft's own event aside, and whether the time falls outside the
473
+ * resource's hours; `null` without a draft, or for a `null` resource. The draft's busy resources
474
+ * are worked out once per draft and events for every resource that asks, and the result keeps its
475
+ * identity while the answer is the same, so a framework re-renders only when it changes.
476
+ */
477
+ function createDraftBusyQuery() {
478
+ let last = null;
479
+ return (draft, events, availability, resourceId) => {
480
+ if (draft === null || resourceId === null) return last = null;
481
+ const { timeZone } = availability;
482
+ const next = {
483
+ events: busyFor(draft, events, timeZone).get(resourceId) ?? noEvents,
484
+ outsideHours: !fitsAvailability(draft.proposed, availability.forResource(resourceId), timeZone)
485
+ };
486
+ if (!sameBusy(last, next)) last = next;
487
+ return last;
488
+ };
489
+ }
490
+ // src/calendar-types.ts
491
+ /** The ids a root's chrome parts point at each other with. */
492
+ function createCalendarPartIds(instanceId) {
493
+ return Object.freeze({
494
+ frame: `${instanceId}-frame`,
495
+ title: `${instanceId}-title`,
496
+ viewport: `${instanceId}-viewport`
497
+ });
498
+ }
499
+ // src/clock.ts
500
+ /** The clock a root reads when it has neither `now` nor `clock`. */
501
+ const systemClock = createSystemClock();
502
+ /** How often a root samples its clock for `today`. */
503
+ const TODAY_SAMPLE_INTERVAL_MS = 6e4;
504
+ /**
505
+ * Samples `clock` every `intervalMs` while subscribed: one timer for every subscriber, started by
506
+ * the first and stopped by the last.
507
+ */
508
+ function createClockTicker(clock, intervalMs) {
509
+ const listeners = createListeners();
510
+ let current;
511
+ let subscriptions = 0;
512
+ let timer;
513
+ const sample = () => {
514
+ const next = clock.instant();
515
+ if (current?.equals(next) === true) return;
516
+ current = next;
517
+ listeners.notify();
518
+ };
519
+ return Object.freeze({
520
+ getSnapshot: () => current ??= clock.instant(),
521
+ subscribe: (onChange) => {
522
+ const unsubscribe = listeners.subscribe(onChange);
523
+ subscriptions += 1;
524
+ sample();
525
+ timer ??= setInterval(sample, intervalMs);
526
+ let subscribed = true;
527
+ return () => {
528
+ if (!subscribed) return;
529
+ subscribed = false;
530
+ unsubscribe();
531
+ subscriptions -= 1;
532
+ if (subscriptions === 0) {
533
+ clearInterval(timer);
534
+ timer = void 0;
535
+ }
536
+ };
537
+ }
538
+ });
539
+ }
540
+ /** The clock a source samples: its own, or the system's. */
541
+ function clockOf(source) {
542
+ return source?.clock ?? systemClock;
543
+ }
544
+ // src/draft-store.ts
545
+ function createDraftStore() {
546
+ let draft = null;
547
+ const listeners = createListeners();
548
+ return Object.freeze({
549
+ getSnapshot: () => draft,
550
+ set(next) {
551
+ if (next === draft) return;
552
+ draft = next;
553
+ listeners.notify();
554
+ },
555
+ subscribe: listeners.subscribe
556
+ });
557
+ }
558
+ /** Each keyboard session as a draft, the same object for as long as the session is. */
559
+ const sessionDrafts = /* @__PURE__ */ new WeakMap();
560
+ function draftOf(session) {
561
+ let draft = sessionDrafts.get(session);
562
+ if (draft === void 0) {
563
+ draft = Object.freeze({
564
+ eventId: session.eventId,
565
+ proposed: session.proposed
566
+ });
567
+ sessionDrafts.set(session, draft);
568
+ }
569
+ return draft;
570
+ }
571
+ const noDraft = () => null;
572
+ /**
573
+ * The change being drafted, by keyboard or pointer: the keyboard's session while one is in
574
+ * progress, else the pointer's draft. The server and hydration read none.
575
+ */
576
+ function createDraftSource(keyboard, pointerDraft) {
577
+ return Object.freeze({
578
+ getServerSnapshot: noDraft,
579
+ getSnapshot: () => {
580
+ const session = keyboard.grabs.getSnapshot()?.session;
581
+ return session === void 0 ? pointerDraft.getSnapshot() : draftOf(session);
582
+ },
583
+ subscribe: (listener) => {
584
+ const stops = [keyboard.grabs.subscribe(listener), pointerDraft.subscribe(listener)];
585
+ return () => {
586
+ for (const stop of stops) stop();
587
+ };
588
+ }
589
+ });
590
+ }
591
+ // src/history.ts
592
+ /**
593
+ * What the server and hydration read: nothing recorded yet. A plain literal, so a bundler drops
594
+ * it from a calendar that doesn't use the history.
595
+ */
596
+ const serverSnapshot = {
597
+ future: [],
598
+ latest: null,
599
+ past: [],
600
+ pending: null
601
+ };
602
+ /** Whether a change is still validating or saving: a saved one waiting for events is done. */
603
+ function isUnsettled(changes) {
604
+ for (const { phase } of changes.values()) if (phase !== "awaiting-events") return true;
605
+ return false;
606
+ }
607
+ /**
608
+ * Binds an event history to a root, as a store of `CalendarHistory` values: undo and redo propose
609
+ * the inverse through the root's `proposeEventChange`, against the events `getOptions` gives, and
610
+ * with its `messages` their outcomes are spoken through the root's announcer channel. The
611
+ * snapshot keeps its identity until the history changes; the server snapshot is an empty history.
612
+ * `getOptions` is read whenever a command runs and when it ends, so the binding is made once per
613
+ * root and history.
614
+ */
615
+ function bindCalendarHistory({ actions, announcements, changes }, history, getOptions) {
616
+ /**
617
+ * Resolves once no change is validating or saving, after the turn in which the last one ended,
618
+ * so its result has reached `onEventChangeResult` and the history.
619
+ */
620
+ function whenSettled() {
621
+ if (!isUnsettled(changes.getSnapshot())) return void 0;
622
+ return new Promise((resolve) => {
623
+ const unsubscribe = changes.subscribe(() => {
624
+ if (isUnsettled(changes.getSnapshot())) return;
625
+ unsubscribe();
626
+ setTimeout(resolve);
627
+ });
628
+ });
629
+ }
630
+ function run(direction, { input } = {}) {
631
+ let checked;
632
+ const getEvents = () => {
633
+ const { events } = getOptions();
634
+ checked ??= events;
635
+ return events;
636
+ };
637
+ const context = {
638
+ getEvents,
639
+ input,
640
+ propose: actions.proposeEventChange,
641
+ whenSettled
642
+ };
643
+ return history[direction](context).then((outcome) => {
644
+ const { events, messages } = getOptions();
645
+ const build = messages?.[direction];
646
+ if (build !== void 0) {
647
+ const eventId = outcome.status === "empty" ? null : outcome.step.eventId;
648
+ const event = eventId === null ? void 0 : events.get(eventId) ?? checked?.get(eventId);
649
+ try {
650
+ announcements.say((where) => build(outcome, {
651
+ ...where,
652
+ event
653
+ }));
654
+ } catch (error) {
655
+ reportCallbackError(error);
656
+ }
657
+ }
658
+ return outcome;
659
+ });
660
+ }
661
+ const redo = (options) => run("redo", options);
662
+ const undo = (options) => run("undo", options);
663
+ const bound = (snapshot) => Object.freeze({
664
+ ...snapshot,
665
+ canRedo: snapshot.future.length > 0,
666
+ canUndo: snapshot.past.length > 0,
667
+ redo,
668
+ undo
669
+ });
670
+ let held;
671
+ let server;
672
+ return Object.freeze({
673
+ getServerSnapshot: () => server ??= bound(serverSnapshot),
674
+ getSnapshot: () => {
675
+ const snapshot = history.getSnapshot();
676
+ if (held?.snapshot !== snapshot) held = {
677
+ bound: bound(snapshot),
678
+ snapshot
679
+ };
680
+ return held.bound;
681
+ },
682
+ subscribe: (listener) => history.subscribe(listener)
683
+ });
684
+ }
685
+ // src/history-shortcuts.ts
686
+ const defaultUndo = ["Mod+Z"];
687
+ const defaultRedo = ["Shift+Mod+Z", "Ctrl+Y"];
688
+ const keyboardInput$1 = { input: "keyboard" };
689
+ /**
690
+ * Where a key belongs to something else: text the browser undoes in its own field, and dialogs,
691
+ * menus and lists inside the calendar, which handle their own keys.
692
+ */
693
+ const ownKeys = "input, textarea, select, [contenteditable]:not([contenteditable=\"false\"]), [role=\"textbox\"], [role=\"dialog\"], [role=\"alertdialog\"], [role=\"menu\"], [role=\"listbox\"]";
694
+ function isApplePlatform() {
695
+ const { platform, userAgentData } = navigator;
696
+ return /mac|iphone|ipad|ipod/i.test(userAgentData?.platform ?? platform);
697
+ }
698
+ /** Whether `event` is `binding`: exactly its modifiers, and its key by name or position. */
699
+ function matches(event, binding, apple) {
700
+ const parts = binding.split("+").map((part) => part.trim().toLowerCase());
701
+ const key = parts.pop();
702
+ if (key === void 0 || key === "") return false;
703
+ let ctrl = false;
704
+ let meta = false;
705
+ let shift = false;
706
+ let alt = false;
707
+ for (const modifier of parts) if (modifier === "mod") {
708
+ if (apple) meta = true;
709
+ else ctrl = true;
710
+ } else if (modifier === "ctrl" || modifier === "control") ctrl = true;
711
+ else if (modifier === "meta" || modifier === "cmd" || modifier === "command") meta = true;
712
+ else if (modifier === "shift") shift = true;
713
+ else if (modifier === "alt" || modifier === "option") alt = true;
714
+ else return false;
715
+ if (event.ctrlKey !== ctrl || event.metaKey !== meta || event.shiftKey !== shift || event.altKey !== alt) return false;
716
+ const typed = event.key.toLowerCase();
717
+ if (typed === key) return true;
718
+ if (/^[a-z0-9]$/.test(typed)) return false;
719
+ if (/^[a-z]$/.test(key)) return event.code === `Key${key.toUpperCase()}`;
720
+ return /^[0-9]$/.test(key) && event.code === `Digit${key}`;
721
+ }
722
+ /**
723
+ * Whether something on the key's path inside `scope`, from its target out, handles keys of its
724
+ * own: a field, also inside a web component's shadow root, or a dialog, menu or list. A dialog
725
+ * around the whole calendar doesn't count.
726
+ */
727
+ function ownsKeys(path, scope) {
728
+ for (const node of path) {
729
+ if (node === scope) return false;
730
+ if (!(node instanceof Element)) continue;
731
+ if (node instanceof HTMLElement && node.isContentEditable || node.matches(ownKeys)) return true;
732
+ }
733
+ return false;
734
+ }
735
+ /**
736
+ * Listens for a calendar's undo and redo keys until the returned cleanup runs: Mod+Z undoes, and
737
+ * Shift+Mod+Z or Ctrl+Y redoes, where Mod is ⌘ on Apple platforms and Ctrl elsewhere. One
738
+ * `keydown` listener on the document acts on keys whose target is inside the scope, after the
739
+ * page's own handlers, a framework's delegated ones included. Keys never undo in a text field,
740
+ * where the browser undoes the text, or in a dialog, menu or list inside the scope, nor during a
741
+ * keyboard or pointer gesture of the root's, nor once something else handled them. Commands pass
742
+ * `{ input: "keyboard" }`.
743
+ *
744
+ * `getConfig` is read when a key arrives, so a scope that mounts after the listener, or remounts,
745
+ * keeps its keys, and a portal outside it, such as a dialog, never reaches them.
746
+ */
747
+ function attachCalendarHistoryShortcuts({ keyboard, pointerDraft }, getConfig) {
748
+ const apple = isApplePlatform();
749
+ const listener = (event) => {
750
+ const { history, redo = defaultRedo, scope, undo = defaultUndo } = getConfig();
751
+ if (event.defaultPrevented || event.isComposing || scope === null) return;
752
+ const path = event.composedPath();
753
+ if (!path.includes(scope)) return;
754
+ const direction = undo.some((binding) => matches(event, binding, apple)) ? "undo" : redo.some((binding) => matches(event, binding, apple)) ? "redo" : null;
755
+ if (direction === null || ownsKeys(path, scope)) return;
756
+ if (keyboard.get() !== null || pointerDraft.getSnapshot() !== null) return;
757
+ event.preventDefault();
758
+ try {
759
+ Promise.resolve(history[direction](keyboardInput$1)).catch(reportCallbackError);
760
+ } catch (error) {
761
+ reportCallbackError(error);
762
+ }
763
+ };
764
+ document.addEventListener("keydown", listener);
765
+ return () => document.removeEventListener("keydown", listener);
766
+ }
767
+ // src/interaction.ts
768
+ /** Time-grid slots when a view doesn't choose its own, as in the pointer layer. */
769
+ const DEFAULT_SNAP = Object.freeze({
770
+ increment: 15,
771
+ smallestUnit: "minute"
772
+ });
773
+ // src/keyboard.ts
774
+ const DEFAULT_CREATE_DURATION = { hours: 1 };
775
+ /**
776
+ * What a key tells the state handlers it changes: its reason, and the key itself, from which the
777
+ * store works out the source, the keyboard's, or the agent's while an agent's step presses it.
778
+ */
779
+ function keyCommand(event) {
780
+ return {
781
+ event,
782
+ reason: "keyboard-navigation"
783
+ };
784
+ }
785
+ const keyboardInput = Object.freeze({ input: "keyboard" });
786
+ const navigationKeys = {
787
+ ArrowDown: "down",
788
+ ArrowLeft: "left",
789
+ ArrowRight: "right",
790
+ ArrowUp: "up",
791
+ End: "end",
792
+ Home: "home",
793
+ PageDown: "page-down",
794
+ PageUp: "page-up"
795
+ };
796
+ /**
797
+ * The keyboard of one rendered active view: navigation, and keyboard move, resize and create.
798
+ * `getOptions` and `getResources` (the root's resource tree) are read whenever a key arrives, so
799
+ * the controller is created once per root and view and never again for new options.
800
+ *
801
+ * - Arrow keys, Home, End, Page Up, and Page Down move focus through the view's
802
+ * `getSpatialNavigation`, navigating the view when focus leaves it. Enter moves into a cell's
803
+ * events and Escape back out.
804
+ * - Space grabs the focused event to move it, or the focused cell to create an event there;
805
+ * Shift+Space grabs an event's end to resize it, and again switches to its start. Navigation
806
+ * keys then step the gesture, Enter or Space commits it through `proposeEventChange`, and
807
+ * Escape, Tab, or leaving the view cancels it. On a read-only root, Space grabs nothing.
808
+ *
809
+ * Every phase is announced through the root's announcer channel. A view that unmounts mid-gesture
810
+ * lets go of it with `interaction.keyboard.set(null)`.
811
+ */
812
+ function createCalendarKeyboard({ actions, announcements, isReadOnly, keyboard, read }, { getView, roving }, getOptions, getResources) {
813
+ const getSnap = () => getOptions().snap ?? DEFAULT_SNAP;
814
+ const view = () => getView();
815
+ function navigate(command, focus) {
816
+ const { definition, environment, options, projection, range } = view();
817
+ return definition.strategy.getSpatialNavigation?.({
818
+ command,
819
+ environment,
820
+ focus,
821
+ options,
822
+ projection,
823
+ range,
824
+ snap: getSnap()
825
+ }) ?? null;
826
+ }
827
+ /** The cell a navigation result names, for keys that move a cell. */
828
+ function cellOf(result) {
829
+ return result !== null && "focus" in result && result.focus.kind !== "event" ? result.focus : null;
830
+ }
831
+ function interactionOptions() {
832
+ return {
833
+ snap: getSnap(),
834
+ timeZone: view().environment.timeZone
835
+ };
836
+ }
837
+ /**
838
+ * Navigates the view by whole ranges until it shows `date`. `command` carries the key, or the
839
+ * focus change, behind it, so the state handlers hear a person's keys as the keyboard's.
840
+ */
841
+ function reveal(date, command) {
842
+ const { definition, environment, options, range } = view();
843
+ if (plainDateIntervalContains(range, date)) return;
844
+ const { anchorDate } = read();
845
+ actions.setAnchorDate(anchorShowingDate(definition.strategy, anchorDate, date, environment, options), command);
846
+ }
847
+ /** Moves the calendar's focus and, once the view renders it, DOM focus. */
848
+ function moveFocus(focus, command) {
849
+ if (sameFocus(focus, read().focus)) {
850
+ roving.focusTabStop("now");
851
+ return;
852
+ }
853
+ roving.focusTabStop("after-update");
854
+ actions.setFocus(focus, command);
855
+ if (focus !== null) reveal(focus.date, command);
856
+ }
857
+ function apply(result, command) {
858
+ if (result === null) return false;
859
+ if ("focus" in result) moveFocus(result.focus, command);
860
+ else {
861
+ const { definition, options } = view();
862
+ roving.focusTabStop("after-update");
863
+ if (result.page < 0) roving.enterFromEnd();
864
+ actions.setAnchorDate(definition.strategy.navigate(read().anchorDate, result.page, options), command);
865
+ actions.setFocus(null, command);
866
+ }
867
+ return true;
868
+ }
869
+ function announce(grab, detail) {
870
+ const { check, session } = grab;
871
+ announcements.announcer.announce({
872
+ cause: session.cause,
873
+ event: grab.event,
874
+ input: "keyboard",
875
+ original: session.original,
876
+ proposed: session.proposed,
877
+ ...detail.phase === "start" || detail.phase === "step" ? { check } : void 0,
878
+ ...detail
879
+ });
880
+ }
881
+ /** What the root's policies would say to committing `session` now, as its preview shows. */
882
+ function checkOf(session) {
883
+ const proposal = keyboardSessionProposal(session);
884
+ return proposal === null ? null : actions.checkEventChange(proposal, keyboardInput);
885
+ }
886
+ /**
887
+ * Follows the grabbed event into the cursor's date and resource, or a create's cell. A move out
888
+ * of the event's last copy in a resource, as into the unassigned bucket, follows it to a resource
889
+ * it still shows in.
890
+ */
891
+ function focusOfSession(session) {
892
+ const { cursor, eventId, proposed } = session;
893
+ return eventId === null ? cursor : {
894
+ date: cursor.date,
895
+ eventId,
896
+ kind: "event",
897
+ resourceId: resourceOn(proposed, cursor.resourceId)
898
+ };
899
+ }
900
+ /** A slot create starts `createDuration` long: its cursor steps later, as a drag would. */
901
+ function startCreate(cell) {
902
+ let session = startKeyboardSession({
903
+ cause: "create",
904
+ cell
905
+ }, interactionOptions());
906
+ if (cell.kind !== "slot") return session;
907
+ const later = getOptions().axis !== "inline" ? "down" : view().environment.direction === "rtl" ? "left" : "right";
908
+ const duration = Temporal.Duration.from(getOptions().createDuration ?? DEFAULT_CREATE_DURATION);
909
+ const slots = Math.round(duration.total({ unit: "minutes" }) / slotDuration(getSnap()).total({ unit: "minutes" }));
910
+ for (let step = 1; step < slots; step += 1) {
911
+ const cursor = cellOf(navigate(later, session.cursor));
912
+ if (cursor === null) break;
913
+ session = moveKeyboardCursor(session, cursor, interactionOptions());
914
+ }
915
+ return session;
916
+ }
917
+ function grab(focus, cause, command) {
918
+ if (focus.kind !== "event") {
919
+ if (cause !== "create") return false;
920
+ const session = startCreate(focus);
921
+ const next = {
922
+ cell: focus,
923
+ check: checkOf(session),
924
+ event: null,
925
+ origin: focus,
926
+ session
927
+ };
928
+ keyboard.set(next);
929
+ moveFocus(focusOfSession(session), command);
930
+ announce(next, { phase: "start" });
931
+ return true;
932
+ }
933
+ if (cause === "create") return false;
934
+ const event = view().events.get(focus.eventId);
935
+ const cell = cellOf(navigate("exit", focus));
936
+ if (event === void 0 || cell === null) return false;
937
+ const next = {
938
+ cell,
939
+ check: null,
940
+ event,
941
+ origin: focus,
942
+ session: startKeyboardSession({
943
+ cause,
944
+ cell,
945
+ event
946
+ }, interactionOptions())
947
+ };
948
+ if (event.isReadOnly) {
949
+ announce(next, {
950
+ phase: "reject",
951
+ reason: "read-only"
952
+ });
953
+ return true;
954
+ }
955
+ keyboard.set(next);
956
+ announce(next, { phase: "start" });
957
+ return true;
958
+ }
959
+ function step(current, key, command) {
960
+ const cursor = cellOf(navigate(key, current.session.cursor));
961
+ if (cursor === null) return;
962
+ const session = moveKeyboardCursor(current.session, cursor, interactionOptions());
963
+ if (session === current.session) return;
964
+ const next = {
965
+ ...current,
966
+ check: checkOf(session),
967
+ session
968
+ };
969
+ keyboard.set(next);
970
+ moveFocus(focusOfSession(session), command);
971
+ announce(next, { phase: "step" });
972
+ }
973
+ /** Grabs the other edge, starting the resize over from the event as it was. */
974
+ function switchEdge(current, command) {
975
+ const { cell, event, session } = current;
976
+ if (event === null || !session.cause.startsWith("resize")) return;
977
+ const cause = session.cause === "resize-end" ? "resize-start" : "resize-end";
978
+ const restarted = startKeyboardSession({
979
+ cause,
980
+ cell,
981
+ event
982
+ }, interactionOptions());
983
+ const next = {
984
+ ...current,
985
+ check: null,
986
+ session: restarted
987
+ };
988
+ keyboard.set(next);
989
+ moveFocus(focusOfSession(restarted), command);
990
+ announce(next, { phase: "start" });
991
+ }
992
+ function cancel(current, command) {
993
+ keyboard.set(null);
994
+ moveFocus(current.origin, command);
995
+ announce(current, { phase: "cancel" });
996
+ }
997
+ function commit(current, command) {
998
+ const proposal = keyboardSessionProposal(current.session);
999
+ if (proposal === null) {
1000
+ cancel(current, command);
1001
+ return;
1002
+ }
1003
+ keyboard.set(null);
1004
+ const focused = read().focus;
1005
+ const { definition } = view();
1006
+ const owned = () => keyboard.get() === null && getView()?.definition === definition && sameFocus(read().focus, focused);
1007
+ actions.proposeEventChange(proposal, keyboardInput).then((result) => {
1008
+ if (result.status === "committed") {
1009
+ const { eventId, proposed } = result.change;
1010
+ if (eventId !== null && proposed !== null && owned()) {
1011
+ const { cursor } = current.session;
1012
+ moveFocus({
1013
+ date: dateOn(proposed, cursor.date),
1014
+ eventId,
1015
+ kind: "event",
1016
+ resourceId: resourceOn(proposed, cursor.resourceId)
1017
+ }, command);
1018
+ }
1019
+ announce(current, {
1020
+ phase: "commit",
1021
+ proposed,
1022
+ warnings: result.change.warnings
1023
+ });
1024
+ } else {
1025
+ if (owned()) moveFocus(current.origin, command);
1026
+ announce(current, {
1027
+ phase: "reject",
1028
+ reason: result.reason,
1029
+ ...result.error === void 0 ? {} : { error: result.error }
1030
+ });
1031
+ }
1032
+ });
1033
+ }
1034
+ /** `date` when `placement` covers it, else the placement's first date. */
1035
+ function dateOn(placement, date) {
1036
+ const { timeZone } = view().environment;
1037
+ const wall = (point) => point instanceof Temporal.Instant ? point.toZonedDateTimeISO(timeZone).toPlainDateTime() : point;
1038
+ 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()];
1039
+ return Temporal.PlainDate.compare(first, date) <= 0 && Temporal.PlainDate.compare(date, last) <= 0 ? date : first;
1040
+ }
1041
+ /**
1042
+ * The resource focus follows a placement into: `resourceId` when the placement shows there, else
1043
+ * the first resource it books that is visible, so the copy focus moves to renders, even scrolled
1044
+ * out of view, and the unassigned bucket when it books none.
1045
+ */
1046
+ function resourceOn(placement, resourceId) {
1047
+ const booked = placement.resourceIds;
1048
+ if (resourceId === void 0 || showsInResource(booked, resourceId)) return resourceId;
1049
+ if (booked.length === 0) return null;
1050
+ const tree = getResources();
1051
+ const visible = tree === null ? [] : visibleResources(tree, read().expandedResourceIds);
1052
+ return booked.find((id) => visible.some((row) => row.id === id));
1053
+ }
1054
+ function onGrabbedKey(current, event) {
1055
+ const key = navigationKeys[event.key];
1056
+ const command = keyCommand(event);
1057
+ if (key !== void 0) {
1058
+ step(current, key, command);
1059
+ return true;
1060
+ }
1061
+ switch (event.key) {
1062
+ case "Enter":
1063
+ commit(current, command);
1064
+ return true;
1065
+ case " ":
1066
+ if (event.shiftKey) switchEdge(current, command);
1067
+ else commit(current, command);
1068
+ return true;
1069
+ case "Escape":
1070
+ cancel(current, command);
1071
+ return true;
1072
+ case "Tab":
1073
+ cancel(current, command);
1074
+ return false;
1075
+ default: return false;
1076
+ }
1077
+ }
1078
+ function onIdleKey(focus, event) {
1079
+ const key = navigationKeys[event.key];
1080
+ const command = keyCommand(event);
1081
+ if (key !== void 0) return !event.shiftKey && apply(navigate(key, focus), command);
1082
+ if (focus === null) return false;
1083
+ switch (event.key) {
1084
+ case "Enter": return focus.kind !== "event" && !event.shiftKey && apply(navigate("enter", focus), command);
1085
+ case "Escape": return focus.kind === "event" && apply(navigate("exit", focus), command);
1086
+ case " ": return !isReadOnly && grab(focus, focus.kind !== "event" ? "create" : event.shiftKey ? "resize-end" : "move", command);
1087
+ default: return false;
1088
+ }
1089
+ }
1090
+ return Object.freeze({
1091
+ focusOut(event, region) {
1092
+ if (keyboard.get() === null) return;
1093
+ const next = event.relatedTarget;
1094
+ if (next !== null && region.contains(next)) return;
1095
+ const command = {
1096
+ event,
1097
+ reason: "focus-change"
1098
+ };
1099
+ setTimeout(() => {
1100
+ const current = keyboard.get();
1101
+ if (current !== null && !region.contains(document.activeElement)) cancel(current, command);
1102
+ });
1103
+ },
1104
+ keyDown(event, wrapper = event) {
1105
+ if (event.defaultPrevented || event.isComposing) return;
1106
+ if (event.altKey || event.ctrlKey || event.metaKey) return;
1107
+ const current = keyboard.get();
1108
+ if (!(current === null ? onIdleKey(roving.focusAt(event.target), event) : onGrabbedKey(current, event))) return;
1109
+ wrapper.preventDefault();
1110
+ if (event.key === "Escape") wrapper.stopPropagation();
1111
+ }
1112
+ });
1113
+ }
420
1114
  // src/keyboard-store.ts
421
1115
  const noPreview = /* @__PURE__ */ new Map();
422
1116
  function createKeyboardSessionStore() {
@@ -1082,11 +1776,360 @@ function createCalendarPrimitive(config) {
1082
1776
  }
1083
1777
  });
1084
1778
  }
1085
- // src/report-error.ts
1086
- /** Reports an application callback's error without failing what it was told about. */
1087
- function reportCallbackError(error) {
1088
- if (typeof reportError === "function") reportError(error);
1089
- else console.error(error);
1779
+ // src/resource-expansion.ts
1780
+ /** A command's options from what a toggle got: the event a person caused, or a caller's options. */
1781
+ function commandOf(cause) {
1782
+ if (typeof cause !== "object" || cause === null) return { reason: "resource-toggle" };
1783
+ if (cause instanceof Event) return {
1784
+ event: cause,
1785
+ reason: "resource-toggle"
1786
+ };
1787
+ const { event, reason, source } = cause;
1788
+ return {
1789
+ reason: typeof reason === "string" ? reason : "resource-toggle",
1790
+ ...event instanceof Event ? { event } : {},
1791
+ ...typeof source === "string" ? { source } : {}
1792
+ };
1793
+ }
1794
+ /**
1795
+ * Expands and collapses `resourceId` through the root's `expandedResourceIds`. Each command reads
1796
+ * the latest requested state, so consecutive commands in one handler compose, and one that would
1797
+ * change nothing asks nothing.
1798
+ */
1799
+ function createResourceExpansionCommands({ actions, read }, resourceId) {
1800
+ const set = (next, cause) => {
1801
+ const current = read().expandedResourceIds;
1802
+ if (current.includes(resourceId) === next) return;
1803
+ actions.setExpandedResourceIds(next ? [...current, resourceId] : current.filter((id) => id !== resourceId), commandOf(cause));
1804
+ };
1805
+ return Object.freeze({
1806
+ collapse: (cause) => set(false, cause),
1807
+ expand: (cause) => set(true, cause),
1808
+ toggle: (cause) => set(!read().expandedResourceIds.includes(resourceId), cause)
1809
+ });
1810
+ }
1811
+ // src/resource-status.ts
1812
+ /** How often the clock is sampled between changes, in case it jumps. */
1813
+ const SAMPLE_MS = 6e4;
1814
+ function sameMoment(left, right) {
1815
+ return left === right || left !== null && right !== null && left.equals(right);
1816
+ }
1817
+ function sameStatus(left, right) {
1818
+ const [a, b] = [left.availability, right.availability];
1819
+ const [c, d] = [left.busy, right.busy];
1820
+ return sameMoment(left.changesAt, right.changesAt) && (a.available ? b.available && sameMoment(a.closesAt, b.closesAt) : !b.available && a.reason === b.reason && a.label === b.label && sameMoment(a.opensAt, b.opensAt)) && (c.busy ? d.busy && sameMoment(c.freeAt, d.freeAt) && c.events.length === d.events.length && c.events.every((event, index) => event === d.events[index]) : !d.busy && sameMoment(c.nextEventAt, d.nextEventAt));
1821
+ }
1822
+ /**
1823
+ * A resource's status on a root's clock, as a store: `compute` (usually `resourceStatusAt` with
1824
+ * the root's availability and events) runs when the status next changes, and every minute in case
1825
+ * the clock jumps, and subscribers hear only when the status differs. One timer serves every
1826
+ * subscriber: it starts with the first and stops with the last. Each new subscription samples
1827
+ * again, so a view revealed after a while shows no stale status, and every subscriber hears it
1828
+ * when that sample differs. Only `source`'s clock is read: a root that fixes `source.now` computes
1829
+ * at it without this store. The server snapshot is `null`, as the server reads no clock.
1830
+ */
1831
+ function createResourceStatusClock(source, compute) {
1832
+ const clock = clockOf(source);
1833
+ const listeners = createListeners();
1834
+ let current;
1835
+ let subscriptions = 0;
1836
+ let timer;
1837
+ /** Samples now and schedules the next sample; whether a status someone read has changed. */
1838
+ function sample() {
1839
+ const now = clock.instant();
1840
+ const next = compute(now);
1841
+ const changed = current !== void 0 && !sameStatus(current, next);
1842
+ if (current === void 0 || changed) current = next;
1843
+ const until = next.changesAt === null ? SAMPLE_MS : now.until(next.changesAt).total("milliseconds");
1844
+ clearTimeout(timer);
1845
+ timer = setTimeout(tick, Math.max(0, Math.min(SAMPLE_MS, until)));
1846
+ return changed;
1847
+ }
1848
+ function tick() {
1849
+ if (sample()) listeners.notify();
1850
+ }
1851
+ return Object.freeze({
1852
+ getServerSnapshot: () => null,
1853
+ getSnapshot: () => current ??= compute(clock.instant()),
1854
+ subscribe: (listener) => {
1855
+ const unsubscribe = listeners.subscribe(listener);
1856
+ subscriptions += 1;
1857
+ tick();
1858
+ let subscribed = true;
1859
+ return () => {
1860
+ if (!subscribed) return;
1861
+ subscribed = false;
1862
+ unsubscribe();
1863
+ subscriptions -= 1;
1864
+ if (subscriptions === 0) {
1865
+ clearTimeout(timer);
1866
+ timer = void 0;
1867
+ }
1868
+ };
1869
+ }
1870
+ });
1871
+ }
1872
+ // src/roving-focus.ts
1873
+ /** Whether `focus` is on an element that shows `target` across `days` dates. */
1874
+ function focusLandsOn(focus, target, days) {
1875
+ if (focus.kind === "event" && target.kind === "event") {
1876
+ const offset = target.date.until(focus.date).days;
1877
+ return focus.eventId === target.eventId && focus.resourceId === target.resourceId && offset >= 0 && offset < days;
1878
+ }
1879
+ return sameFocus(focus, target);
1880
+ }
1881
+ /**
1882
+ * `focus` as it lands on an element showing `target` across `days` dates, or `null` when it does
1883
+ * not. A resource on only one side matches, so focus carries over between views with and without
1884
+ * resources, and then takes the element's resource, keeping its date: one copy is the tab stop,
1885
+ * and keys act in the resource it shows.
1886
+ */
1887
+ function landOn(focus, target, days) {
1888
+ const { resourceId } = target;
1889
+ if (focus.resourceId === resourceId) return focusLandsOn(focus, target, days) ? focus : null;
1890
+ if (focus.resourceId !== void 0 && resourceId !== void 0) return null;
1891
+ const landed = {
1892
+ ...focus,
1893
+ resourceId
1894
+ };
1895
+ return focusLandsOn(landed, target, days) ? landed : null;
1896
+ }
1897
+ /** Creates the roving focus of one rendered active view, entering it through `initialEntry`. */
1898
+ function createRovingFocusStore(initialEntry) {
1899
+ const items = /* @__PURE__ */ new Map();
1900
+ const listeners = createListeners();
1901
+ let focus = null;
1902
+ let getEntry = initialEntry;
1903
+ let entryCommand = "home";
1904
+ let resolved = null;
1905
+ /**
1906
+ * DOM focus owed after the next update: to the tab stop, as keyboard navigation asks, or only
1907
+ * to the focused target once it renders, after the element holding DOM focus went away.
1908
+ */
1909
+ let owed = null;
1910
+ /**
1911
+ * The last element let go while it held DOM focus. It can stay in the document, as a scrolling
1912
+ * view keeps days around the visible ones, and focus on it is still the view's to move.
1913
+ */
1914
+ let released = null;
1915
+ function find(target) {
1916
+ if (target === null) return void 0;
1917
+ let compatible;
1918
+ for (const [element, item] of items) {
1919
+ const landed = landOn(target, item.target, item.days);
1920
+ if (landed === target) return {
1921
+ element,
1922
+ target
1923
+ };
1924
+ if (landed !== null) compatible ??= {
1925
+ element,
1926
+ target: landed
1927
+ };
1928
+ }
1929
+ return compatible;
1930
+ }
1931
+ function resolve() {
1932
+ if (resolved !== null) return resolved;
1933
+ const entry = getEntry(entryCommand);
1934
+ if (items.size === 0) return resolved = {
1935
+ by: "empty",
1936
+ entry,
1937
+ exact: false,
1938
+ target: entry ?? focus
1939
+ };
1940
+ const found = find(focus);
1941
+ if (found !== void 0) return resolved = {
1942
+ ...found,
1943
+ by: "focus",
1944
+ entry,
1945
+ exact: found.target === focus,
1946
+ isFocus: true
1947
+ };
1948
+ const entered = find(entry);
1949
+ if (entered !== void 0) return resolved = {
1950
+ ...entered,
1951
+ by: "entry",
1952
+ entry,
1953
+ exact: entered.target === entry
1954
+ };
1955
+ const [element] = [...items.keys()].sort((left, right) => left.compareDocumentPosition(right) & Node.DOCUMENT_POSITION_FOLLOWING ? -1 : 1);
1956
+ return resolved = {
1957
+ by: "order",
1958
+ element,
1959
+ entry,
1960
+ exact: false,
1961
+ target: element === void 0 ? null : items.get(element).target
1962
+ };
1963
+ }
1964
+ /**
1965
+ * Whether `item`, registering after every other element, can move the resolved tab stop. `find`
1966
+ * takes the first element that lands on its target, so a later one wins only by landing in the
1967
+ * target's own resource where the first didn't, or by landing on the focus when the tab stop
1968
+ * isn't on it. Elements register while a commit reads their tab stops, so keeping the tab stop
1969
+ * saves a pass over every element for each one.
1970
+ */
1971
+ function moves(item, { by, entry, exact }) {
1972
+ const lands = (target) => target === null ? null : landOn(target, item.target, item.days);
1973
+ if (by === "focus") return !exact && lands(focus) === focus;
1974
+ if (by === "entry") return lands(focus) !== null || !exact && lands(entry) === entry;
1975
+ return true;
1976
+ }
1977
+ function changed() {
1978
+ resolved = null;
1979
+ listeners.notify();
1980
+ }
1981
+ let notifying = false;
1982
+ /**
1983
+ * `changed` for elements coming and going: a commit registers them one by one, hundreds in a
1984
+ * year of days, so their elements hear once, after it, rather than once per element.
1985
+ */
1986
+ function changedLater() {
1987
+ if (notifying) return;
1988
+ notifying = true;
1989
+ queueMicrotask(() => {
1990
+ notifying = false;
1991
+ changed();
1992
+ });
1993
+ }
1994
+ function itemAt(node) {
1995
+ for (let current = node; current !== null; current = current.parentNode) {
1996
+ const item = items.get(current);
1997
+ if (item !== void 0) return item;
1998
+ }
1999
+ }
2000
+ /** Focuses the tab stop unless focus has moved elsewhere on the page in the meantime. */
2001
+ function focusNow() {
2002
+ const { element, isFocus = false } = resolve();
2003
+ if (owed === "focus" && !isFocus) return;
2004
+ owed = null;
2005
+ const active = document.activeElement;
2006
+ if (element === void 0 || element === active) return;
2007
+ const ours = itemAt(active) !== void 0 || released?.contains(active) === true;
2008
+ if (active !== null && active !== document.body && !ours) return;
2009
+ released = null;
2010
+ element.focus();
2011
+ }
2012
+ let retrying = false;
2013
+ /**
2014
+ * Retries owed focus once the commit that registered an element is done. By then this commit's
2015
+ * focus has reached the store, so a newer focus wins over the element that came back.
2016
+ */
2017
+ function retryOwedFocus() {
2018
+ if (retrying) return;
2019
+ retrying = true;
2020
+ queueMicrotask(() => {
2021
+ retrying = false;
2022
+ if (owed === "focus") focusNow();
2023
+ });
2024
+ }
2025
+ return Object.freeze({
2026
+ enterFromEnd() {
2027
+ entryCommand = "end";
2028
+ resolved = null;
2029
+ },
2030
+ focusAt(node) {
2031
+ const item = itemAt(node);
2032
+ if (item === void 0) return focus;
2033
+ return (focus === null ? null : landOn(focus, item.target, item.days)) ?? item.target;
2034
+ },
2035
+ focusTabStop(when) {
2036
+ owed = "tab-stop";
2037
+ if (when === "now") focusNow();
2038
+ },
2039
+ isTabStop(target, days) {
2040
+ const stop = resolve().target;
2041
+ return stop !== null && focusLandsOn(stop, target, days);
2042
+ },
2043
+ register(element, target, days) {
2044
+ const item = {
2045
+ days,
2046
+ target
2047
+ };
2048
+ const known = items.get(element);
2049
+ if (resolved !== null) {
2050
+ const same = known !== void 0 && known.days === days && sameFocus(known.target, target);
2051
+ if (known === void 0 ? moves(item, resolved) : !same) resolved = null;
2052
+ }
2053
+ items.set(element, item);
2054
+ changedLater();
2055
+ if (owed === "focus") retryOwedFocus();
2056
+ return () => {
2057
+ if (items.get(element)?.target !== target) return;
2058
+ if (element.contains(document.activeElement)) {
2059
+ owed ??= "focus";
2060
+ released = element;
2061
+ }
2062
+ items.delete(element);
2063
+ if (resolved?.element === element) resolved = null;
2064
+ changedLater();
2065
+ };
2066
+ },
2067
+ subscribe: listeners.subscribe,
2068
+ update(nextFocus, nextEntry) {
2069
+ focus = nextFocus;
2070
+ getEntry = nextEntry;
2071
+ if (nextFocus !== null) entryCommand = "home";
2072
+ changed();
2073
+ if (owed !== null) focusNow();
2074
+ }
2075
+ });
2076
+ }
2077
+ /** The active view's entry points, from its spatial navigation with no focus. */
2078
+ function calendarViewEntry(view) {
2079
+ return (command) => {
2080
+ if (view === null) return null;
2081
+ const { definition, environment, options, projection, range } = view;
2082
+ const result = definition.strategy.getSpatialNavigation?.({
2083
+ command,
2084
+ environment,
2085
+ focus: null,
2086
+ options,
2087
+ projection,
2088
+ range,
2089
+ snap: DEFAULT_SNAP
2090
+ });
2091
+ return result != null && "focus" in result ? result.focus : null;
2092
+ };
2093
+ }
2094
+ /**
2095
+ * The focus plumbing of one rendered active view: `getView` reads the latest active view, and the
2096
+ * roving store starts from the view `getView` returns now, so server markup gets its tab stop.
2097
+ * Keep the store on the root's focus with `roving.update(focus, calendarViewEntry(view))` after
2098
+ * the view's elements register.
2099
+ */
2100
+ function createCalendarViewRuntime(getView) {
2101
+ return Object.freeze({
2102
+ getView,
2103
+ roving: createRovingFocusStore(calendarViewEntry(getView()))
2104
+ });
2105
+ }
2106
+ /**
2107
+ * A key for a focus target that changes exactly when the target does, for an integration that
2108
+ * registers an element again when its target changes. `1` and `"1"` are distinct IDs, and `null`
2109
+ * (unassigned) differs from no resource.
2110
+ */
2111
+ function calendarFocusKey(target) {
2112
+ const { resourceId } = target;
2113
+ const resource = resourceId === void 0 ? "" : resourceId === null ? "|unassigned" : `|${typeof resourceId}:${resourceId}`;
2114
+ switch (target.kind) {
2115
+ case "day": return `day:${target.date.toString()}${resource}`;
2116
+ case "slot": return `slot:${target.date.toString()}T${target.time.toString()}${resource}`;
2117
+ case "event": return `event:${typeof target.eventId}:${target.eventId}@${target.date.toString()}${resource}`;
2118
+ }
2119
+ }
2120
+ /**
2121
+ * What an element showing `target` across `days` dates does when it takes DOM focus itself (call
2122
+ * it only when the focus event's target is that element): it becomes the calendar's focus. Focus
2123
+ * already on it stays as it is, keeping an event's date within the element. `event`, the focus
2124
+ * event, reaches the state handlers, so they hear the click or key that moved focus.
2125
+ */
2126
+ function focusRovingTarget({ actions, read }, target, days, event) {
2127
+ const focus = read().focus;
2128
+ const landed = focus === null ? null : landOn(focus, target, days);
2129
+ if (landed === null || landed !== focus) actions.setFocus(landed ?? target, {
2130
+ event,
2131
+ reason: "focus-change"
2132
+ });
1090
2133
  }
1091
2134
  // src/views.ts
1092
2135
  /** Applies a root's partial overrides to a view's `defaultOptions`. */
@@ -1330,6 +2373,7 @@ function createCalendarRuntime(config) {
1330
2373
  const transactions = createEventTransactions();
1331
2374
  const keyboard = createKeyboardSessionStore();
1332
2375
  const pointerDraft = createDraftStore();
2376
+ const draft = createDraftSource(keyboard, pointerDraft);
1333
2377
  const noChanges = transactions.getPendingChanges();
1334
2378
  const pendingChanges = Object.freeze({
1335
2379
  getServerSnapshot: () => noChanges,
@@ -1590,6 +2634,7 @@ function createCalendarRuntime(config) {
1590
2634
  actions,
1591
2635
  announcements,
1592
2636
  changes: pendingChanges,
2637
+ draft,
1593
2638
  isReadOnly,
1594
2639
  keyboard,
1595
2640
  pointerDraft,
@@ -1700,4 +2745,4 @@ function createCalendarRuntime(config) {
1700
2745
  viewsByName
1701
2746
  });
1702
2747
  }
1703
- export { TODAY_SAMPLE_INTERVAL_MS, agentEventLabel, calendarAgentActions, calendarStateSlices, clockOf, createAnnouncerChannel, createCalendarPartIds, createCalendarPrimitive, createCalendarRuntime, createCalendarStore, createClockTicker, createDraftStore, createKeyboardSessionStore, createMemoCell, createStableCell, describeAgentEvent, describeAgentPlacement, eventLabel, eventsInRange, findEvent, getCalendarStoreInternals, mergeControlledState, parseInstant, parsePlainDate, parsePlainDateTime, parseTimeZone, readAgentInput, reportCallbackError, resolveCalendarStoreDefaults, resolveViewOptions, sameAvailability, sameElements, sameInstant, samePlainDate, sameRange, sameSecondaryTimeZones, sameSliceValue, sameWeekRules, shallowEqual, systemClock, visibleEventsOf };
2748
+ export { TODAY_SAMPLE_INTERVAL_MS, agentEventLabel, attachCalendarHistoryShortcuts, bindCalendarHistory, calendarAgentActions, calendarFocusKey, calendarStateSlices, calendarViewEntry, clockOf, createAnnouncerChannel, createAnnouncerLiveText, createBusyResourcesQuery, createCalendarKeyboard, createCalendarPartIds, createCalendarPrimitive, createCalendarRuntime, createCalendarStore, createCalendarViewRuntime, createClockTicker, createDraftBusyQuery, createDraftStore, createKeyboardSessionStore, createMemoCell, createResourceExpansionCommands, createResourceStatusClock, createStableCell, describeAgentEvent, describeAgentPlacement, eventLabel, eventsInRange, findEvent, focusRovingTarget, getCalendarStoreInternals, mergeControlledState, parseInstant, parsePlainDate, parsePlainDateTime, parseTimeZone, readAgentInput, reportCallbackError, resolveCalendarStoreDefaults, resolveViewOptions, sameAvailability, sameElements, sameInstant, samePlainDate, sameRange, sameSecondaryTimeZones, sameSliceValue, sameWeekRules, shallowEqual, subscribeAnchorDateRequests, systemClock, visibleEventsOf };