@moltenship/calendar-primitives 0.0.0-stage → 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 ADDED
@@ -0,0 +1,2748 @@
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
+ import { definePrimitive, dispatch } from "@ui-sdk/core";
4
+ // src/agent.ts
5
+ function describe(value) {
6
+ return typeof value === "string" ? `"${value}"` : JSON.stringify(value) ?? String(value);
7
+ }
8
+ /** A date as `YYYY-MM-DD`; a date-time's date counts too. */
9
+ const calendarAnnotation = /\[!?u-ca=([^\]]*)\]/iu;
10
+ /**
11
+ * Refuses a date in another calendar than ISO 8601, as `2026-08-20[u-ca=hebrew]` gives: Temporal
12
+ * would carry that calendar into state and proposals, where everything else is ISO, and its
13
+ * month and day would mean something else to every reader.
14
+ */
15
+ function refuseOtherCalendars(value, name) {
16
+ const calendar = typeof value === "string" ? calendarAnnotation.exec(value)?.[1] : value instanceof Temporal.PlainDate || value instanceof Temporal.PlainDateTime || value instanceof Temporal.ZonedDateTime ? value.calendarId : void 0;
17
+ if (calendar === void 0 || calendar.toLowerCase() === "iso8601") return;
18
+ throw new RangeError(`calendar-agent-unsupported-calendar: ${name} is in the ${JSON.stringify(calendar)} calendar, in ${describe(value)}; the calendar takes ISO 8601 dates only, without a [u-ca=…] annotation`);
19
+ }
20
+ function parsePlainDate(value, name) {
21
+ refuseOtherCalendars(value, name);
22
+ if (value instanceof Temporal.PlainDate) return value;
23
+ if (typeof value === "string") try {
24
+ return Temporal.PlainDate.from(value);
25
+ } catch {}
26
+ throw new TypeError(`calendar-agent-invalid-date: ${name} must be an ISO date such as "2026-03-14", not ${describe(value)}`);
27
+ }
28
+ /** A time zone as an IANA name, checked against the platform's database. */
29
+ function parseTimeZone(value) {
30
+ if (typeof value === "string") try {
31
+ return Temporal.ZonedDateTime.from({
32
+ day: 1,
33
+ month: 1,
34
+ timeZone: value,
35
+ year: 2e3
36
+ }).timeZoneId;
37
+ } catch {}
38
+ throw new TypeError(`calendar-agent-invalid-time-zone: expected an IANA time zone such as "Europe/Berlin", not ${describe(value)}`);
39
+ }
40
+ const offsetOrZone = /(?:[zZ]|[+-]\d{2}(?::?\d{2})?)(?:\[[^\]]+\])?$|\[[^\]]+\]$/u;
41
+ /**
42
+ * An exact time: with an offset or `Z` it means that instant, as `2026-03-14T09:00Z`; without
43
+ * one it is wall-clock time in the display time zone, as `2026-03-14T09:00`.
44
+ */
45
+ function parseInstant(value, name, environment) {
46
+ refuseOtherCalendars(value, name);
47
+ if (value instanceof Temporal.Instant) return value;
48
+ if (value instanceof Temporal.ZonedDateTime) return value.toInstant();
49
+ if (typeof value === "string") try {
50
+ const iso = value.replace(calendarAnnotation, "");
51
+ if (offsetOrZone.test(iso)) return iso.includes("[") ? Temporal.ZonedDateTime.from(iso).toInstant() : Temporal.Instant.from(iso);
52
+ return Temporal.PlainDateTime.from(iso).toZonedDateTime(environment.timeZone, { disambiguation: environment.disambiguation }).toInstant();
53
+ } catch {}
54
+ throw new TypeError(`calendar-agent-invalid-time: ${name} must be an ISO date-time such as "2026-03-14T09:00" (in the calendar's time zone, ${environment.timeZone}) or "2026-03-14T09:00Z", not ${describe(value)}`);
55
+ }
56
+ /** A wall-clock date-time, for floating events. */
57
+ function parsePlainDateTime(value, name) {
58
+ refuseOtherCalendars(value, name);
59
+ if (value instanceof Temporal.PlainDateTime) return value;
60
+ if (typeof value === "string") try {
61
+ return Temporal.PlainDateTime.from(value);
62
+ } catch {}
63
+ throw new TypeError(`calendar-agent-invalid-time: ${name} must be an ISO date-time such as "2026-03-14T09:00", not ${describe(value)}`);
64
+ }
65
+ function isRecord$1(value) {
66
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
67
+ const prototype = Object.getPrototypeOf(value);
68
+ return prototype === Object.prototype || prototype === null;
69
+ }
70
+ /**
71
+ * An action's one JSON object argument, checked against the keys it takes: `true` for a required
72
+ * key, `false` for an optional one. Anything else, a second argument, an unknown key or a missing
73
+ * one, fails with the action's signature, so the agent can retry with what it expected.
74
+ */
75
+ function readAgentInput(action, signature, input, keys, extra = [], nullable = []) {
76
+ const fail = (problem) => {
77
+ throw new TypeError(`calendar-agent-invalid-arguments: ${action} takes ${signature}; ${problem}`);
78
+ };
79
+ if (extra.some((value) => value !== void 0)) fail(`it takes one object, not ${extra.length + 1} arguments`);
80
+ if (!isRecord$1(input)) fail(`got ${describe(input)}`);
81
+ const record = input;
82
+ const known = keys;
83
+ const unknown = Object.keys(record).filter((key) => !Object.hasOwn(known, key));
84
+ if (unknown.length > 0) fail(`it has no ${unknown.map((key) => JSON.stringify(key)).join(", ")}`);
85
+ for (const [key, required] of Object.entries(known)) {
86
+ const value = record[key];
87
+ if (value === null && !nullable.includes(key)) fail(`${key} can't be null`);
88
+ if (required && value === void 0) fail(`${key} is missing`);
89
+ }
90
+ return record;
91
+ }
92
+ /** An event's ID as the adapter gives it: a string or a number. */
93
+ function readEventId(value) {
94
+ if (typeof value === "string" || typeof value === "number" && Number.isFinite(value)) return value;
95
+ throw new TypeError(`calendar-agent-invalid-arguments: eventId must be an event's ID, a string or a number from listEvents, not ${describe(value)}`);
96
+ }
97
+ /** A list of resource IDs, each a string or a number. */
98
+ function readResourceIds(value, known) {
99
+ if (!Array.isArray(value) || !value.every((id) => typeof id === "string" || typeof id === "number")) throw new TypeError(`calendar-agent-invalid-resources: resourceIds must be a list of resource IDs, not ${describe(value)}`);
100
+ if (known.size === 0) return Object.freeze([...value]);
101
+ return Object.freeze(value.map((id) => {
102
+ if (known.has(id)) return id;
103
+ const found = [...known.keys()].find((candidate) => String(candidate) === String(id));
104
+ if (found !== void 0) return found;
105
+ const listed = [...known.keys()].slice(0, 20).map((candidate) => JSON.stringify(candidate));
106
+ throw new RangeError(`calendar-agent-unknown-resource: no resource has the ID ${describe(id)}. Resources: ${listed.join(", ")}${known.size > listed.length ? ", …" : ""}`);
107
+ }));
108
+ }
109
+ /**
110
+ * The fields an agent gives beside a placement: its `fields` object with its `title` in it. Not
111
+ * validated further: what a field means is the application's to decide.
112
+ */
113
+ function readFields(input) {
114
+ const { fields, title } = input;
115
+ if (title !== void 0 && typeof title !== "string") throw new TypeError(`calendar-agent-invalid-arguments: title must be a string, not ${describe(title)}`);
116
+ if (fields !== void 0 && !isRecord$1(fields)) throw new TypeError(`calendar-agent-invalid-arguments: fields must be an object of JSON values, not ${describe(fields)}`);
117
+ if (title !== void 0 && fields !== void 0 && Object.hasOwn(fields, "title")) throw new TypeError("calendar-agent-invalid-arguments: give the title as title or as fields.title, not both");
118
+ if (fields === void 0 && title === void 0) return void 0;
119
+ return Object.freeze({
120
+ ...fields,
121
+ ...title === void 0 ? {} : { title }
122
+ });
123
+ }
124
+ function hasTime(value) {
125
+ return typeof value === "string" ? value.includes("T") || value.includes("t") : !(value instanceof Temporal.PlainDate);
126
+ }
127
+ /** The event an agent names, by its ID as the adapter gives it or as a string. */
128
+ function findEvent(events, id) {
129
+ const exact = typeof id === "string" || typeof id === "number" ? events.get(id) : void 0;
130
+ if (exact !== void 0) return exact;
131
+ const found = events.events.find((event) => String(event.id) === String(id));
132
+ if (found !== void 0) return found;
133
+ const known = events.events.slice(0, 20).map((event) => JSON.stringify(event.id));
134
+ throw new RangeError(`calendar-agent-unknown-event: no event has the ID ${describe(id)}. Events: ${known.length === 0 ? "none" : known.join(", ")}${events.size > known.length ? ", …" : ""}`);
135
+ }
136
+ /** Where `event` would land when it starts at `start`, keeping its length unless `end` is given. */
137
+ function movedPlacement(event, start, end, environment) {
138
+ if (event.kind === "all-day") {
139
+ const from = parsePlainDate(start, "start");
140
+ return {
141
+ end: end === void 0 ? from.add(event.start.until(event.end)) : parsePlainDate(end, "end"),
142
+ kind: "all-day",
143
+ start: from
144
+ };
145
+ }
146
+ if (event.kind === "floating") {
147
+ const from = parsePlainDateTime(start, "start");
148
+ return {
149
+ end: end === void 0 ? from.add(event.start.until(event.end)) : parsePlainDateTime(end, "end"),
150
+ kind: "floating",
151
+ start: from
152
+ };
153
+ }
154
+ const from = parseInstant(start, "start", environment);
155
+ return {
156
+ end: end === void 0 ? from.add(event.start.until(event.end)) : parseInstant(end, "end", environment),
157
+ kind: "timed",
158
+ start: from,
159
+ ...event.sourceTimeZone === void 0 ? {} : { sourceTimeZone: event.sourceTimeZone }
160
+ };
161
+ }
162
+ /** A new event's placement: dates make an all-day event, date-times a timed one. */
163
+ function createdPlacement(start, end, resourceIds, environment, resources) {
164
+ const withResources = resourceIds === void 0 ? {} : { resourceIds: readResourceIds(resourceIds, resources) };
165
+ if (!hasTime(start) && !hasTime(end)) return {
166
+ end: parsePlainDate(end, "end"),
167
+ kind: "all-day",
168
+ start: parsePlainDate(start, "start"),
169
+ ...withResources
170
+ };
171
+ return {
172
+ end: parseInstant(end, "end", environment),
173
+ kind: "timed",
174
+ start: parseInstant(start, "start", environment),
175
+ ...withResources
176
+ };
177
+ }
178
+ /** The events that overlap `range` in the calendar's time zone, all-day ones first, then by start. */
179
+ function eventsInRange(events, range, environment) {
180
+ const startOfDay = (date) => date.toZonedDateTime({ timeZone: environment.timeZone }).toInstant();
181
+ const instants = instantInterval(startOfDay(range.start), startOfDay(range.end));
182
+ const floating = plainDateTimeInterval(range.start.toPlainDateTime(), range.end.toPlainDateTime());
183
+ const timed = [...events.queryTimed(instants), ...events.queryFloating(floating)];
184
+ timed.sort((left, right) => Temporal.Instant.compare(startOf(left, environment), startOf(right, environment)));
185
+ return [...events.queryAllDay(range), ...timed];
186
+ }
187
+ /** The events the active view shows, in the order a reader meets them: all-day ones first. */
188
+ function visibleEventsOf(events, view) {
189
+ if (view === null) return [];
190
+ const { instantRange, range } = view;
191
+ const floating = plainDateTimeInterval(range.start.toPlainDateTime(), range.end.toPlainDateTime());
192
+ const timed = [...events.queryTimed(instantRange), ...events.queryFloating(floating)];
193
+ timed.sort((left, right) => Temporal.Instant.compare(startOf(left, view.environment), startOf(right, view.environment)));
194
+ return [...events.queryAllDay(range), ...timed];
195
+ }
196
+ function startOf(event, environment) {
197
+ return event.kind === "timed" ? event.start : event.start.toZonedDateTime(environment.timeZone).toInstant();
198
+ }
199
+ /** A placement as JSON, with its times in `timeZone`. */
200
+ function describeAgentPlacement(placement, timeZone) {
201
+ const timed = (instant) => instant.toZonedDateTimeISO(timeZone).toString({ timeZoneName: "never" });
202
+ const [start, end] = placement.kind === "timed" ? [timed(placement.start), timed(placement.end)] : [placement.start.toString(), placement.end.toString()];
203
+ return Object.freeze({
204
+ end,
205
+ kind: placement.kind,
206
+ resourceIds: placement.resourceIds,
207
+ start
208
+ });
209
+ }
210
+ /** An event as JSON, with its times in the calendar's time zone. */
211
+ function describeAgentEvent(event, environment) {
212
+ return Object.freeze({
213
+ ...describeAgentPlacement(event, environment.timeZone),
214
+ id: event.id,
215
+ ...event.isPending === true ? { pending: true } : {},
216
+ ...event.isReadOnly ? { readOnly: true } : {},
217
+ title: event.title
218
+ });
219
+ }
220
+ /** `2026-03-14T09:00:00+01:00` as `2026-03-14T09:00`, for a label a person can read too. */
221
+ function minutes(value) {
222
+ return value.slice(0, 16);
223
+ }
224
+ /**
225
+ * An event's default label for an agent: its title, then when it happens in ISO 8601, in the
226
+ * calendar's time zone, as `Design review · 2026-03-14T09:00 to 2026-03-14T10:00 (Europe/Berlin)`.
227
+ * Unlike a localized date, an agent can read it back exactly. An all-day event's last day is
228
+ * inclusive here, as a person reads `to`; `listEvents` gives the exclusive end.
229
+ */
230
+ function agentEventLabel(event, timeZone) {
231
+ let when;
232
+ if (event.kind === "all-day") {
233
+ const last = Temporal.PlainDate.from(event.end).subtract({ days: 1 }).toString();
234
+ when = last === event.start ? `${event.start} (all day)` : `${event.start} to ${last} (all day)`;
235
+ } else {
236
+ const zone = event.kind === "timed" ? timeZone : "local time";
237
+ when = `${minutes(event.start)} to ${minutes(event.end)} (${zone})`;
238
+ }
239
+ return event.title === "" ? when : `${event.title} · ${when}`;
240
+ }
241
+ /** `agentEventLabel` of a normalized event, in the calendar's time zone. */
242
+ function eventLabel(event, environment) {
243
+ return agentEventLabel(describeAgentEvent(event, environment), environment.timeZone);
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
+ }
286
+ // src/announcer-channel.ts
287
+ function buildMessage(messages, update, context) {
288
+ const build = messages[update.phase];
289
+ return build(update, context);
290
+ }
291
+ /** `getEnvironment` and `getResources` read the root's last commit when an update arrives. */
292
+ function createAnnouncerChannel(getEnvironment, getResources) {
293
+ const mounted = [];
294
+ function formatRange(placement) {
295
+ const { locale, timeZone } = getEnvironment();
296
+ return (mounted.at(-1)?.getMessages().formatRange ?? formatPlacementRange)(placement, {
297
+ locale,
298
+ timeZone
299
+ });
300
+ }
301
+ function resourceTitle(resourceId) {
302
+ return getResources().byId.get(resourceId)?.resource.title;
303
+ }
304
+ function say(build) {
305
+ const current = mounted.at(-1);
306
+ if (current === void 0) return;
307
+ const { locale, timeZone } = getEnvironment();
308
+ const text = build({
309
+ formatRange,
310
+ locale,
311
+ resourceTitle,
312
+ timeZone
313
+ }, current.getMessages());
314
+ if (text !== null && text !== "") current.speak(text);
315
+ }
316
+ return Object.freeze({
317
+ announcer: Object.freeze({
318
+ announce: (update) => say((context, messages) => buildMessage(messages, update, context)),
319
+ formatRange
320
+ }),
321
+ mount(getMessages, speak) {
322
+ const entry = {
323
+ getMessages,
324
+ speak
325
+ };
326
+ mounted.push(entry);
327
+ return () => {
328
+ const index = mounted.lastIndexOf(entry);
329
+ if (index !== -1) mounted.splice(index, 1);
330
+ };
331
+ },
332
+ say
333
+ });
334
+ }
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 = "";
342
+ const listeners = createListeners();
343
+ return Object.freeze({
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;
352
+ listeners.notify();
353
+ },
354
+ subscribe: listeners.subscribe
355
+ });
356
+ }
357
+ // src/equality.ts
358
+ function sameElements(left, right) {
359
+ return left === right || left.length === right.length && left.every((value, index) => Object.is(value, right[index]));
360
+ }
361
+ /** Compares own enumerable properties with `Object.is`; non-objects compare with `Object.is`. */
362
+ function shallowEqual(left, right) {
363
+ if (Object.is(left, right)) return true;
364
+ if (typeof left !== "object" || typeof right !== "object" || left === null || right === null) return false;
365
+ const leftKeys = Object.keys(left);
366
+ return leftKeys.length === Object.keys(right).length && leftKeys.every((key) => Object.hasOwn(right, key) && Object.is(left[key], right[key]));
367
+ }
368
+ function samePlainDate(left, right) {
369
+ return left === right || left != null && right != null && left.equals(right);
370
+ }
371
+ function sameInstant(left, right) {
372
+ return left === right || left !== void 0 && right !== void 0 && left.equals(right);
373
+ }
374
+ function sameRange(left, right) {
375
+ return left === right || left !== void 0 && right !== void 0 && left.start.equals(right.start) && left.end.equals(right.end);
376
+ }
377
+ function sameWeekRules(left, right) {
378
+ return left === right || left.firstDay === right.firstDay && left.minimalDays === right.minimalDays && sameElements(left.weekend, right.weekend);
379
+ }
380
+ const isRecord = (value) => typeof value === "object" && value !== null;
381
+ /**
382
+ * Lists by element: identical values, or records `same` matches. Anything else, such as an
383
+ * invalid entry the snapshot reports, matches only itself.
384
+ */
385
+ function sameList(left, right, same) {
386
+ if (left === right) return true;
387
+ if (!Array.isArray(left) || !Array.isArray(right) || left.length !== right.length) return false;
388
+ return Array.from(left).every((value, index) => {
389
+ const other = right[index];
390
+ return Object.is(value, other) || isRecord(value) && isRecord(other) && same(value, other);
391
+ });
392
+ }
393
+ /** Temporal dates and times by value; anything else, such as invalid input, by identity. */
394
+ function sameTemporal(left, right) {
395
+ if (Object.is(left, right)) return true;
396
+ if (left instanceof Temporal.PlainTime) return right instanceof Temporal.PlainTime && left.equals(right);
397
+ return left instanceof Temporal.PlainDate && right instanceof Temporal.PlainDate && left.equals(right);
398
+ }
399
+ function sameHours(left, right) {
400
+ return sameTemporal(left.start, right.start) && sameTemporal(left.end, right.end);
401
+ }
402
+ /**
403
+ * Compares working hours by value, so an inline `availability` keeps its shading cached. Invalid
404
+ * entries never throw here; the snapshot reports them.
405
+ */
406
+ function sameAvailability(left, right) {
407
+ return left === right || isRecord(left) && isRecord(right) && left.timeZone === right.timeZone && sameList(left.weekly, right.weekly, (a, b) => sameHours(a, b) && sameList(a.days, b.days, Object.is)) && sameList(left.exceptions, right.exceptions, (a, b) => sameTemporal(a.date, b.date) && a.label === b.label && sameList(a.hours, b.hours, sameHours));
408
+ }
409
+ const sameZone = (left, right) => Object.is(left, right) || isRecord(left) && isRecord(right) && left.timeZone === right.timeZone && left.label === right.label;
410
+ /**
411
+ * Compares secondary time zones by value, so an inline list keeps the environment as it is. A
412
+ * single zone passed where a list belongs, which the root reports, compares by value too.
413
+ */
414
+ function sameSecondaryTimeZones(left, right) {
415
+ return Array.isArray(left) && Array.isArray(right) ? sameList(left, right, sameZone) : sameZone(left, right);
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
+ }
1114
+ // src/keyboard-store.ts
1115
+ const noPreview = /* @__PURE__ */ new Map();
1116
+ function createKeyboardSessionStore() {
1117
+ let grab = null;
1118
+ let preview = noPreview;
1119
+ const listeners = createListeners();
1120
+ const { subscribe } = listeners;
1121
+ return Object.freeze({
1122
+ get: () => grab,
1123
+ getPreview: () => preview,
1124
+ grabs: Object.freeze({
1125
+ getSnapshot: () => grab,
1126
+ subscribe
1127
+ }),
1128
+ set(next) {
1129
+ if (next === grab) return;
1130
+ grab = next;
1131
+ const session = next?.session;
1132
+ preview = session?.eventId == null ? noPreview : /* @__PURE__ */ new Map([[session.eventId, session.proposed]]);
1133
+ listeners.notify();
1134
+ },
1135
+ subscribe
1136
+ });
1137
+ }
1138
+ // src/memo.ts
1139
+ /**
1140
+ * Memo cells: what `useMemo` and a stable-value hook do in a component, as plain closures a
1141
+ * runtime owns, so a framework can derive during render (or in a signal's memo) and get the same
1142
+ * objects back while their inputs hold.
1143
+ */
1144
+ /** A value that keeps its first identity while `isEqual` says each next one is the same. */
1145
+ function createStableCell(isEqual) {
1146
+ let held;
1147
+ return (next) => {
1148
+ if (held !== void 0 && (held.value === next || isEqual(held.value, next))) return held.value;
1149
+ held = { value: next };
1150
+ return next;
1151
+ };
1152
+ }
1153
+ /** A value computed again only when one of its dependencies changes identity. */
1154
+ function createMemoCell() {
1155
+ let held;
1156
+ return (deps, compute) => {
1157
+ if (held !== void 0 && held.deps.length === deps.length && held.deps.every((dep, index) => Object.is(dep, deps[index]))) return held.value;
1158
+ const value = compute();
1159
+ held = {
1160
+ deps,
1161
+ value
1162
+ };
1163
+ return value;
1164
+ };
1165
+ }
1166
+ // src/store.ts
1167
+ const handlerNames = Object.freeze({
1168
+ anchorDate: "onAnchorDateChange",
1169
+ expandedResourceIds: "onExpandedResourceIdsChange",
1170
+ focus: "onFocusChange",
1171
+ selection: "onSelectionChange",
1172
+ timeZone: "onTimeZoneChange",
1173
+ view: "onViewChange"
1174
+ });
1175
+ /** The six slices, in a fixed order. */
1176
+ const calendarStateSlices = Object.keys(handlerNames);
1177
+ const storeInternals = /* @__PURE__ */ new WeakMap();
1178
+ function uniqueResourceIds(resourceIds) {
1179
+ return Object.freeze([...new Set(resourceIds)]);
1180
+ }
1181
+ /** Dates by value and resource lists by element; everything else by identity. */
1182
+ function sameSliceValue(slice, previous, next) {
1183
+ if (slice === "anchorDate") return samePlainDate(previous, next);
1184
+ if (slice === "expandedResourceIds") return sameElements(previous, next);
1185
+ return Object.is(previous, next);
1186
+ }
1187
+ /** Overlays every defined controlled slice on the uncontrolled state. */
1188
+ function mergeControlledState(state, controlled) {
1189
+ if (controlled === void 0) return state;
1190
+ const overlay = calendarStateSlices.filter((slice) => controlled[slice] !== void 0);
1191
+ if (overlay.length === 0) return state;
1192
+ const merged = { ...state };
1193
+ for (const slice of overlay) Object.assign(merged, { [slice]: controlled[slice] });
1194
+ return Object.freeze(merged);
1195
+ }
1196
+ function getCalendarStoreInternals(store) {
1197
+ const internals = storeInternals.get(store);
1198
+ if (internals === void 0) throw new TypeError("calendar-store-not-created-by-createCalendarStore");
1199
+ return internals;
1200
+ }
1201
+ function createCalendarStore(options) {
1202
+ let state = Object.freeze({
1203
+ anchorDate: options.defaultAnchorDate,
1204
+ expandedResourceIds: uniqueResourceIds(options.defaultExpandedResourceIds ?? []),
1205
+ focus: options.defaultFocus ?? null,
1206
+ selection: options.defaultSelection ?? null,
1207
+ timeZone: options.defaultTimeZone,
1208
+ view: options.defaultView
1209
+ });
1210
+ const listeners = createListeners();
1211
+ const mountedRoots = [];
1212
+ const notify = () => {
1213
+ listeners.notify();
1214
+ };
1215
+ function createActions(run) {
1216
+ return Object.freeze({
1217
+ setAnchorDate: (next, options) => run("anchorDate", next, options),
1218
+ setExpandedResourceIds: (next, options) => run("expandedResourceIds", next, options),
1219
+ setFocus: (next, options) => run("focus", next, options),
1220
+ setSelection: (next, options) => run("selection", next, options),
1221
+ setTimeZone: (next, options) => run("timeZone", next, options),
1222
+ setView: (next, options) => run("view", next, options)
1223
+ });
1224
+ }
1225
+ function bind(initial) {
1226
+ let current = initial;
1227
+ let pending;
1228
+ /**
1229
+ * Values the owners of controlled slices were told about and have not committed: an owner
1230
+ * that defers or declines a change still holds it.
1231
+ */
1232
+ let unsettled = {};
1233
+ const requestListeners = /* @__PURE__ */ new Set();
1234
+ const handlerContext = Object.freeze({ options: () => current.handlers });
1235
+ const read = () => mergeControlledState(mergeControlledState(state, current.controlled), pending);
1236
+ const run = (slice, requested, options) => {
1237
+ const next = slice === "expandedResourceIds" ? uniqueResourceIds(requested) : requested;
1238
+ for (const entry of requestListeners) entry.listener(slice, next);
1239
+ const previous = read()[slice];
1240
+ const controlled = current.controlled[slice] !== void 0;
1241
+ if (sameSliceValue(slice, previous, next)) {
1242
+ const told = unsettled[slice];
1243
+ if (!controlled || told === void 0 || sameSliceValue(slice, told, next)) return;
1244
+ }
1245
+ const before = state;
1246
+ let written;
1247
+ if (controlled) {
1248
+ if (pending === void 0) queueMicrotask(() => pending = void 0);
1249
+ pending = {
1250
+ ...pending,
1251
+ [slice]: next
1252
+ };
1253
+ const settled = sameSliceValue(slice, current.controlled[slice], next);
1254
+ unsettled = {
1255
+ ...unsettled,
1256
+ [slice]: settled ? void 0 : next
1257
+ };
1258
+ } else {
1259
+ written = Object.freeze({
1260
+ ...state,
1261
+ [slice]: next
1262
+ });
1263
+ state = written;
1264
+ notify();
1265
+ }
1266
+ if (dispatch(handlerContext, handlerNames[slice], next, {
1267
+ controlled,
1268
+ ...options?.event === void 0 ? {} : { event: options.event },
1269
+ previous,
1270
+ reason: options?.reason ?? "imperative",
1271
+ slice,
1272
+ ...options?.source === void 0 ? {} : { source: options.source }
1273
+ }) && written !== void 0 && Object.is(state[slice], written[slice])) {
1274
+ state = Object.freeze({
1275
+ ...state,
1276
+ [slice]: before[slice]
1277
+ });
1278
+ notify();
1279
+ }
1280
+ };
1281
+ const binding = Object.freeze({
1282
+ actions: createActions(run),
1283
+ attach: () => {
1284
+ mountedRoots.push(binding);
1285
+ return () => {
1286
+ const index = mountedRoots.lastIndexOf(binding);
1287
+ if (index !== -1) mountedRoots.splice(index, 1);
1288
+ };
1289
+ },
1290
+ commit: (next) => {
1291
+ const previous = current;
1292
+ current = next;
1293
+ for (const slice of calendarStateSlices) {
1294
+ const committed = next.controlled[slice];
1295
+ if (unsettled[slice] !== void 0 && (committed === void 0 || !sameSliceValue(slice, previous.controlled[slice], committed))) unsettled = {
1296
+ ...unsettled,
1297
+ [slice]: void 0
1298
+ };
1299
+ }
1300
+ if (pending === void 0) return;
1301
+ const retained = { ...pending };
1302
+ for (const slice of calendarStateSlices) {
1303
+ if (retained[slice] === void 0) continue;
1304
+ const committed = next.controlled[slice];
1305
+ if (committed === void 0 || !sameSliceValue(slice, previous.controlled[slice], committed)) delete retained[slice];
1306
+ }
1307
+ pending = calendarStateSlices.some((slice) => retained[slice] !== void 0) ? retained : void 0;
1308
+ },
1309
+ read,
1310
+ subscribeRequests: (listener) => {
1311
+ const entry = { listener };
1312
+ requestListeners.add(entry);
1313
+ return () => {
1314
+ requestListeners.delete(entry);
1315
+ };
1316
+ }
1317
+ });
1318
+ return binding;
1319
+ }
1320
+ const unbound = bind({
1321
+ controlled: {},
1322
+ handlers: {}
1323
+ });
1324
+ const owner = () => mountedRoots.at(-1) ?? unbound;
1325
+ const store = {
1326
+ actions: Object.freeze({
1327
+ setAnchorDate: (next, options) => owner().actions.setAnchorDate(next, options),
1328
+ setExpandedResourceIds: (next, options) => owner().actions.setExpandedResourceIds(next, options),
1329
+ setFocus: (next, options) => owner().actions.setFocus(next, options),
1330
+ setSelection: (next, options) => owner().actions.setSelection(next, options),
1331
+ setTimeZone: (next, options) => owner().actions.setTimeZone(next, options),
1332
+ setView: (next, options) => owner().actions.setView(next, options)
1333
+ }),
1334
+ getSnapshot: () => state,
1335
+ subscribe: listeners.subscribe
1336
+ };
1337
+ storeInternals.set(store, { bind });
1338
+ return store;
1339
+ }
1340
+ // src/primitive.ts
1341
+ /**
1342
+ * What each agent action takes, as `describeCalendar` lists it and the action's errors repeat:
1343
+ * ui-sdk's bridge has no way to describe an action's arguments.
1344
+ */
1345
+ const signatures = Object.freeze({
1346
+ createEvent: "{ start: ISO date or date-time, end: ISO date or date-time, title?: string, resourceIds?: ID[], fields?: object }",
1347
+ deleteEvent: "{ eventId: ID }",
1348
+ describeCalendar: "nothing",
1349
+ getChange: "{ changeId: string }",
1350
+ goToDate: "{ date: ISO date }",
1351
+ listEvents: "nothing, or { start?: ISO date, end?: ISO date }",
1352
+ moveEvent: "{ eventId: ID, start: ISO date or date-time, end?: same, resourceIds?: ID[] }",
1353
+ navigateNext: "nothing",
1354
+ navigatePrevious: "nothing",
1355
+ navigateToday: "nothing",
1356
+ resizeEvent: "{ eventId: ID, start?: ISO date or date-time, end?: same }, one of start and end",
1357
+ selectEvent: "{ eventId: ID or null }",
1358
+ setTimeZone: "{ timeZone: IANA name }",
1359
+ setView: "{ view: one of views }",
1360
+ updateEvent: "{ eventId: ID, title?: string, start?: ISO date or date-time, end?: same, resourceIds?: ID[], fields?: object }"
1361
+ });
1362
+ /** The methods an agent may call, with JSON arguments. */
1363
+ const calendarAgentActions = Object.freeze([
1364
+ "describeCalendar",
1365
+ "listEvents",
1366
+ "getChange",
1367
+ "navigateNext",
1368
+ "navigatePrevious",
1369
+ "navigateToday",
1370
+ "goToDate",
1371
+ "setView",
1372
+ "setTimeZone",
1373
+ "selectEvent",
1374
+ "createEvent",
1375
+ "updateEvent",
1376
+ "moveEvent",
1377
+ "resizeEvent",
1378
+ "deleteEvent"
1379
+ ]);
1380
+ const conventions = "Dates are ISO 8601. A time without an offset is wall-clock time in timeZone; with an offset or Z it is that instant. Ranges include start and exclude end. Event IDs are listEvents' id values.";
1381
+ /** Every change an agent's action makes is the agent's, whatever else runs around it. */
1382
+ const asAgent = Object.freeze({ source: "agent" });
1383
+ const agentInput$1 = Object.freeze({ input: "agent" });
1384
+ /** How many of an agent's changes `getChange` remembers, per root. */
1385
+ const changeLogSize = 50;
1386
+ /**
1387
+ * The agent's changes by ID, per root: a framework may make an instance it then throws away, as
1388
+ * React's Strict Mode does, so the log outlives any one.
1389
+ */
1390
+ const changeLogs = /* @__PURE__ */ new WeakMap();
1391
+ function changeLogOf(runtime) {
1392
+ let log = changeLogs.get(runtime);
1393
+ if (log === void 0) {
1394
+ log = /* @__PURE__ */ new Map();
1395
+ changeLogs.set(runtime, log);
1396
+ }
1397
+ return log;
1398
+ }
1399
+ function remember(runtime, change) {
1400
+ const log = changeLogOf(runtime);
1401
+ log.delete(change.changeId);
1402
+ log.set(change.changeId, change);
1403
+ if (log.size > changeLogSize) log.delete(log.keys().next().value);
1404
+ return change;
1405
+ }
1406
+ function slicesOf(options) {
1407
+ const slices = {};
1408
+ for (const slice of calendarStateSlices) slices[slice] = options[slice];
1409
+ return Object.freeze(slices);
1410
+ }
1411
+ function modelOf(runtime) {
1412
+ const model = runtime.committed();
1413
+ if (model === void 0) throw new Error("calendar-primitive-before-first-derive");
1414
+ return model;
1415
+ }
1416
+ function agentChange(change, status, timeZone, reason) {
1417
+ return Object.freeze({
1418
+ cause: change.cause,
1419
+ changeId: change.id,
1420
+ eventId: change.eventId,
1421
+ proposed: change.proposed === null ? null : describeAgentPlacement(change.proposed, timeZone),
1422
+ ...reason === void 0 ? {} : { reason },
1423
+ status
1424
+ });
1425
+ }
1426
+ /** Why a change was turned down, with the handler's own message when it threw one. */
1427
+ function rejection(result) {
1428
+ const message = result.error instanceof Error ? result.error.message : void 0;
1429
+ return message === void 0 || message === "" ? `calendar-event-change-rejected: ${result.reason}` : `calendar-event-change-rejected: ${result.reason} (${message})`;
1430
+ }
1431
+ /** An action that takes nothing takes an empty object too, as some agents send one. */
1432
+ function noArguments(action, args) {
1433
+ const [first, ...extra] = args;
1434
+ if (first === void 0 && extra.every((arg) => arg === void 0)) return;
1435
+ readAgentInput(action, "nothing", first, {}, extra);
1436
+ }
1437
+ /**
1438
+ * Defines a calendar's ui-sdk primitive: the six state slices as always-controlled keys, the
1439
+ * semantic commands as its api, its chrome as slots, and what an AI agent may see and do. The
1440
+ * slices live in the calendar store and the application's props; the instance is a projection of
1441
+ * them for parts and agents, and every change goes through the root's store, which tells the
1442
+ * application's handlers.
1443
+ */
1444
+ function createCalendarPrimitive(config) {
1445
+ const viewNames = Object.freeze(config.views.map((view) => view.name));
1446
+ const registered = new Set(viewNames);
1447
+ return definePrimitive({
1448
+ name: "calendar",
1449
+ options: {
1450
+ allowAgentDelete: "boolean",
1451
+ anchorDate: "value",
1452
+ expandedResourceIds: "value",
1453
+ focus: "value",
1454
+ formatAgentEventLabel: "value",
1455
+ runtime: "value",
1456
+ selection: "value",
1457
+ timeZone: "string",
1458
+ view: "string"
1459
+ },
1460
+ controlled: [
1461
+ "anchorDate",
1462
+ "view",
1463
+ "timeZone",
1464
+ "selection",
1465
+ "focus",
1466
+ "expandedResourceIds"
1467
+ ],
1468
+ state: (options) => slicesOf(options),
1469
+ sync: (options) => slicesOf(options),
1470
+ api: (context) => {
1471
+ const runtime = () => context.options().runtime;
1472
+ const actions = () => modelOf(runtime()).actions;
1473
+ /**
1474
+ * The bridge offers an action only while the api has it, so the event changes are getters
1475
+ * that hide on a read-only root, and delete unless the root allows it. ui-sdk checks in
1476
+ * development that every listed action exists as the instance is made, so they all show
1477
+ * until then.
1478
+ */
1479
+ let made = false;
1480
+ queueMicrotask(() => made = true);
1481
+ const canChange = () => !modelOf(runtime()).isReadOnly;
1482
+ const canDelete = () => canChange() && context.options().allowAgentDelete === true;
1483
+ const offered = (available, method) => !made || available() ? method : void 0;
1484
+ /** The application's events with the changes still pending, as the next render shows them. */
1485
+ function currentEvents() {
1486
+ const model = modelOf(runtime());
1487
+ return applyEventOverlay(model.eventSnapshot, runtime().transactions.getPending());
1488
+ }
1489
+ /** The state and range the latest commands asked for, before a framework renders them. */
1490
+ function latest() {
1491
+ const model = modelOf(runtime());
1492
+ const current = runtime().latest();
1493
+ const state = current?.state ?? model.state;
1494
+ return {
1495
+ model,
1496
+ range: current === void 0 ? model.activeView?.range ?? null : current.range,
1497
+ state
1498
+ };
1499
+ }
1500
+ function describeEvents(range) {
1501
+ if (range === null) return [];
1502
+ const { model, state } = latest();
1503
+ const environment = {
1504
+ ...model.viewEnvironment,
1505
+ timeZone: state.timeZone
1506
+ };
1507
+ return eventsInRange(currentEvents(), range, environment).map((event) => describeAgentEvent(event, environment));
1508
+ }
1509
+ /**
1510
+ * Proposes an agent's change once: a refusal the policies or the handler give at once fails
1511
+ * the step with its reason, and a change still saving returns where it is. Its outcome
1512
+ * reaches `onEventChangeResult` once, and the agent's log, so a late failure is never an
1513
+ * unhandled rejection.
1514
+ */
1515
+ function propose(proposal, fields) {
1516
+ const root = runtime();
1517
+ const timeZone = latest().state.timeZone;
1518
+ const detail = fields === void 0 ? agentInput$1 : Object.freeze({
1519
+ fields,
1520
+ input: "agent"
1521
+ });
1522
+ const outcome = root.proposeNow(proposal, detail);
1523
+ if (outcome.status === "rejected") {
1524
+ if (outcome.change !== void 0) remember(root, agentChange(outcome.change, "rejected", timeZone, outcome.reason));
1525
+ throw new Error(rejection(outcome), { cause: outcome.error });
1526
+ }
1527
+ if (outcome.status === "committed") return remember(root, agentChange(outcome.change, "saved", timeZone));
1528
+ outcome.result.then((result) => {
1529
+ const change = result.change ?? outcome.change;
1530
+ remember(root, result.status === "committed" ? agentChange(change, "saved", timeZone) : agentChange(change, "rejected", timeZone, result.reason));
1531
+ });
1532
+ return remember(root, agentChange(outcome.change, outcome.phase, timeZone));
1533
+ }
1534
+ function checkedView(view) {
1535
+ if (typeof view === "string" && registered.has(view)) return view;
1536
+ throw new RangeError(`calendar-unknown-view: ${JSON.stringify(view)} is not a registered view. Views: ${viewNames.map((name) => JSON.stringify(name)).join(", ")}`);
1537
+ }
1538
+ function eventOf(input) {
1539
+ return findEvent(currentEvents(), readEventId(input.eventId));
1540
+ }
1541
+ function environment() {
1542
+ const { model, state } = latest();
1543
+ return {
1544
+ ...model.viewEnvironment,
1545
+ timeZone: state.timeZone
1546
+ };
1547
+ }
1548
+ const createEvent = (input, ...extra) => {
1549
+ const args = readAgentInput("createEvent", signatures.createEvent, input, {
1550
+ end: true,
1551
+ fields: false,
1552
+ resourceIds: false,
1553
+ start: true,
1554
+ title: false
1555
+ }, extra);
1556
+ return propose({
1557
+ cause: "create",
1558
+ proposed: createdPlacement(args.start, args.end, args.resourceIds, environment(), modelOf(runtime()).resourceTree.byId)
1559
+ }, readFields(args));
1560
+ };
1561
+ const updateEvent = (input, ...extra) => {
1562
+ const args = readAgentInput("updateEvent", signatures.updateEvent, input, {
1563
+ end: false,
1564
+ eventId: true,
1565
+ fields: false,
1566
+ resourceIds: false,
1567
+ start: false,
1568
+ title: false
1569
+ }, extra);
1570
+ const { end, fields, resourceIds, start, title } = args;
1571
+ if ([
1572
+ end,
1573
+ fields,
1574
+ resourceIds,
1575
+ start,
1576
+ title
1577
+ ].every((value) => value === void 0)) throw new TypeError(`calendar-agent-invalid-arguments: updateEvent changes something: ${signatures.updateEvent}`);
1578
+ const event = eventOf(args);
1579
+ const placement = movedPlacement(event, args.start ?? event.start, args.start === void 0 && args.end === void 0 ? event.end : args.end, environment());
1580
+ return propose({
1581
+ cause: "update",
1582
+ eventId: event.id,
1583
+ proposed: args.resourceIds === void 0 ? placement : {
1584
+ ...placement,
1585
+ resourceIds: readResourceIds(args.resourceIds, modelOf(runtime()).resourceTree.byId)
1586
+ }
1587
+ }, readFields(args));
1588
+ };
1589
+ const moveEvent = (input, ...extra) => {
1590
+ const args = readAgentInput("moveEvent", signatures.moveEvent, input, {
1591
+ end: false,
1592
+ eventId: true,
1593
+ resourceIds: false,
1594
+ start: true
1595
+ }, extra);
1596
+ const event = eventOf(args);
1597
+ const placement = movedPlacement(event, args.start, args.end, environment());
1598
+ return propose({
1599
+ cause: "move",
1600
+ eventId: event.id,
1601
+ proposed: args.resourceIds === void 0 ? placement : {
1602
+ ...placement,
1603
+ resourceIds: readResourceIds(args.resourceIds, modelOf(runtime()).resourceTree.byId)
1604
+ }
1605
+ }, void 0);
1606
+ };
1607
+ const resizeEvent = (input, ...extra) => {
1608
+ const args = readAgentInput("resizeEvent", signatures.resizeEvent, input, {
1609
+ end: false,
1610
+ eventId: true,
1611
+ start: false
1612
+ }, extra);
1613
+ if (args.start === void 0 === (args.end === void 0)) throw new TypeError(`calendar-agent-invalid-arguments: resizeEvent takes one of start and end: ${signatures.resizeEvent}`);
1614
+ const event = eventOf(args);
1615
+ const fromStart = args.start !== void 0;
1616
+ return propose({
1617
+ cause: fromStart ? "resize-start" : "resize-end",
1618
+ eventId: event.id,
1619
+ proposed: fromStart ? movedPlacement(event, args.start, event.end, environment()) : movedPlacement(event, event.start, args.end, environment())
1620
+ }, void 0);
1621
+ };
1622
+ const deleteEvent = (input, ...extra) => {
1623
+ const proposal = {
1624
+ cause: "delete",
1625
+ eventId: eventOf(readAgentInput("deleteEvent", signatures.deleteEvent, input, { eventId: true }, extra)).id
1626
+ };
1627
+ if (!canDelete() && modelOf(runtime()).actions.checkEventChange(proposal, agentInput$1)?.status !== "rejected") throw new Error(`calendar-event-change-rejected: ${canChange() ? "agent-delete-not-allowed" : "read-only"}`);
1628
+ return propose(proposal, void 0);
1629
+ };
1630
+ const api = {
1631
+ get createEvent() {
1632
+ return offered(canChange, createEvent);
1633
+ },
1634
+ get deleteEvent() {
1635
+ return offered(canDelete, deleteEvent);
1636
+ },
1637
+ describeCalendar(...args) {
1638
+ noArguments("describeCalendar", args);
1639
+ const { model, range, state } = latest();
1640
+ const { environment: root } = model;
1641
+ const now = (root.now ?? clockOf(root).instant()).toZonedDateTimeISO(state.timeZone);
1642
+ const available = Object.fromEntries(calendarAgentActions.filter((action) => typeof api[action] === "function").map((action) => [action, signatures[action]]));
1643
+ const selection = state.selection;
1644
+ return Object.freeze({
1645
+ actions: Object.freeze(available),
1646
+ anchorDate: state.anchorDate.toString(),
1647
+ canDelete: canDelete(),
1648
+ conventions,
1649
+ locale: String(root.locale),
1650
+ now: now.toString({ timeZoneName: "never" }),
1651
+ pendingChanges: Object.freeze([...runtime().pendingChanges.getSnapshot().values()].filter(({ phase }) => phase !== "awaiting-events").map(({ change, phase }) => agentChange(change, phase === "validating" ? "validating" : "saving", state.timeZone))),
1652
+ readOnly: model.isReadOnly,
1653
+ resources: Object.freeze([...model.resourceTree.byId.values()].map((node) => Object.freeze({
1654
+ id: node.id,
1655
+ parentId: node.parentId,
1656
+ title: node.resource.title
1657
+ }))),
1658
+ selectedEventId: selection?.kind === "event" ? selection.eventId : null,
1659
+ timeZone: state.timeZone,
1660
+ today: now.toPlainDate().toString(),
1661
+ view: state.view,
1662
+ views: viewNames,
1663
+ visibleRange: range === null ? null : Object.freeze({
1664
+ end: range.end.toString(),
1665
+ start: range.start.toString()
1666
+ })
1667
+ });
1668
+ },
1669
+ getChange(input, ...extra) {
1670
+ const args = readAgentInput("getChange", signatures.getChange, input, { changeId: true }, extra);
1671
+ const root = runtime();
1672
+ const known = changeLogOf(root).get(String(args.changeId));
1673
+ if (known !== void 0) return known;
1674
+ const pending = root.pendingChanges.getSnapshot().get(String(args.changeId));
1675
+ if (pending !== void 0) return agentChange(pending.change, pending.phase === "validating" ? "validating" : pending.phase === "saving" ? "saving" : "saved", latest().state.timeZone);
1676
+ const ids = [...changeLogOf(root).keys()].slice(-10).map((id) => JSON.stringify(id));
1677
+ throw new RangeError(`calendar-agent-unknown-change: no change has the ID ${JSON.stringify(args.changeId)}. Recent changes: ${ids.length === 0 ? "none" : ids.join(", ")}`);
1678
+ },
1679
+ goToDate(input, ...extra) {
1680
+ const args = readAgentInput("goToDate", signatures.goToDate, input, { date: true }, extra);
1681
+ actions().setAnchorDate(parsePlainDate(args.date, "date"), asAgent);
1682
+ },
1683
+ listEvents(input, ...extra) {
1684
+ const args = readAgentInput("listEvents", signatures.listEvents, input ?? {}, {
1685
+ end: false,
1686
+ start: false
1687
+ }, extra);
1688
+ const visible = latest().range;
1689
+ if (args.start === void 0 && args.end === void 0) return Object.freeze(describeEvents(visible));
1690
+ const start = args.start === void 0 ? visible?.start : parsePlainDate(args.start, "start");
1691
+ const end = args.end === void 0 ? visible?.end : parsePlainDate(args.end, "end");
1692
+ if (start === void 0 || end === void 0 || Temporal.PlainDate.compare(start, end) >= 0) throw new RangeError(`calendar-agent-invalid-range: listEvents takes a start before its end, not ${JSON.stringify(input)}`);
1693
+ return Object.freeze(describeEvents(plainDateInterval(start, end)));
1694
+ },
1695
+ get moveEvent() {
1696
+ return offered(canChange, moveEvent);
1697
+ },
1698
+ navigateNext(...args) {
1699
+ noArguments("navigateNext", args);
1700
+ actions().navigateNext(asAgent);
1701
+ },
1702
+ navigatePrevious(...args) {
1703
+ noArguments("navigatePrevious", args);
1704
+ actions().navigatePrevious(asAgent);
1705
+ },
1706
+ navigateToday(...args) {
1707
+ noArguments("navigateToday", args);
1708
+ actions().navigateToday(asAgent);
1709
+ },
1710
+ get resizeEvent() {
1711
+ return offered(canChange, resizeEvent);
1712
+ },
1713
+ selectEvent(input, ...extra) {
1714
+ const args = readAgentInput("selectEvent", signatures.selectEvent, input, { eventId: true }, extra, ["eventId"]);
1715
+ const selection = args.eventId === null ? null : {
1716
+ eventId: eventOf(args).id,
1717
+ kind: "event"
1718
+ };
1719
+ actions().setSelection(selection, asAgent);
1720
+ },
1721
+ selectView(view, options) {
1722
+ if (!registered.has(view)) return false;
1723
+ actions().setView(view, options);
1724
+ return true;
1725
+ },
1726
+ setTimeZone(input, ...extra) {
1727
+ const args = readAgentInput("setTimeZone", signatures.setTimeZone, input, { timeZone: true }, extra);
1728
+ actions().setTimeZone(parseTimeZone(args.timeZone), asAgent);
1729
+ },
1730
+ setView(input, ...extra) {
1731
+ const args = readAgentInput("setView", signatures.setView, input, { view: true }, extra);
1732
+ actions().setView(checkedView(args.view), asAgent);
1733
+ },
1734
+ showNext: (options) => actions().navigateNext(options),
1735
+ showPrevious: (options) => actions().navigatePrevious(options),
1736
+ showToday: (options) => actions().navigateToday(options),
1737
+ get updateEvent() {
1738
+ return offered(canChange, updateEvent);
1739
+ },
1740
+ viewNames: () => viewNames,
1741
+ visibleEvents() {
1742
+ if (runtime().committed() === void 0) return [];
1743
+ const { model } = latest();
1744
+ const timeZone = latest().state.timeZone;
1745
+ const format = context.options().formatAgentEventLabel;
1746
+ return describeEvents(latest().range ?? model.activeView?.range ?? null).map((event) => Object.freeze({
1747
+ label: format === void 0 ? agentEventLabel(event, timeZone) : format(event),
1748
+ value: String(event.id)
1749
+ }));
1750
+ }
1751
+ };
1752
+ return Object.freeze(api);
1753
+ },
1754
+ slots: (slot) => ({
1755
+ root: slot({}),
1756
+ toolbar: slot({}),
1757
+ title: slot({}),
1758
+ viewport: slot({}),
1759
+ "previous-trigger": slot({ press: ({ api }, event) => api.showPrevious({
1760
+ event,
1761
+ reason: "previous-press"
1762
+ }) }),
1763
+ "next-trigger": slot({ press: ({ api }, event) => api.showNext({
1764
+ event,
1765
+ reason: "next-press"
1766
+ }) }),
1767
+ "today-trigger": slot({ press: ({ api }, event) => api.showToday({
1768
+ event,
1769
+ reason: "today-press"
1770
+ }) }),
1771
+ "view-switcher": slot({})
1772
+ }),
1773
+ agent: {
1774
+ actions: [...calendarAgentActions],
1775
+ items: (api) => api.visibleEvents()
1776
+ }
1777
+ });
1778
+ }
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
+ });
2133
+ }
2134
+ // src/views.ts
2135
+ /** Applies a root's partial overrides to a view's `defaultOptions`. */
2136
+ function resolveViewOptions(view, overrides) {
2137
+ return overrides === void 0 ? view.defaultOptions : {
2138
+ ...view.defaultOptions,
2139
+ ...overrides
2140
+ };
2141
+ }
2142
+ // src/runtime.ts
2143
+ const noResources = Object.freeze([]);
2144
+ const noAnnotations = Object.freeze([]);
2145
+ const noSecondaryTimeZones = Object.freeze([]);
2146
+ /** A root without `onEventChange` is read-only, so its checks reject everything. */
2147
+ const readOnlyRoot = () => ({
2148
+ reason: "read-only",
2149
+ type: "reject"
2150
+ });
2151
+ /** A read-only root's handler: its check rejects every change first, so this never runs. */
2152
+ const noHandler = () => {
2153
+ throw new TypeError("calendar-root-is-read-only");
2154
+ };
2155
+ /** The detail of a proposal made without one, or with something that names no input. */
2156
+ const apiInput = Object.freeze({ input: "api" });
2157
+ const agentInput = Object.freeze({ input: "agent" });
2158
+ const knownInputs = /* @__PURE__ */ new Set([
2159
+ "agent",
2160
+ "api",
2161
+ "keyboard",
2162
+ "pointer"
2163
+ ]);
2164
+ /**
2165
+ * The source ui-sdk gives a change made now, read the one way its public entries offer: an event
2166
+ * option `dispatch` calls with the details a change would get. While an agent's step runs, such as
2167
+ * a press on the application's own button, that is `"agent"`; the state handlers hear the same.
2168
+ * The probe is a handler of our own, so nothing else hears it and nothing changes.
2169
+ */
2170
+ let probed;
2171
+ const sourceProbe = Object.freeze({ options: () => probeOptions });
2172
+ const probeOptions = Object.freeze({ onSourceProbe: (_value, details) => {
2173
+ probed = details.source;
2174
+ } });
2175
+ function currentSource() {
2176
+ probed = void 0;
2177
+ dispatch(sourceProbe, "onSourceProbe", null, { reason: "imperative" });
2178
+ return probed;
2179
+ }
2180
+ /**
2181
+ * The detail every listener hears. Anything an agent's step causes is the agent's, whatever the
2182
+ * caller passed, so a policy that refuses agents can't be stepped around by pressing a button;
2183
+ * the rest of the detail, such as a history's `history`, is kept.
2184
+ */
2185
+ function detailOf(detail) {
2186
+ if (detail?.input !== "agent" && currentSource() === "agent") return detail === void 0 ? agentInput : Object.freeze({
2187
+ ...detail,
2188
+ input: "agent"
2189
+ });
2190
+ return detail !== void 0 && knownInputs.has(detail.input) ? detail : apiInput;
2191
+ }
2192
+ /**
2193
+ * An agent deletes only where the root allows it with `allowAgentDelete`, however it got there:
2194
+ * through the calendar's own action or a button of the application's it pressed. The application
2195
+ * hears the refusal like any other, through `onEventChangeResult`.
2196
+ */
2197
+ const noAgentDeletes = ((change, { detail }) => change.cause === "delete" && detail?.input === "agent" ? {
2198
+ reason: "agent-delete-not-allowed",
2199
+ type: "reject"
2200
+ } : { type: "accept" });
2201
+ function sameLocale(left, right) {
2202
+ return String(left) === String(right);
2203
+ }
2204
+ function sameIssue(left, right) {
2205
+ return left.code === right.code && left.index === right.index && left.eventId === right.eventId && left.accessor === right.accessor && left.message === right.message && left.resourceIndex === right.resourceIndex;
2206
+ }
2207
+ function sameDiagnostics(left, right) {
2208
+ return left.length === right.length && left.every((diagnostic, index) => {
2209
+ const other = right[index];
2210
+ if (other === void 0 || other.code !== diagnostic.code) return false;
2211
+ switch (diagnostic.code) {
2212
+ case "invalid-event": return other.code === "invalid-event" && sameIssue(diagnostic.issue, other.issue);
2213
+ case "invalid-annotation": return other.code === "invalid-annotation" && other.issue.annotation === diagnostic.issue.annotation && other.issue.code === diagnostic.issue.code && other.issue.index === diagnostic.issue.index;
2214
+ case "invalid-availability": return other.code === "invalid-availability" && other.issue.code === diagnostic.issue.code && other.issue.resourceId === diagnostic.issue.resourceId && other.issue.value === diagnostic.issue.value;
2215
+ case "invalid-secondary-time-zone": return other.code === "invalid-secondary-time-zone" && other.issue.index === diagnostic.issue.index && other.issue.value === diagnostic.issue.value;
2216
+ case "unregistered-active-view": return other.code === "unregistered-active-view" && other.viewName === diagnostic.viewName;
2217
+ }
2218
+ });
2219
+ }
2220
+ function collectDiagnostics(view, viewIsRegistered, issues, annotationIssues, availabilityIssues, secondaryTimeZoneIssues) {
2221
+ const diagnostics = [];
2222
+ if (!viewIsRegistered) diagnostics.push(Object.freeze({
2223
+ code: "unregistered-active-view",
2224
+ severity: "error",
2225
+ viewName: view
2226
+ }));
2227
+ for (const issue of issues) diagnostics.push(Object.freeze({
2228
+ code: "invalid-event",
2229
+ issue,
2230
+ severity: "error"
2231
+ }));
2232
+ for (const issue of annotationIssues) diagnostics.push(Object.freeze({
2233
+ code: "invalid-annotation",
2234
+ issue,
2235
+ severity: "error"
2236
+ }));
2237
+ for (const issue of availabilityIssues) diagnostics.push(Object.freeze({
2238
+ code: "invalid-availability",
2239
+ issue,
2240
+ severity: "error"
2241
+ }));
2242
+ for (const issue of secondaryTimeZoneIssues) diagnostics.push(Object.freeze({
2243
+ code: "invalid-secondary-time-zone",
2244
+ issue,
2245
+ severity: "error"
2246
+ }));
2247
+ return Object.freeze(diagnostics);
2248
+ }
2249
+ function sameControlledState(left, right) {
2250
+ return samePlainDate(left.anchorDate, right.anchorDate) && (left.expandedResourceIds === right.expandedResourceIds || left.expandedResourceIds !== void 0 && right.expandedResourceIds !== void 0 && sameElements(left.expandedResourceIds, right.expandedResourceIds)) && Object.is(left.focus, right.focus) && Object.is(left.selection, right.selection) && left.timeZone === right.timeZone && left.view === right.view;
2251
+ }
2252
+ function createStateSource(store, controlled) {
2253
+ let base;
2254
+ let merged;
2255
+ return Object.freeze({
2256
+ getSnapshot: () => {
2257
+ const next = store.getSnapshot();
2258
+ if (next !== base || merged === void 0) {
2259
+ base = next;
2260
+ merged = mergeControlledState(next, controlled);
2261
+ }
2262
+ return merged;
2263
+ },
2264
+ subscribe: store.subscribe
2265
+ });
2266
+ }
2267
+ function createSemanticActions({ actions, read }, viewsByName, committed, transactions, readOnly) {
2268
+ /** The policies every change runs through; a root without `onEventChange` rejects them all. */
2269
+ function policiesOf({ allowAgentDelete, onEventChange, policies = [] }) {
2270
+ if (onEventChange === void 0) return [readOnlyRoot];
2271
+ return allowAgentDelete === true ? [readOnly, ...policies] : [
2272
+ readOnly,
2273
+ noAgentDeletes,
2274
+ ...policies
2275
+ ];
2276
+ }
2277
+ function navigate(delta, options) {
2278
+ const latest = read();
2279
+ const view = viewsByName.get(latest.view);
2280
+ if (view === void 0) return;
2281
+ const viewOptions = resolveViewOptions(view, committed.current.viewOptions?.[latest.view]);
2282
+ actions.setAnchorDate(view.strategy.navigate(latest.anchorDate, delta, viewOptions), options);
2283
+ }
2284
+ /** Proposes a change through the policies once, with the detail every listener hears. */
2285
+ function start(proposal, detail) {
2286
+ const { availability, eventSnapshot, onEventChange } = committed.current;
2287
+ const reported = detailOf(detail);
2288
+ return {
2289
+ outcome: transactions.proposeNow(proposal, {
2290
+ availability,
2291
+ detail: reported,
2292
+ onEventChange: onEventChange ?? noHandler,
2293
+ policies: policiesOf(committed.current),
2294
+ snapshot: eventSnapshot,
2295
+ timeZone: read().timeZone
2296
+ }),
2297
+ reported
2298
+ };
2299
+ }
2300
+ function report(result, detail) {
2301
+ try {
2302
+ committed.current.onEventChangeResult?.(result, detail);
2303
+ } catch (error) {
2304
+ reportCallbackError(error);
2305
+ }
2306
+ return result;
2307
+ }
2308
+ /**
2309
+ * `proposeEventChange` that answers at once when it can: what an agent's step returns before a
2310
+ * framework renders. The result callback hears every proposal once, when it settles.
2311
+ */
2312
+ function proposeNow(proposal, detail) {
2313
+ const { outcome, reported } = start(proposal, detail);
2314
+ if (outcome.status !== "pending") return report(outcome, reported);
2315
+ return Object.freeze({
2316
+ ...outcome,
2317
+ result: outcome.result.then((result) => report(result, reported))
2318
+ });
2319
+ }
2320
+ return {
2321
+ actions: Object.freeze({
2322
+ ...actions,
2323
+ checkEventChange(proposal, detail) {
2324
+ const { availability, eventSnapshot } = committed.current;
2325
+ return transactions.check(proposal, {
2326
+ availability,
2327
+ detail: detailOf(detail),
2328
+ policies: policiesOf(committed.current),
2329
+ snapshot: eventSnapshot,
2330
+ timeZone: read().timeZone
2331
+ });
2332
+ },
2333
+ navigateNext: (options) => navigate(1, options),
2334
+ navigatePrevious: (options) => navigate(-1, options),
2335
+ navigateToday(options) {
2336
+ const { environment } = committed.current;
2337
+ const instant = environment.now ?? (environment.clock ?? systemClock).instant();
2338
+ actions.setAnchorDate(instant.toZonedDateTimeISO(read().timeZone).toPlainDate(), options);
2339
+ },
2340
+ proposeEventChange(proposal, detail) {
2341
+ const { outcome, reported } = start(proposal, detail);
2342
+ return (outcome.status === "pending" ? outcome.result : Promise.resolve(outcome)).then((result) => report(result, reported));
2343
+ }
2344
+ }),
2345
+ proposeNow
2346
+ };
2347
+ }
2348
+ /**
2349
+ * The store defaults a root's props give, for `connect`'s `defaults`: a default wins over a
2350
+ * controlled value, and the first registered view stands in for a missing one.
2351
+ */
2352
+ function resolveCalendarStoreDefaults(props, views) {
2353
+ const initialAnchorDate = props.defaultAnchorDate ?? props.anchorDate;
2354
+ const initialTimeZone = props.defaultTimeZone ?? props.timeZone;
2355
+ const initialView = props.defaultView ?? props.view ?? views[0]?.name;
2356
+ if (initialAnchorDate === void 0) throw new TypeError("calendar-root-requires-anchor-date");
2357
+ if (initialTimeZone === void 0) throw new TypeError("calendar-root-requires-time-zone");
2358
+ if (initialView === void 0) throw new TypeError("calendar-root-requires-view");
2359
+ return {
2360
+ defaultAnchorDate: initialAnchorDate,
2361
+ defaultExpandedResourceIds: props.defaultExpandedResourceIds,
2362
+ defaultFocus: props.defaultFocus,
2363
+ defaultSelection: props.defaultSelection,
2364
+ defaultTimeZone: initialTimeZone,
2365
+ defaultView: initialView
2366
+ };
2367
+ }
2368
+ function createCalendarRuntime(config) {
2369
+ const views = Object.freeze([...config.views]);
2370
+ const viewsByName = new Map(views.map((view) => [view.name, view]));
2371
+ const readOnly = readOnlyPolicy();
2372
+ const snapshotCache = createEventSnapshotCache(config.eventAdapter, { invalidEventPolicy: config.invalidEventPolicy });
2373
+ const transactions = createEventTransactions();
2374
+ const keyboard = createKeyboardSessionStore();
2375
+ const pointerDraft = createDraftStore();
2376
+ const draft = createDraftSource(keyboard, pointerDraft);
2377
+ const noChanges = transactions.getPendingChanges();
2378
+ const pendingChanges = Object.freeze({
2379
+ getServerSnapshot: () => noChanges,
2380
+ getSnapshot: transactions.getPendingChanges,
2381
+ subscribe: transactions.subscribe
2382
+ });
2383
+ let overlaySnapshot = Object.freeze({
2384
+ pending: transactions.getPending(),
2385
+ preview: keyboard.getPreview()
2386
+ });
2387
+ const overlay = Object.freeze({
2388
+ getSnapshot: () => {
2389
+ const pending = transactions.getPending();
2390
+ const preview = keyboard.getPreview();
2391
+ if (pending !== overlaySnapshot.pending || preview !== overlaySnapshot.preview) overlaySnapshot = Object.freeze({
2392
+ pending,
2393
+ preview
2394
+ });
2395
+ return overlaySnapshot;
2396
+ },
2397
+ subscribe: (listener) => {
2398
+ const stops = [transactions.subscribe(listener), keyboard.subscribe(listener)];
2399
+ return () => {
2400
+ for (const stop of stops) stop();
2401
+ };
2402
+ }
2403
+ });
2404
+ /** Each model's actions' `proposeNow`, which the runtime's own reads from the last commit. */
2405
+ const proposers = /* @__PURE__ */ new WeakMap();
2406
+ let committedInputs;
2407
+ let committedModel;
2408
+ let reportedRange = null;
2409
+ const announcements = createAnnouncerChannel(() => committedInputs.current.environment, () => committedInputs.current.resourceTree);
2410
+ let ownedStore;
2411
+ const bindingCell = createMemoCell();
2412
+ const controlledCell = createStableCell(sameControlledState);
2413
+ const sourceCell = createMemoCell();
2414
+ const connectionCell = createMemoCell();
2415
+ const uncommittedBinding = Object.freeze({
2416
+ controlled: {},
2417
+ handlers: {}
2418
+ });
2419
+ const locale = createStableCell(sameLocale);
2420
+ const weekRules = createStableCell(sameWeekRules);
2421
+ const now = createStableCell(sameInstant);
2422
+ const secondaryInput = createStableCell(sameSecondaryTimeZones);
2423
+ const secondaryCell = createMemoCell();
2424
+ const viewEnvironmentCell = createMemoCell();
2425
+ const environmentCell = createMemoCell();
2426
+ const eventsInput = createStableCell(sameElements);
2427
+ const eventSnapshotCell = createMemoCell();
2428
+ const visibleEventsCell = createMemoCell();
2429
+ const resourcesInput = createStableCell(sameElements);
2430
+ const resourceTreeCell = createMemoCell();
2431
+ const expandedInput = createStableCell(sameElements);
2432
+ const annotationsInput = createStableCell(sameElements);
2433
+ const annotationSnapshotCell = createMemoCell();
2434
+ const annotationSourcesInput = createStableCell(sameElements);
2435
+ const annotationsCell = createMemoCell();
2436
+ const availabilityInput = createStableCell(sameAvailability);
2437
+ const availabilityCell = createMemoCell();
2438
+ const optionsInput = createStableCell(shallowEqual);
2439
+ const rangeInput = createStableCell(sameRange);
2440
+ const loadRangeInput = createStableCell(sameRange);
2441
+ const todayInput = createStableCell(samePlainDate);
2442
+ const visibleRangeCell = createMemoCell();
2443
+ const activeViewCell = createMemoCell();
2444
+ const diagnosticsInput = createStableCell(sameDiagnostics);
2445
+ const actionsCell = createMemoCell();
2446
+ const interactionCell = createMemoCell();
2447
+ const modelCell = createMemoCell();
2448
+ function connect({ controlled: controlledInput, defaults, store: injected }) {
2449
+ if (injected === void 0) ownedStore ??= createCalendarStore(defaults());
2450
+ const store = injected ?? ownedStore;
2451
+ const internals = getCalendarStoreInternals(store);
2452
+ const controlled = controlledCell(controlledInput);
2453
+ const binding = bindingCell([internals], () => internals.bind(uncommittedBinding));
2454
+ const source = sourceCell([controlled, store], () => createStateSource(store, controlled));
2455
+ return connectionCell([
2456
+ binding,
2457
+ controlled,
2458
+ source,
2459
+ store
2460
+ ], () => Object.freeze({
2461
+ binding,
2462
+ controlled,
2463
+ source,
2464
+ store
2465
+ }));
2466
+ }
2467
+ function committedOf(inputs, model) {
2468
+ return {
2469
+ activeView: model.activeView,
2470
+ allowAgentDelete: inputs.allowAgentDelete,
2471
+ availability: model.availability,
2472
+ environment: model.environment,
2473
+ eventSnapshot: model.eventSnapshot,
2474
+ onDiagnosticsChange: inputs.onDiagnosticsChange,
2475
+ onEventChange: inputs.onEventChange,
2476
+ onEventChangeResult: inputs.onEventChangeResult,
2477
+ onVisibleRangeChange: inputs.onVisibleRangeChange,
2478
+ policies: inputs.policies,
2479
+ resourceTree: model.resourceTree,
2480
+ viewOptions: inputs.viewOptions
2481
+ };
2482
+ }
2483
+ function derive(inputs) {
2484
+ const { connection, state } = inputs;
2485
+ const stableLocale = locale(inputs.locale);
2486
+ const stableWeekRules = weekRules(inputs.weekRules);
2487
+ const stableNow = now(inputs.now);
2488
+ const stableSecondary = secondaryInput(inputs.secondaryTimeZones ?? noSecondaryTimeZones);
2489
+ const secondary = secondaryCell([stableSecondary], () => resolveSecondaryTimeZones(stableSecondary));
2490
+ const direction = inputs.direction ?? "ltr";
2491
+ const disambiguation = inputs.disambiguation ?? "compatible";
2492
+ const viewEnvironment = viewEnvironmentCell([
2493
+ direction,
2494
+ disambiguation,
2495
+ secondary.zones,
2496
+ stableLocale,
2497
+ stableWeekRules,
2498
+ state.timeZone
2499
+ ], () => Object.freeze({
2500
+ direction,
2501
+ disambiguation,
2502
+ locale: stableLocale,
2503
+ secondaryTimeZones: secondary.zones,
2504
+ timeZone: state.timeZone,
2505
+ weekRules: stableWeekRules
2506
+ }));
2507
+ const { clock } = inputs;
2508
+ const environment = environmentCell([
2509
+ clock,
2510
+ stableNow,
2511
+ viewEnvironment
2512
+ ], () => {
2513
+ if (stableNow !== void 0) return Object.freeze({
2514
+ ...viewEnvironment,
2515
+ now: stableNow
2516
+ });
2517
+ if (clock !== void 0) return Object.freeze({
2518
+ ...viewEnvironment,
2519
+ clock
2520
+ });
2521
+ return viewEnvironment;
2522
+ });
2523
+ const stableEvents = eventsInput(inputs.events);
2524
+ const eventSnapshot = eventSnapshotCell([stableEvents], () => snapshotCache.getSnapshot(stableEvents));
2525
+ const { pending, preview } = inputs.overlay;
2526
+ const visibleEvents = visibleEventsCell([
2527
+ eventSnapshot,
2528
+ pending,
2529
+ preview
2530
+ ], () => applyEventOverlay(applyEventOverlay(eventSnapshot, pending), preview));
2531
+ const resources = resourcesInput(inputs.resources ?? noResources);
2532
+ const resourceTree = resourceTreeCell([resources], () => createResourceTree(resources));
2533
+ const expandedResourceIds = expandedInput(state.expandedResourceIds);
2534
+ const annotationList = annotationsInput(inputs.annotations ?? noAnnotations);
2535
+ const annotationSnapshot = annotationSnapshotCell([annotationList], () => createAnnotationSnapshot(annotationList));
2536
+ const annotationSources = annotationSourcesInput(inputs.annotationSources ?? noAnnotations);
2537
+ const annotations = annotationsCell([annotationSnapshot, annotationSources], () => Object.freeze({
2538
+ snapshot: annotationSnapshot,
2539
+ sources: annotationSources
2540
+ }));
2541
+ const availabilityRules = availabilityInput(inputs.availability);
2542
+ const availability = availabilityCell([
2543
+ availabilityRules,
2544
+ resources,
2545
+ state.timeZone
2546
+ ], () => createAvailabilitySnapshot({
2547
+ availability: availabilityRules,
2548
+ resources,
2549
+ timeZone: state.timeZone
2550
+ }));
2551
+ const activeDefinition = viewsByName.get(state.view);
2552
+ const viewOverrides = inputs.viewOptions;
2553
+ const options = optionsInput(activeDefinition === void 0 ? void 0 : resolveViewOptions(activeDefinition, viewOverrides?.[state.view]));
2554
+ const range = rangeInput(activeDefinition?.strategy.getRange(state.anchorDate, viewEnvironment, options));
2555
+ const loadRange = loadRangeInput(activeDefinition === void 0 || range === void 0 ? void 0 : resolveViewLoadRange(activeDefinition.strategy, state.anchorDate, viewEnvironment, options, range));
2556
+ const { instant } = inputs;
2557
+ const today = todayInput(instant === null ? null : instant.toZonedDateTimeISO(state.timeZone).toPlainDate());
2558
+ const visibleRange = visibleRangeCell([
2559
+ activeDefinition,
2560
+ loadRange,
2561
+ range,
2562
+ viewEnvironment.timeZone
2563
+ ], () => activeDefinition === void 0 || range === void 0 || loadRange === void 0 ? null : Object.freeze({
2564
+ instantRange: resolveViewInstantRange(range, viewEnvironment.timeZone),
2565
+ loadInstantRange: resolveViewInstantRange(loadRange, viewEnvironment.timeZone),
2566
+ loadRange,
2567
+ range,
2568
+ view: activeDefinition.name
2569
+ }));
2570
+ const activeView = activeViewCell([
2571
+ activeDefinition,
2572
+ options,
2573
+ visibleRange,
2574
+ resourceTree,
2575
+ expandedResourceIds,
2576
+ today,
2577
+ viewEnvironment,
2578
+ visibleEvents
2579
+ ], () => {
2580
+ if (activeDefinition === void 0 || visibleRange === null) return null;
2581
+ const { instantRange, loadInstantRange, loadRange, range } = visibleRange;
2582
+ return Object.freeze({
2583
+ definition: activeDefinition,
2584
+ environment: viewEnvironment,
2585
+ events: visibleEvents,
2586
+ instantRange,
2587
+ loadInstantRange,
2588
+ loadRange,
2589
+ options,
2590
+ projection: activeDefinition.strategy.project({
2591
+ environment: viewEnvironment,
2592
+ expandedResourceIds,
2593
+ instantRange,
2594
+ loadRange,
2595
+ options,
2596
+ range,
2597
+ resources: resourceTree,
2598
+ snapshot: visibleEvents,
2599
+ today
2600
+ }),
2601
+ range,
2602
+ view: activeDefinition.name
2603
+ });
2604
+ });
2605
+ const diagnostics = diagnosticsInput(collectDiagnostics(state.view, activeDefinition !== void 0, eventSnapshot.issues, annotationSnapshot.issues, availability.issues, secondary.issues));
2606
+ committedInputs ??= { current: {
2607
+ activeView,
2608
+ allowAgentDelete: inputs.allowAgentDelete,
2609
+ availability,
2610
+ environment,
2611
+ eventSnapshot,
2612
+ onDiagnosticsChange: inputs.onDiagnosticsChange,
2613
+ onEventChange: inputs.onEventChange,
2614
+ onEventChangeResult: inputs.onEventChangeResult,
2615
+ onVisibleRangeChange: inputs.onVisibleRangeChange,
2616
+ policies: inputs.policies,
2617
+ resourceTree,
2618
+ viewOptions: viewOverrides
2619
+ } };
2620
+ const committed = committedInputs;
2621
+ const { binding, source } = connection;
2622
+ const actions = actionsCell([binding], () => {
2623
+ const created = createSemanticActions(binding, viewsByName, committed, transactions, readOnly);
2624
+ proposers.set(created.actions, created.proposeNow);
2625
+ return created.actions;
2626
+ });
2627
+ const isReadOnly = inputs.onEventChange === void 0;
2628
+ const interaction = interactionCell([
2629
+ actions,
2630
+ binding,
2631
+ isReadOnly,
2632
+ source
2633
+ ], () => Object.freeze({
2634
+ actions,
2635
+ announcements,
2636
+ changes: pendingChanges,
2637
+ draft,
2638
+ isReadOnly,
2639
+ keyboard,
2640
+ pointerDraft,
2641
+ rangeOf: (anchor) => {
2642
+ const view = committed.current.activeView;
2643
+ return view === null ? null : view.definition.strategy.getRange(anchor, view.environment, view.options);
2644
+ },
2645
+ read: binding.read,
2646
+ requests: binding.subscribeRequests,
2647
+ source
2648
+ }));
2649
+ const model = modelCell([
2650
+ actions,
2651
+ activeDefinition,
2652
+ activeView,
2653
+ annotations,
2654
+ availability,
2655
+ diagnostics,
2656
+ environment,
2657
+ eventSnapshot,
2658
+ interaction,
2659
+ isReadOnly,
2660
+ resourceTree,
2661
+ resources,
2662
+ source,
2663
+ state,
2664
+ today,
2665
+ viewEnvironment,
2666
+ visibleEvents,
2667
+ visibleRange
2668
+ ], () => Object.freeze({
2669
+ actions,
2670
+ activeDefinition,
2671
+ activeView,
2672
+ annotations,
2673
+ availability,
2674
+ diagnostics,
2675
+ environment,
2676
+ eventSnapshot,
2677
+ interaction,
2678
+ isReadOnly,
2679
+ resourceTree,
2680
+ resources,
2681
+ source,
2682
+ state,
2683
+ today,
2684
+ viewEnvironment,
2685
+ visibleEvents,
2686
+ visibleRange
2687
+ }));
2688
+ committedModel ??= model;
2689
+ return model;
2690
+ }
2691
+ return Object.freeze({
2692
+ announcements,
2693
+ commit(model, inputs) {
2694
+ inputs.connection.binding.commit({
2695
+ controlled: inputs.connection.controlled,
2696
+ handlers: inputs.handlers
2697
+ });
2698
+ const record = committedOf(inputs, model);
2699
+ if (committedInputs === void 0) committedInputs = { current: record };
2700
+ else committedInputs.current = record;
2701
+ committedModel = model;
2702
+ },
2703
+ committed: () => committedModel,
2704
+ connect,
2705
+ derive,
2706
+ keyboard,
2707
+ overlay,
2708
+ pendingChanges,
2709
+ pointerDraft,
2710
+ proposeNow(proposal, detail) {
2711
+ const propose = committedModel === void 0 ? void 0 : proposers.get(committedModel.actions);
2712
+ if (propose === void 0) throw new Error("calendar-runtime-before-first-derive");
2713
+ return propose(proposal, detail);
2714
+ },
2715
+ latest() {
2716
+ const model = committedModel;
2717
+ if (model === void 0) return void 0;
2718
+ const state = model.interaction.read();
2719
+ const definition = viewsByName.get(state.view);
2720
+ if (definition === void 0) return Object.freeze({
2721
+ range: null,
2722
+ state
2723
+ });
2724
+ const environment = {
2725
+ ...model.viewEnvironment,
2726
+ timeZone: state.timeZone
2727
+ };
2728
+ const options = resolveViewOptions(definition, committedInputs?.current.viewOptions?.[state.view]);
2729
+ return Object.freeze({
2730
+ range: definition.strategy.getRange(state.anchorDate, environment, options),
2731
+ state
2732
+ });
2733
+ },
2734
+ reconcile: (eventSnapshot) => transactions.reconcile(eventSnapshot),
2735
+ reportDiagnostics(diagnostics) {
2736
+ committedInputs?.current.onDiagnosticsChange?.(diagnostics);
2737
+ },
2738
+ reportVisibleRange(visibleRange) {
2739
+ if (visibleRange === null || visibleRange === reportedRange) return;
2740
+ reportedRange = visibleRange;
2741
+ committedInputs?.current.onVisibleRangeChange?.(visibleRange);
2742
+ },
2743
+ transactions,
2744
+ views,
2745
+ viewsByName
2746
+ });
2747
+ }
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 };