@moltenship/calendar-primitives 0.0.0-stage → 2.0.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs ADDED
@@ -0,0 +1,1703 @@
1
+ import { createSystemClock, instantInterval, plainDateInterval, plainDateTimeInterval } from "@moltenship/calendar-temporal";
2
+ import { applyEventOverlay, createAnnotationSnapshot, createAvailabilitySnapshot, createEventSnapshotCache, createEventTransactions, createResourceTree, formatPlacementRange, readOnlyPolicy, resolveSecondaryTimeZones, resolveViewInstantRange, resolveViewLoadRange } from "@moltenship/calendar-core";
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/announcer-channel.ts
246
+ function buildMessage(messages, update, context) {
247
+ const build = messages[update.phase];
248
+ return build(update, context);
249
+ }
250
+ /** `getEnvironment` and `getResources` read the root's last commit when an update arrives. */
251
+ function createAnnouncerChannel(getEnvironment, getResources) {
252
+ const mounted = [];
253
+ function formatRange(placement) {
254
+ const { locale, timeZone } = getEnvironment();
255
+ return (mounted.at(-1)?.getMessages().formatRange ?? formatPlacementRange)(placement, {
256
+ locale,
257
+ timeZone
258
+ });
259
+ }
260
+ function resourceTitle(resourceId) {
261
+ return getResources().byId.get(resourceId)?.resource.title;
262
+ }
263
+ function say(build) {
264
+ const current = mounted.at(-1);
265
+ if (current === void 0) return;
266
+ const { locale, timeZone } = getEnvironment();
267
+ const text = build({
268
+ formatRange,
269
+ locale,
270
+ resourceTitle,
271
+ timeZone
272
+ }, current.getMessages());
273
+ if (text !== null && text !== "") current.speak(text);
274
+ }
275
+ return Object.freeze({
276
+ announcer: Object.freeze({
277
+ announce: (update) => say((context, messages) => buildMessage(messages, update, context)),
278
+ formatRange
279
+ }),
280
+ mount(getMessages, speak) {
281
+ const entry = {
282
+ getMessages,
283
+ speak
284
+ };
285
+ mounted.push(entry);
286
+ return () => {
287
+ const index = mounted.lastIndexOf(entry);
288
+ if (index !== -1) mounted.splice(index, 1);
289
+ };
290
+ },
291
+ say
292
+ });
293
+ }
294
+ // src/calendar-types.ts
295
+ /** The ids a root's chrome parts point at each other with. */
296
+ function createCalendarPartIds(instanceId) {
297
+ return Object.freeze({
298
+ frame: `${instanceId}-frame`,
299
+ title: `${instanceId}-title`,
300
+ viewport: `${instanceId}-viewport`
301
+ });
302
+ }
303
+ // src/clock.ts
304
+ /** The clock a root reads when it has neither `now` nor `clock`. */
305
+ const systemClock = createSystemClock();
306
+ /** How often a root samples its clock for `today`. */
307
+ const TODAY_SAMPLE_INTERVAL_MS = 6e4;
308
+ /** Samples `clock` every `intervalMs` while subscribed. */
309
+ function createClockTicker(clock, intervalMs) {
310
+ let current;
311
+ return Object.freeze({
312
+ getSnapshot: () => current ??= clock.instant(),
313
+ subscribe: (onChange) => {
314
+ const sample = () => {
315
+ const next = clock.instant();
316
+ if (current?.equals(next) === true) return;
317
+ current = next;
318
+ onChange();
319
+ };
320
+ sample();
321
+ const timer = setInterval(sample, intervalMs);
322
+ return () => clearInterval(timer);
323
+ }
324
+ });
325
+ }
326
+ /** The clock a source samples: its own, or the system's. */
327
+ function clockOf(source) {
328
+ return source?.clock ?? systemClock;
329
+ }
330
+ // src/listeners.ts
331
+ function createListeners() {
332
+ const entries = /* @__PURE__ */ new Set();
333
+ return Object.freeze({
334
+ notify() {
335
+ for (const entry of entries) entry.listener();
336
+ },
337
+ subscribe(listener) {
338
+ const entry = { listener };
339
+ entries.add(entry);
340
+ return () => {
341
+ entries.delete(entry);
342
+ };
343
+ }
344
+ });
345
+ }
346
+ // src/draft-store.ts
347
+ function createDraftStore() {
348
+ let draft = null;
349
+ const listeners = createListeners();
350
+ return Object.freeze({
351
+ getSnapshot: () => draft,
352
+ set(next) {
353
+ if (next === draft) return;
354
+ draft = next;
355
+ listeners.notify();
356
+ },
357
+ subscribe: listeners.subscribe
358
+ });
359
+ }
360
+ // src/equality.ts
361
+ function sameElements(left, right) {
362
+ return left === right || left.length === right.length && left.every((value, index) => Object.is(value, right[index]));
363
+ }
364
+ /** Compares own enumerable properties with `Object.is`; non-objects compare with `Object.is`. */
365
+ function shallowEqual(left, right) {
366
+ if (Object.is(left, right)) return true;
367
+ if (typeof left !== "object" || typeof right !== "object" || left === null || right === null) return false;
368
+ const leftKeys = Object.keys(left);
369
+ return leftKeys.length === Object.keys(right).length && leftKeys.every((key) => Object.hasOwn(right, key) && Object.is(left[key], right[key]));
370
+ }
371
+ function samePlainDate(left, right) {
372
+ return left === right || left != null && right != null && left.equals(right);
373
+ }
374
+ function sameInstant(left, right) {
375
+ return left === right || left !== void 0 && right !== void 0 && left.equals(right);
376
+ }
377
+ function sameRange(left, right) {
378
+ return left === right || left !== void 0 && right !== void 0 && left.start.equals(right.start) && left.end.equals(right.end);
379
+ }
380
+ function sameWeekRules(left, right) {
381
+ return left === right || left.firstDay === right.firstDay && left.minimalDays === right.minimalDays && sameElements(left.weekend, right.weekend);
382
+ }
383
+ const isRecord = (value) => typeof value === "object" && value !== null;
384
+ /**
385
+ * Lists by element: identical values, or records `same` matches. Anything else, such as an
386
+ * invalid entry the snapshot reports, matches only itself.
387
+ */
388
+ function sameList(left, right, same) {
389
+ if (left === right) return true;
390
+ if (!Array.isArray(left) || !Array.isArray(right) || left.length !== right.length) return false;
391
+ return Array.from(left).every((value, index) => {
392
+ const other = right[index];
393
+ return Object.is(value, other) || isRecord(value) && isRecord(other) && same(value, other);
394
+ });
395
+ }
396
+ /** Temporal dates and times by value; anything else, such as invalid input, by identity. */
397
+ function sameTemporal(left, right) {
398
+ if (Object.is(left, right)) return true;
399
+ if (left instanceof Temporal.PlainTime) return right instanceof Temporal.PlainTime && left.equals(right);
400
+ return left instanceof Temporal.PlainDate && right instanceof Temporal.PlainDate && left.equals(right);
401
+ }
402
+ function sameHours(left, right) {
403
+ return sameTemporal(left.start, right.start) && sameTemporal(left.end, right.end);
404
+ }
405
+ /**
406
+ * Compares working hours by value, so an inline `availability` keeps its shading cached. Invalid
407
+ * entries never throw here; the snapshot reports them.
408
+ */
409
+ function sameAvailability(left, right) {
410
+ 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));
411
+ }
412
+ const sameZone = (left, right) => Object.is(left, right) || isRecord(left) && isRecord(right) && left.timeZone === right.timeZone && left.label === right.label;
413
+ /**
414
+ * Compares secondary time zones by value, so an inline list keeps the environment as it is. A
415
+ * single zone passed where a list belongs, which the root reports, compares by value too.
416
+ */
417
+ function sameSecondaryTimeZones(left, right) {
418
+ return Array.isArray(left) && Array.isArray(right) ? sameList(left, right, sameZone) : sameZone(left, right);
419
+ }
420
+ // src/keyboard-store.ts
421
+ const noPreview = /* @__PURE__ */ new Map();
422
+ function createKeyboardSessionStore() {
423
+ let grab = null;
424
+ let preview = noPreview;
425
+ const listeners = createListeners();
426
+ const { subscribe } = listeners;
427
+ return Object.freeze({
428
+ get: () => grab,
429
+ getPreview: () => preview,
430
+ grabs: Object.freeze({
431
+ getSnapshot: () => grab,
432
+ subscribe
433
+ }),
434
+ set(next) {
435
+ if (next === grab) return;
436
+ grab = next;
437
+ const session = next?.session;
438
+ preview = session?.eventId == null ? noPreview : /* @__PURE__ */ new Map([[session.eventId, session.proposed]]);
439
+ listeners.notify();
440
+ },
441
+ subscribe
442
+ });
443
+ }
444
+ // src/memo.ts
445
+ /**
446
+ * Memo cells: what `useMemo` and a stable-value hook do in a component, as plain closures a
447
+ * runtime owns, so a framework can derive during render (or in a signal's memo) and get the same
448
+ * objects back while their inputs hold.
449
+ */
450
+ /** A value that keeps its first identity while `isEqual` says each next one is the same. */
451
+ function createStableCell(isEqual) {
452
+ let held;
453
+ return (next) => {
454
+ if (held !== void 0 && (held.value === next || isEqual(held.value, next))) return held.value;
455
+ held = { value: next };
456
+ return next;
457
+ };
458
+ }
459
+ /** A value computed again only when one of its dependencies changes identity. */
460
+ function createMemoCell() {
461
+ let held;
462
+ return (deps, compute) => {
463
+ if (held !== void 0 && held.deps.length === deps.length && held.deps.every((dep, index) => Object.is(dep, deps[index]))) return held.value;
464
+ const value = compute();
465
+ held = {
466
+ deps,
467
+ value
468
+ };
469
+ return value;
470
+ };
471
+ }
472
+ // src/store.ts
473
+ const handlerNames = Object.freeze({
474
+ anchorDate: "onAnchorDateChange",
475
+ expandedResourceIds: "onExpandedResourceIdsChange",
476
+ focus: "onFocusChange",
477
+ selection: "onSelectionChange",
478
+ timeZone: "onTimeZoneChange",
479
+ view: "onViewChange"
480
+ });
481
+ /** The six slices, in a fixed order. */
482
+ const calendarStateSlices = Object.keys(handlerNames);
483
+ const storeInternals = /* @__PURE__ */ new WeakMap();
484
+ function uniqueResourceIds(resourceIds) {
485
+ return Object.freeze([...new Set(resourceIds)]);
486
+ }
487
+ /** Dates by value and resource lists by element; everything else by identity. */
488
+ function sameSliceValue(slice, previous, next) {
489
+ if (slice === "anchorDate") return samePlainDate(previous, next);
490
+ if (slice === "expandedResourceIds") return sameElements(previous, next);
491
+ return Object.is(previous, next);
492
+ }
493
+ /** Overlays every defined controlled slice on the uncontrolled state. */
494
+ function mergeControlledState(state, controlled) {
495
+ if (controlled === void 0) return state;
496
+ const overlay = calendarStateSlices.filter((slice) => controlled[slice] !== void 0);
497
+ if (overlay.length === 0) return state;
498
+ const merged = { ...state };
499
+ for (const slice of overlay) Object.assign(merged, { [slice]: controlled[slice] });
500
+ return Object.freeze(merged);
501
+ }
502
+ function getCalendarStoreInternals(store) {
503
+ const internals = storeInternals.get(store);
504
+ if (internals === void 0) throw new TypeError("calendar-store-not-created-by-createCalendarStore");
505
+ return internals;
506
+ }
507
+ function createCalendarStore(options) {
508
+ let state = Object.freeze({
509
+ anchorDate: options.defaultAnchorDate,
510
+ expandedResourceIds: uniqueResourceIds(options.defaultExpandedResourceIds ?? []),
511
+ focus: options.defaultFocus ?? null,
512
+ selection: options.defaultSelection ?? null,
513
+ timeZone: options.defaultTimeZone,
514
+ view: options.defaultView
515
+ });
516
+ const listeners = createListeners();
517
+ const mountedRoots = [];
518
+ const notify = () => {
519
+ listeners.notify();
520
+ };
521
+ function createActions(run) {
522
+ return Object.freeze({
523
+ setAnchorDate: (next, options) => run("anchorDate", next, options),
524
+ setExpandedResourceIds: (next, options) => run("expandedResourceIds", next, options),
525
+ setFocus: (next, options) => run("focus", next, options),
526
+ setSelection: (next, options) => run("selection", next, options),
527
+ setTimeZone: (next, options) => run("timeZone", next, options),
528
+ setView: (next, options) => run("view", next, options)
529
+ });
530
+ }
531
+ function bind(initial) {
532
+ let current = initial;
533
+ let pending;
534
+ /**
535
+ * Values the owners of controlled slices were told about and have not committed: an owner
536
+ * that defers or declines a change still holds it.
537
+ */
538
+ let unsettled = {};
539
+ const requestListeners = /* @__PURE__ */ new Set();
540
+ const handlerContext = Object.freeze({ options: () => current.handlers });
541
+ const read = () => mergeControlledState(mergeControlledState(state, current.controlled), pending);
542
+ const run = (slice, requested, options) => {
543
+ const next = slice === "expandedResourceIds" ? uniqueResourceIds(requested) : requested;
544
+ for (const entry of requestListeners) entry.listener(slice, next);
545
+ const previous = read()[slice];
546
+ const controlled = current.controlled[slice] !== void 0;
547
+ if (sameSliceValue(slice, previous, next)) {
548
+ const told = unsettled[slice];
549
+ if (!controlled || told === void 0 || sameSliceValue(slice, told, next)) return;
550
+ }
551
+ const before = state;
552
+ let written;
553
+ if (controlled) {
554
+ if (pending === void 0) queueMicrotask(() => pending = void 0);
555
+ pending = {
556
+ ...pending,
557
+ [slice]: next
558
+ };
559
+ const settled = sameSliceValue(slice, current.controlled[slice], next);
560
+ unsettled = {
561
+ ...unsettled,
562
+ [slice]: settled ? void 0 : next
563
+ };
564
+ } else {
565
+ written = Object.freeze({
566
+ ...state,
567
+ [slice]: next
568
+ });
569
+ state = written;
570
+ notify();
571
+ }
572
+ if (dispatch(handlerContext, handlerNames[slice], next, {
573
+ controlled,
574
+ ...options?.event === void 0 ? {} : { event: options.event },
575
+ previous,
576
+ reason: options?.reason ?? "imperative",
577
+ slice,
578
+ ...options?.source === void 0 ? {} : { source: options.source }
579
+ }) && written !== void 0 && Object.is(state[slice], written[slice])) {
580
+ state = Object.freeze({
581
+ ...state,
582
+ [slice]: before[slice]
583
+ });
584
+ notify();
585
+ }
586
+ };
587
+ const binding = Object.freeze({
588
+ actions: createActions(run),
589
+ attach: () => {
590
+ mountedRoots.push(binding);
591
+ return () => {
592
+ const index = mountedRoots.lastIndexOf(binding);
593
+ if (index !== -1) mountedRoots.splice(index, 1);
594
+ };
595
+ },
596
+ commit: (next) => {
597
+ const previous = current;
598
+ current = next;
599
+ for (const slice of calendarStateSlices) {
600
+ const committed = next.controlled[slice];
601
+ if (unsettled[slice] !== void 0 && (committed === void 0 || !sameSliceValue(slice, previous.controlled[slice], committed))) unsettled = {
602
+ ...unsettled,
603
+ [slice]: void 0
604
+ };
605
+ }
606
+ if (pending === void 0) return;
607
+ const retained = { ...pending };
608
+ for (const slice of calendarStateSlices) {
609
+ if (retained[slice] === void 0) continue;
610
+ const committed = next.controlled[slice];
611
+ if (committed === void 0 || !sameSliceValue(slice, previous.controlled[slice], committed)) delete retained[slice];
612
+ }
613
+ pending = calendarStateSlices.some((slice) => retained[slice] !== void 0) ? retained : void 0;
614
+ },
615
+ read,
616
+ subscribeRequests: (listener) => {
617
+ const entry = { listener };
618
+ requestListeners.add(entry);
619
+ return () => {
620
+ requestListeners.delete(entry);
621
+ };
622
+ }
623
+ });
624
+ return binding;
625
+ }
626
+ const unbound = bind({
627
+ controlled: {},
628
+ handlers: {}
629
+ });
630
+ const owner = () => mountedRoots.at(-1) ?? unbound;
631
+ const store = {
632
+ actions: Object.freeze({
633
+ setAnchorDate: (next, options) => owner().actions.setAnchorDate(next, options),
634
+ setExpandedResourceIds: (next, options) => owner().actions.setExpandedResourceIds(next, options),
635
+ setFocus: (next, options) => owner().actions.setFocus(next, options),
636
+ setSelection: (next, options) => owner().actions.setSelection(next, options),
637
+ setTimeZone: (next, options) => owner().actions.setTimeZone(next, options),
638
+ setView: (next, options) => owner().actions.setView(next, options)
639
+ }),
640
+ getSnapshot: () => state,
641
+ subscribe: listeners.subscribe
642
+ };
643
+ storeInternals.set(store, { bind });
644
+ return store;
645
+ }
646
+ // src/primitive.ts
647
+ /**
648
+ * What each agent action takes, as `describeCalendar` lists it and the action's errors repeat:
649
+ * ui-sdk's bridge has no way to describe an action's arguments.
650
+ */
651
+ const signatures = Object.freeze({
652
+ createEvent: "{ start: ISO date or date-time, end: ISO date or date-time, title?: string, resourceIds?: ID[], fields?: object }",
653
+ deleteEvent: "{ eventId: ID }",
654
+ describeCalendar: "nothing",
655
+ getChange: "{ changeId: string }",
656
+ goToDate: "{ date: ISO date }",
657
+ listEvents: "nothing, or { start?: ISO date, end?: ISO date }",
658
+ moveEvent: "{ eventId: ID, start: ISO date or date-time, end?: same, resourceIds?: ID[] }",
659
+ navigateNext: "nothing",
660
+ navigatePrevious: "nothing",
661
+ navigateToday: "nothing",
662
+ resizeEvent: "{ eventId: ID, start?: ISO date or date-time, end?: same }, one of start and end",
663
+ selectEvent: "{ eventId: ID or null }",
664
+ setTimeZone: "{ timeZone: IANA name }",
665
+ setView: "{ view: one of views }",
666
+ updateEvent: "{ eventId: ID, title?: string, start?: ISO date or date-time, end?: same, resourceIds?: ID[], fields?: object }"
667
+ });
668
+ /** The methods an agent may call, with JSON arguments. */
669
+ const calendarAgentActions = Object.freeze([
670
+ "describeCalendar",
671
+ "listEvents",
672
+ "getChange",
673
+ "navigateNext",
674
+ "navigatePrevious",
675
+ "navigateToday",
676
+ "goToDate",
677
+ "setView",
678
+ "setTimeZone",
679
+ "selectEvent",
680
+ "createEvent",
681
+ "updateEvent",
682
+ "moveEvent",
683
+ "resizeEvent",
684
+ "deleteEvent"
685
+ ]);
686
+ 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.";
687
+ /** Every change an agent's action makes is the agent's, whatever else runs around it. */
688
+ const asAgent = Object.freeze({ source: "agent" });
689
+ const agentInput$1 = Object.freeze({ input: "agent" });
690
+ /** How many of an agent's changes `getChange` remembers, per root. */
691
+ const changeLogSize = 50;
692
+ /**
693
+ * The agent's changes by ID, per root: a framework may make an instance it then throws away, as
694
+ * React's Strict Mode does, so the log outlives any one.
695
+ */
696
+ const changeLogs = /* @__PURE__ */ new WeakMap();
697
+ function changeLogOf(runtime) {
698
+ let log = changeLogs.get(runtime);
699
+ if (log === void 0) {
700
+ log = /* @__PURE__ */ new Map();
701
+ changeLogs.set(runtime, log);
702
+ }
703
+ return log;
704
+ }
705
+ function remember(runtime, change) {
706
+ const log = changeLogOf(runtime);
707
+ log.delete(change.changeId);
708
+ log.set(change.changeId, change);
709
+ if (log.size > changeLogSize) log.delete(log.keys().next().value);
710
+ return change;
711
+ }
712
+ function slicesOf(options) {
713
+ const slices = {};
714
+ for (const slice of calendarStateSlices) slices[slice] = options[slice];
715
+ return Object.freeze(slices);
716
+ }
717
+ function modelOf(runtime) {
718
+ const model = runtime.committed();
719
+ if (model === void 0) throw new Error("calendar-primitive-before-first-derive");
720
+ return model;
721
+ }
722
+ function agentChange(change, status, timeZone, reason) {
723
+ return Object.freeze({
724
+ cause: change.cause,
725
+ changeId: change.id,
726
+ eventId: change.eventId,
727
+ proposed: change.proposed === null ? null : describeAgentPlacement(change.proposed, timeZone),
728
+ ...reason === void 0 ? {} : { reason },
729
+ status
730
+ });
731
+ }
732
+ /** Why a change was turned down, with the handler's own message when it threw one. */
733
+ function rejection(result) {
734
+ const message = result.error instanceof Error ? result.error.message : void 0;
735
+ return message === void 0 || message === "" ? `calendar-event-change-rejected: ${result.reason}` : `calendar-event-change-rejected: ${result.reason} (${message})`;
736
+ }
737
+ /** An action that takes nothing takes an empty object too, as some agents send one. */
738
+ function noArguments(action, args) {
739
+ const [first, ...extra] = args;
740
+ if (first === void 0 && extra.every((arg) => arg === void 0)) return;
741
+ readAgentInput(action, "nothing", first, {}, extra);
742
+ }
743
+ /**
744
+ * Defines a calendar's ui-sdk primitive: the six state slices as always-controlled keys, the
745
+ * semantic commands as its api, its chrome as slots, and what an AI agent may see and do. The
746
+ * slices live in the calendar store and the application's props; the instance is a projection of
747
+ * them for parts and agents, and every change goes through the root's store, which tells the
748
+ * application's handlers.
749
+ */
750
+ function createCalendarPrimitive(config) {
751
+ const viewNames = Object.freeze(config.views.map((view) => view.name));
752
+ const registered = new Set(viewNames);
753
+ return definePrimitive({
754
+ name: "calendar",
755
+ options: {
756
+ allowAgentDelete: "boolean",
757
+ anchorDate: "value",
758
+ expandedResourceIds: "value",
759
+ focus: "value",
760
+ formatAgentEventLabel: "value",
761
+ runtime: "value",
762
+ selection: "value",
763
+ timeZone: "string",
764
+ view: "string"
765
+ },
766
+ controlled: [
767
+ "anchorDate",
768
+ "view",
769
+ "timeZone",
770
+ "selection",
771
+ "focus",
772
+ "expandedResourceIds"
773
+ ],
774
+ state: (options) => slicesOf(options),
775
+ sync: (options) => slicesOf(options),
776
+ api: (context) => {
777
+ const runtime = () => context.options().runtime;
778
+ const actions = () => modelOf(runtime()).actions;
779
+ /**
780
+ * The bridge offers an action only while the api has it, so the event changes are getters
781
+ * that hide on a read-only root, and delete unless the root allows it. ui-sdk checks in
782
+ * development that every listed action exists as the instance is made, so they all show
783
+ * until then.
784
+ */
785
+ let made = false;
786
+ queueMicrotask(() => made = true);
787
+ const canChange = () => !modelOf(runtime()).isReadOnly;
788
+ const canDelete = () => canChange() && context.options().allowAgentDelete === true;
789
+ const offered = (available, method) => !made || available() ? method : void 0;
790
+ /** The application's events with the changes still pending, as the next render shows them. */
791
+ function currentEvents() {
792
+ const model = modelOf(runtime());
793
+ return applyEventOverlay(model.eventSnapshot, runtime().transactions.getPending());
794
+ }
795
+ /** The state and range the latest commands asked for, before a framework renders them. */
796
+ function latest() {
797
+ const model = modelOf(runtime());
798
+ const current = runtime().latest();
799
+ const state = current?.state ?? model.state;
800
+ return {
801
+ model,
802
+ range: current === void 0 ? model.activeView?.range ?? null : current.range,
803
+ state
804
+ };
805
+ }
806
+ function describeEvents(range) {
807
+ if (range === null) return [];
808
+ const { model, state } = latest();
809
+ const environment = {
810
+ ...model.viewEnvironment,
811
+ timeZone: state.timeZone
812
+ };
813
+ return eventsInRange(currentEvents(), range, environment).map((event) => describeAgentEvent(event, environment));
814
+ }
815
+ /**
816
+ * Proposes an agent's change once: a refusal the policies or the handler give at once fails
817
+ * the step with its reason, and a change still saving returns where it is. Its outcome
818
+ * reaches `onEventChangeResult` once, and the agent's log, so a late failure is never an
819
+ * unhandled rejection.
820
+ */
821
+ function propose(proposal, fields) {
822
+ const root = runtime();
823
+ const timeZone = latest().state.timeZone;
824
+ const detail = fields === void 0 ? agentInput$1 : Object.freeze({
825
+ fields,
826
+ input: "agent"
827
+ });
828
+ const outcome = root.proposeNow(proposal, detail);
829
+ if (outcome.status === "rejected") {
830
+ if (outcome.change !== void 0) remember(root, agentChange(outcome.change, "rejected", timeZone, outcome.reason));
831
+ throw new Error(rejection(outcome), { cause: outcome.error });
832
+ }
833
+ if (outcome.status === "committed") return remember(root, agentChange(outcome.change, "saved", timeZone));
834
+ outcome.result.then((result) => {
835
+ const change = result.change ?? outcome.change;
836
+ remember(root, result.status === "committed" ? agentChange(change, "saved", timeZone) : agentChange(change, "rejected", timeZone, result.reason));
837
+ });
838
+ return remember(root, agentChange(outcome.change, outcome.phase, timeZone));
839
+ }
840
+ function checkedView(view) {
841
+ if (typeof view === "string" && registered.has(view)) return view;
842
+ throw new RangeError(`calendar-unknown-view: ${JSON.stringify(view)} is not a registered view. Views: ${viewNames.map((name) => JSON.stringify(name)).join(", ")}`);
843
+ }
844
+ function eventOf(input) {
845
+ return findEvent(currentEvents(), readEventId(input.eventId));
846
+ }
847
+ function environment() {
848
+ const { model, state } = latest();
849
+ return {
850
+ ...model.viewEnvironment,
851
+ timeZone: state.timeZone
852
+ };
853
+ }
854
+ const createEvent = (input, ...extra) => {
855
+ const args = readAgentInput("createEvent", signatures.createEvent, input, {
856
+ end: true,
857
+ fields: false,
858
+ resourceIds: false,
859
+ start: true,
860
+ title: false
861
+ }, extra);
862
+ return propose({
863
+ cause: "create",
864
+ proposed: createdPlacement(args.start, args.end, args.resourceIds, environment(), modelOf(runtime()).resourceTree.byId)
865
+ }, readFields(args));
866
+ };
867
+ const updateEvent = (input, ...extra) => {
868
+ const args = readAgentInput("updateEvent", signatures.updateEvent, input, {
869
+ end: false,
870
+ eventId: true,
871
+ fields: false,
872
+ resourceIds: false,
873
+ start: false,
874
+ title: false
875
+ }, extra);
876
+ const { end, fields, resourceIds, start, title } = args;
877
+ if ([
878
+ end,
879
+ fields,
880
+ resourceIds,
881
+ start,
882
+ title
883
+ ].every((value) => value === void 0)) throw new TypeError(`calendar-agent-invalid-arguments: updateEvent changes something: ${signatures.updateEvent}`);
884
+ const event = eventOf(args);
885
+ const placement = movedPlacement(event, args.start ?? event.start, args.start === void 0 && args.end === void 0 ? event.end : args.end, environment());
886
+ return propose({
887
+ cause: "update",
888
+ eventId: event.id,
889
+ proposed: args.resourceIds === void 0 ? placement : {
890
+ ...placement,
891
+ resourceIds: readResourceIds(args.resourceIds, modelOf(runtime()).resourceTree.byId)
892
+ }
893
+ }, readFields(args));
894
+ };
895
+ const moveEvent = (input, ...extra) => {
896
+ const args = readAgentInput("moveEvent", signatures.moveEvent, input, {
897
+ end: false,
898
+ eventId: true,
899
+ resourceIds: false,
900
+ start: true
901
+ }, extra);
902
+ const event = eventOf(args);
903
+ const placement = movedPlacement(event, args.start, args.end, environment());
904
+ return propose({
905
+ cause: "move",
906
+ eventId: event.id,
907
+ proposed: args.resourceIds === void 0 ? placement : {
908
+ ...placement,
909
+ resourceIds: readResourceIds(args.resourceIds, modelOf(runtime()).resourceTree.byId)
910
+ }
911
+ }, void 0);
912
+ };
913
+ const resizeEvent = (input, ...extra) => {
914
+ const args = readAgentInput("resizeEvent", signatures.resizeEvent, input, {
915
+ end: false,
916
+ eventId: true,
917
+ start: false
918
+ }, extra);
919
+ 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}`);
920
+ const event = eventOf(args);
921
+ const fromStart = args.start !== void 0;
922
+ return propose({
923
+ cause: fromStart ? "resize-start" : "resize-end",
924
+ eventId: event.id,
925
+ proposed: fromStart ? movedPlacement(event, args.start, event.end, environment()) : movedPlacement(event, event.start, args.end, environment())
926
+ }, void 0);
927
+ };
928
+ const deleteEvent = (input, ...extra) => {
929
+ const proposal = {
930
+ cause: "delete",
931
+ eventId: eventOf(readAgentInput("deleteEvent", signatures.deleteEvent, input, { eventId: true }, extra)).id
932
+ };
933
+ 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"}`);
934
+ return propose(proposal, void 0);
935
+ };
936
+ const api = {
937
+ get createEvent() {
938
+ return offered(canChange, createEvent);
939
+ },
940
+ get deleteEvent() {
941
+ return offered(canDelete, deleteEvent);
942
+ },
943
+ describeCalendar(...args) {
944
+ noArguments("describeCalendar", args);
945
+ const { model, range, state } = latest();
946
+ const { environment: root } = model;
947
+ const now = (root.now ?? clockOf(root).instant()).toZonedDateTimeISO(state.timeZone);
948
+ const available = Object.fromEntries(calendarAgentActions.filter((action) => typeof api[action] === "function").map((action) => [action, signatures[action]]));
949
+ const selection = state.selection;
950
+ return Object.freeze({
951
+ actions: Object.freeze(available),
952
+ anchorDate: state.anchorDate.toString(),
953
+ canDelete: canDelete(),
954
+ conventions,
955
+ locale: String(root.locale),
956
+ now: now.toString({ timeZoneName: "never" }),
957
+ pendingChanges: Object.freeze([...runtime().pendingChanges.getSnapshot().values()].filter(({ phase }) => phase !== "awaiting-events").map(({ change, phase }) => agentChange(change, phase === "validating" ? "validating" : "saving", state.timeZone))),
958
+ readOnly: model.isReadOnly,
959
+ resources: Object.freeze([...model.resourceTree.byId.values()].map((node) => Object.freeze({
960
+ id: node.id,
961
+ parentId: node.parentId,
962
+ title: node.resource.title
963
+ }))),
964
+ selectedEventId: selection?.kind === "event" ? selection.eventId : null,
965
+ timeZone: state.timeZone,
966
+ today: now.toPlainDate().toString(),
967
+ view: state.view,
968
+ views: viewNames,
969
+ visibleRange: range === null ? null : Object.freeze({
970
+ end: range.end.toString(),
971
+ start: range.start.toString()
972
+ })
973
+ });
974
+ },
975
+ getChange(input, ...extra) {
976
+ const args = readAgentInput("getChange", signatures.getChange, input, { changeId: true }, extra);
977
+ const root = runtime();
978
+ const known = changeLogOf(root).get(String(args.changeId));
979
+ if (known !== void 0) return known;
980
+ const pending = root.pendingChanges.getSnapshot().get(String(args.changeId));
981
+ if (pending !== void 0) return agentChange(pending.change, pending.phase === "validating" ? "validating" : pending.phase === "saving" ? "saving" : "saved", latest().state.timeZone);
982
+ const ids = [...changeLogOf(root).keys()].slice(-10).map((id) => JSON.stringify(id));
983
+ throw new RangeError(`calendar-agent-unknown-change: no change has the ID ${JSON.stringify(args.changeId)}. Recent changes: ${ids.length === 0 ? "none" : ids.join(", ")}`);
984
+ },
985
+ goToDate(input, ...extra) {
986
+ const args = readAgentInput("goToDate", signatures.goToDate, input, { date: true }, extra);
987
+ actions().setAnchorDate(parsePlainDate(args.date, "date"), asAgent);
988
+ },
989
+ listEvents(input, ...extra) {
990
+ const args = readAgentInput("listEvents", signatures.listEvents, input ?? {}, {
991
+ end: false,
992
+ start: false
993
+ }, extra);
994
+ const visible = latest().range;
995
+ if (args.start === void 0 && args.end === void 0) return Object.freeze(describeEvents(visible));
996
+ const start = args.start === void 0 ? visible?.start : parsePlainDate(args.start, "start");
997
+ const end = args.end === void 0 ? visible?.end : parsePlainDate(args.end, "end");
998
+ 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)}`);
999
+ return Object.freeze(describeEvents(plainDateInterval(start, end)));
1000
+ },
1001
+ get moveEvent() {
1002
+ return offered(canChange, moveEvent);
1003
+ },
1004
+ navigateNext(...args) {
1005
+ noArguments("navigateNext", args);
1006
+ actions().navigateNext(asAgent);
1007
+ },
1008
+ navigatePrevious(...args) {
1009
+ noArguments("navigatePrevious", args);
1010
+ actions().navigatePrevious(asAgent);
1011
+ },
1012
+ navigateToday(...args) {
1013
+ noArguments("navigateToday", args);
1014
+ actions().navigateToday(asAgent);
1015
+ },
1016
+ get resizeEvent() {
1017
+ return offered(canChange, resizeEvent);
1018
+ },
1019
+ selectEvent(input, ...extra) {
1020
+ const args = readAgentInput("selectEvent", signatures.selectEvent, input, { eventId: true }, extra, ["eventId"]);
1021
+ const selection = args.eventId === null ? null : {
1022
+ eventId: eventOf(args).id,
1023
+ kind: "event"
1024
+ };
1025
+ actions().setSelection(selection, asAgent);
1026
+ },
1027
+ selectView(view, options) {
1028
+ if (!registered.has(view)) return false;
1029
+ actions().setView(view, options);
1030
+ return true;
1031
+ },
1032
+ setTimeZone(input, ...extra) {
1033
+ const args = readAgentInput("setTimeZone", signatures.setTimeZone, input, { timeZone: true }, extra);
1034
+ actions().setTimeZone(parseTimeZone(args.timeZone), asAgent);
1035
+ },
1036
+ setView(input, ...extra) {
1037
+ const args = readAgentInput("setView", signatures.setView, input, { view: true }, extra);
1038
+ actions().setView(checkedView(args.view), asAgent);
1039
+ },
1040
+ showNext: (options) => actions().navigateNext(options),
1041
+ showPrevious: (options) => actions().navigatePrevious(options),
1042
+ showToday: (options) => actions().navigateToday(options),
1043
+ get updateEvent() {
1044
+ return offered(canChange, updateEvent);
1045
+ },
1046
+ viewNames: () => viewNames,
1047
+ visibleEvents() {
1048
+ if (runtime().committed() === void 0) return [];
1049
+ const { model } = latest();
1050
+ const timeZone = latest().state.timeZone;
1051
+ const format = context.options().formatAgentEventLabel;
1052
+ return describeEvents(latest().range ?? model.activeView?.range ?? null).map((event) => Object.freeze({
1053
+ label: format === void 0 ? agentEventLabel(event, timeZone) : format(event),
1054
+ value: String(event.id)
1055
+ }));
1056
+ }
1057
+ };
1058
+ return Object.freeze(api);
1059
+ },
1060
+ slots: (slot) => ({
1061
+ root: slot({}),
1062
+ toolbar: slot({}),
1063
+ title: slot({}),
1064
+ viewport: slot({}),
1065
+ "previous-trigger": slot({ press: ({ api }, event) => api.showPrevious({
1066
+ event,
1067
+ reason: "previous-press"
1068
+ }) }),
1069
+ "next-trigger": slot({ press: ({ api }, event) => api.showNext({
1070
+ event,
1071
+ reason: "next-press"
1072
+ }) }),
1073
+ "today-trigger": slot({ press: ({ api }, event) => api.showToday({
1074
+ event,
1075
+ reason: "today-press"
1076
+ }) }),
1077
+ "view-switcher": slot({})
1078
+ }),
1079
+ agent: {
1080
+ actions: [...calendarAgentActions],
1081
+ items: (api) => api.visibleEvents()
1082
+ }
1083
+ });
1084
+ }
1085
+ // src/report-error.ts
1086
+ /** Reports an application callback's error without failing what it was told about. */
1087
+ function reportCallbackError(error) {
1088
+ if (typeof reportError === "function") reportError(error);
1089
+ else console.error(error);
1090
+ }
1091
+ // src/views.ts
1092
+ /** Applies a root's partial overrides to a view's `defaultOptions`. */
1093
+ function resolveViewOptions(view, overrides) {
1094
+ return overrides === void 0 ? view.defaultOptions : {
1095
+ ...view.defaultOptions,
1096
+ ...overrides
1097
+ };
1098
+ }
1099
+ // src/runtime.ts
1100
+ const noResources = Object.freeze([]);
1101
+ const noAnnotations = Object.freeze([]);
1102
+ const noSecondaryTimeZones = Object.freeze([]);
1103
+ /** A root without `onEventChange` is read-only, so its checks reject everything. */
1104
+ const readOnlyRoot = () => ({
1105
+ reason: "read-only",
1106
+ type: "reject"
1107
+ });
1108
+ /** A read-only root's handler: its check rejects every change first, so this never runs. */
1109
+ const noHandler = () => {
1110
+ throw new TypeError("calendar-root-is-read-only");
1111
+ };
1112
+ /** The detail of a proposal made without one, or with something that names no input. */
1113
+ const apiInput = Object.freeze({ input: "api" });
1114
+ const agentInput = Object.freeze({ input: "agent" });
1115
+ const knownInputs = /* @__PURE__ */ new Set([
1116
+ "agent",
1117
+ "api",
1118
+ "keyboard",
1119
+ "pointer"
1120
+ ]);
1121
+ /**
1122
+ * The source ui-sdk gives a change made now, read the one way its public entries offer: an event
1123
+ * option `dispatch` calls with the details a change would get. While an agent's step runs, such as
1124
+ * a press on the application's own button, that is `"agent"`; the state handlers hear the same.
1125
+ * The probe is a handler of our own, so nothing else hears it and nothing changes.
1126
+ */
1127
+ let probed;
1128
+ const sourceProbe = Object.freeze({ options: () => probeOptions });
1129
+ const probeOptions = Object.freeze({ onSourceProbe: (_value, details) => {
1130
+ probed = details.source;
1131
+ } });
1132
+ function currentSource() {
1133
+ probed = void 0;
1134
+ dispatch(sourceProbe, "onSourceProbe", null, { reason: "imperative" });
1135
+ return probed;
1136
+ }
1137
+ /**
1138
+ * The detail every listener hears. Anything an agent's step causes is the agent's, whatever the
1139
+ * caller passed, so a policy that refuses agents can't be stepped around by pressing a button;
1140
+ * the rest of the detail, such as a history's `history`, is kept.
1141
+ */
1142
+ function detailOf(detail) {
1143
+ if (detail?.input !== "agent" && currentSource() === "agent") return detail === void 0 ? agentInput : Object.freeze({
1144
+ ...detail,
1145
+ input: "agent"
1146
+ });
1147
+ return detail !== void 0 && knownInputs.has(detail.input) ? detail : apiInput;
1148
+ }
1149
+ /**
1150
+ * An agent deletes only where the root allows it with `allowAgentDelete`, however it got there:
1151
+ * through the calendar's own action or a button of the application's it pressed. The application
1152
+ * hears the refusal like any other, through `onEventChangeResult`.
1153
+ */
1154
+ const noAgentDeletes = ((change, { detail }) => change.cause === "delete" && detail?.input === "agent" ? {
1155
+ reason: "agent-delete-not-allowed",
1156
+ type: "reject"
1157
+ } : { type: "accept" });
1158
+ function sameLocale(left, right) {
1159
+ return String(left) === String(right);
1160
+ }
1161
+ function sameIssue(left, right) {
1162
+ 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;
1163
+ }
1164
+ function sameDiagnostics(left, right) {
1165
+ return left.length === right.length && left.every((diagnostic, index) => {
1166
+ const other = right[index];
1167
+ if (other === void 0 || other.code !== diagnostic.code) return false;
1168
+ switch (diagnostic.code) {
1169
+ case "invalid-event": return other.code === "invalid-event" && sameIssue(diagnostic.issue, other.issue);
1170
+ 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;
1171
+ 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;
1172
+ case "invalid-secondary-time-zone": return other.code === "invalid-secondary-time-zone" && other.issue.index === diagnostic.issue.index && other.issue.value === diagnostic.issue.value;
1173
+ case "unregistered-active-view": return other.code === "unregistered-active-view" && other.viewName === diagnostic.viewName;
1174
+ }
1175
+ });
1176
+ }
1177
+ function collectDiagnostics(view, viewIsRegistered, issues, annotationIssues, availabilityIssues, secondaryTimeZoneIssues) {
1178
+ const diagnostics = [];
1179
+ if (!viewIsRegistered) diagnostics.push(Object.freeze({
1180
+ code: "unregistered-active-view",
1181
+ severity: "error",
1182
+ viewName: view
1183
+ }));
1184
+ for (const issue of issues) diagnostics.push(Object.freeze({
1185
+ code: "invalid-event",
1186
+ issue,
1187
+ severity: "error"
1188
+ }));
1189
+ for (const issue of annotationIssues) diagnostics.push(Object.freeze({
1190
+ code: "invalid-annotation",
1191
+ issue,
1192
+ severity: "error"
1193
+ }));
1194
+ for (const issue of availabilityIssues) diagnostics.push(Object.freeze({
1195
+ code: "invalid-availability",
1196
+ issue,
1197
+ severity: "error"
1198
+ }));
1199
+ for (const issue of secondaryTimeZoneIssues) diagnostics.push(Object.freeze({
1200
+ code: "invalid-secondary-time-zone",
1201
+ issue,
1202
+ severity: "error"
1203
+ }));
1204
+ return Object.freeze(diagnostics);
1205
+ }
1206
+ function sameControlledState(left, right) {
1207
+ 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;
1208
+ }
1209
+ function createStateSource(store, controlled) {
1210
+ let base;
1211
+ let merged;
1212
+ return Object.freeze({
1213
+ getSnapshot: () => {
1214
+ const next = store.getSnapshot();
1215
+ if (next !== base || merged === void 0) {
1216
+ base = next;
1217
+ merged = mergeControlledState(next, controlled);
1218
+ }
1219
+ return merged;
1220
+ },
1221
+ subscribe: store.subscribe
1222
+ });
1223
+ }
1224
+ function createSemanticActions({ actions, read }, viewsByName, committed, transactions, readOnly) {
1225
+ /** The policies every change runs through; a root without `onEventChange` rejects them all. */
1226
+ function policiesOf({ allowAgentDelete, onEventChange, policies = [] }) {
1227
+ if (onEventChange === void 0) return [readOnlyRoot];
1228
+ return allowAgentDelete === true ? [readOnly, ...policies] : [
1229
+ readOnly,
1230
+ noAgentDeletes,
1231
+ ...policies
1232
+ ];
1233
+ }
1234
+ function navigate(delta, options) {
1235
+ const latest = read();
1236
+ const view = viewsByName.get(latest.view);
1237
+ if (view === void 0) return;
1238
+ const viewOptions = resolveViewOptions(view, committed.current.viewOptions?.[latest.view]);
1239
+ actions.setAnchorDate(view.strategy.navigate(latest.anchorDate, delta, viewOptions), options);
1240
+ }
1241
+ /** Proposes a change through the policies once, with the detail every listener hears. */
1242
+ function start(proposal, detail) {
1243
+ const { availability, eventSnapshot, onEventChange } = committed.current;
1244
+ const reported = detailOf(detail);
1245
+ return {
1246
+ outcome: transactions.proposeNow(proposal, {
1247
+ availability,
1248
+ detail: reported,
1249
+ onEventChange: onEventChange ?? noHandler,
1250
+ policies: policiesOf(committed.current),
1251
+ snapshot: eventSnapshot,
1252
+ timeZone: read().timeZone
1253
+ }),
1254
+ reported
1255
+ };
1256
+ }
1257
+ function report(result, detail) {
1258
+ try {
1259
+ committed.current.onEventChangeResult?.(result, detail);
1260
+ } catch (error) {
1261
+ reportCallbackError(error);
1262
+ }
1263
+ return result;
1264
+ }
1265
+ /**
1266
+ * `proposeEventChange` that answers at once when it can: what an agent's step returns before a
1267
+ * framework renders. The result callback hears every proposal once, when it settles.
1268
+ */
1269
+ function proposeNow(proposal, detail) {
1270
+ const { outcome, reported } = start(proposal, detail);
1271
+ if (outcome.status !== "pending") return report(outcome, reported);
1272
+ return Object.freeze({
1273
+ ...outcome,
1274
+ result: outcome.result.then((result) => report(result, reported))
1275
+ });
1276
+ }
1277
+ return {
1278
+ actions: Object.freeze({
1279
+ ...actions,
1280
+ checkEventChange(proposal, detail) {
1281
+ const { availability, eventSnapshot } = committed.current;
1282
+ return transactions.check(proposal, {
1283
+ availability,
1284
+ detail: detailOf(detail),
1285
+ policies: policiesOf(committed.current),
1286
+ snapshot: eventSnapshot,
1287
+ timeZone: read().timeZone
1288
+ });
1289
+ },
1290
+ navigateNext: (options) => navigate(1, options),
1291
+ navigatePrevious: (options) => navigate(-1, options),
1292
+ navigateToday(options) {
1293
+ const { environment } = committed.current;
1294
+ const instant = environment.now ?? (environment.clock ?? systemClock).instant();
1295
+ actions.setAnchorDate(instant.toZonedDateTimeISO(read().timeZone).toPlainDate(), options);
1296
+ },
1297
+ proposeEventChange(proposal, detail) {
1298
+ const { outcome, reported } = start(proposal, detail);
1299
+ return (outcome.status === "pending" ? outcome.result : Promise.resolve(outcome)).then((result) => report(result, reported));
1300
+ }
1301
+ }),
1302
+ proposeNow
1303
+ };
1304
+ }
1305
+ /**
1306
+ * The store defaults a root's props give, for `connect`'s `defaults`: a default wins over a
1307
+ * controlled value, and the first registered view stands in for a missing one.
1308
+ */
1309
+ function resolveCalendarStoreDefaults(props, views) {
1310
+ const initialAnchorDate = props.defaultAnchorDate ?? props.anchorDate;
1311
+ const initialTimeZone = props.defaultTimeZone ?? props.timeZone;
1312
+ const initialView = props.defaultView ?? props.view ?? views[0]?.name;
1313
+ if (initialAnchorDate === void 0) throw new TypeError("calendar-root-requires-anchor-date");
1314
+ if (initialTimeZone === void 0) throw new TypeError("calendar-root-requires-time-zone");
1315
+ if (initialView === void 0) throw new TypeError("calendar-root-requires-view");
1316
+ return {
1317
+ defaultAnchorDate: initialAnchorDate,
1318
+ defaultExpandedResourceIds: props.defaultExpandedResourceIds,
1319
+ defaultFocus: props.defaultFocus,
1320
+ defaultSelection: props.defaultSelection,
1321
+ defaultTimeZone: initialTimeZone,
1322
+ defaultView: initialView
1323
+ };
1324
+ }
1325
+ function createCalendarRuntime(config) {
1326
+ const views = Object.freeze([...config.views]);
1327
+ const viewsByName = new Map(views.map((view) => [view.name, view]));
1328
+ const readOnly = readOnlyPolicy();
1329
+ const snapshotCache = createEventSnapshotCache(config.eventAdapter, { invalidEventPolicy: config.invalidEventPolicy });
1330
+ const transactions = createEventTransactions();
1331
+ const keyboard = createKeyboardSessionStore();
1332
+ const pointerDraft = createDraftStore();
1333
+ const noChanges = transactions.getPendingChanges();
1334
+ const pendingChanges = Object.freeze({
1335
+ getServerSnapshot: () => noChanges,
1336
+ getSnapshot: transactions.getPendingChanges,
1337
+ subscribe: transactions.subscribe
1338
+ });
1339
+ let overlaySnapshot = Object.freeze({
1340
+ pending: transactions.getPending(),
1341
+ preview: keyboard.getPreview()
1342
+ });
1343
+ const overlay = Object.freeze({
1344
+ getSnapshot: () => {
1345
+ const pending = transactions.getPending();
1346
+ const preview = keyboard.getPreview();
1347
+ if (pending !== overlaySnapshot.pending || preview !== overlaySnapshot.preview) overlaySnapshot = Object.freeze({
1348
+ pending,
1349
+ preview
1350
+ });
1351
+ return overlaySnapshot;
1352
+ },
1353
+ subscribe: (listener) => {
1354
+ const stops = [transactions.subscribe(listener), keyboard.subscribe(listener)];
1355
+ return () => {
1356
+ for (const stop of stops) stop();
1357
+ };
1358
+ }
1359
+ });
1360
+ /** Each model's actions' `proposeNow`, which the runtime's own reads from the last commit. */
1361
+ const proposers = /* @__PURE__ */ new WeakMap();
1362
+ let committedInputs;
1363
+ let committedModel;
1364
+ let reportedRange = null;
1365
+ const announcements = createAnnouncerChannel(() => committedInputs.current.environment, () => committedInputs.current.resourceTree);
1366
+ let ownedStore;
1367
+ const bindingCell = createMemoCell();
1368
+ const controlledCell = createStableCell(sameControlledState);
1369
+ const sourceCell = createMemoCell();
1370
+ const connectionCell = createMemoCell();
1371
+ const uncommittedBinding = Object.freeze({
1372
+ controlled: {},
1373
+ handlers: {}
1374
+ });
1375
+ const locale = createStableCell(sameLocale);
1376
+ const weekRules = createStableCell(sameWeekRules);
1377
+ const now = createStableCell(sameInstant);
1378
+ const secondaryInput = createStableCell(sameSecondaryTimeZones);
1379
+ const secondaryCell = createMemoCell();
1380
+ const viewEnvironmentCell = createMemoCell();
1381
+ const environmentCell = createMemoCell();
1382
+ const eventsInput = createStableCell(sameElements);
1383
+ const eventSnapshotCell = createMemoCell();
1384
+ const visibleEventsCell = createMemoCell();
1385
+ const resourcesInput = createStableCell(sameElements);
1386
+ const resourceTreeCell = createMemoCell();
1387
+ const expandedInput = createStableCell(sameElements);
1388
+ const annotationsInput = createStableCell(sameElements);
1389
+ const annotationSnapshotCell = createMemoCell();
1390
+ const annotationSourcesInput = createStableCell(sameElements);
1391
+ const annotationsCell = createMemoCell();
1392
+ const availabilityInput = createStableCell(sameAvailability);
1393
+ const availabilityCell = createMemoCell();
1394
+ const optionsInput = createStableCell(shallowEqual);
1395
+ const rangeInput = createStableCell(sameRange);
1396
+ const loadRangeInput = createStableCell(sameRange);
1397
+ const todayInput = createStableCell(samePlainDate);
1398
+ const visibleRangeCell = createMemoCell();
1399
+ const activeViewCell = createMemoCell();
1400
+ const diagnosticsInput = createStableCell(sameDiagnostics);
1401
+ const actionsCell = createMemoCell();
1402
+ const interactionCell = createMemoCell();
1403
+ const modelCell = createMemoCell();
1404
+ function connect({ controlled: controlledInput, defaults, store: injected }) {
1405
+ if (injected === void 0) ownedStore ??= createCalendarStore(defaults());
1406
+ const store = injected ?? ownedStore;
1407
+ const internals = getCalendarStoreInternals(store);
1408
+ const controlled = controlledCell(controlledInput);
1409
+ const binding = bindingCell([internals], () => internals.bind(uncommittedBinding));
1410
+ const source = sourceCell([controlled, store], () => createStateSource(store, controlled));
1411
+ return connectionCell([
1412
+ binding,
1413
+ controlled,
1414
+ source,
1415
+ store
1416
+ ], () => Object.freeze({
1417
+ binding,
1418
+ controlled,
1419
+ source,
1420
+ store
1421
+ }));
1422
+ }
1423
+ function committedOf(inputs, model) {
1424
+ return {
1425
+ activeView: model.activeView,
1426
+ allowAgentDelete: inputs.allowAgentDelete,
1427
+ availability: model.availability,
1428
+ environment: model.environment,
1429
+ eventSnapshot: model.eventSnapshot,
1430
+ onDiagnosticsChange: inputs.onDiagnosticsChange,
1431
+ onEventChange: inputs.onEventChange,
1432
+ onEventChangeResult: inputs.onEventChangeResult,
1433
+ onVisibleRangeChange: inputs.onVisibleRangeChange,
1434
+ policies: inputs.policies,
1435
+ resourceTree: model.resourceTree,
1436
+ viewOptions: inputs.viewOptions
1437
+ };
1438
+ }
1439
+ function derive(inputs) {
1440
+ const { connection, state } = inputs;
1441
+ const stableLocale = locale(inputs.locale);
1442
+ const stableWeekRules = weekRules(inputs.weekRules);
1443
+ const stableNow = now(inputs.now);
1444
+ const stableSecondary = secondaryInput(inputs.secondaryTimeZones ?? noSecondaryTimeZones);
1445
+ const secondary = secondaryCell([stableSecondary], () => resolveSecondaryTimeZones(stableSecondary));
1446
+ const direction = inputs.direction ?? "ltr";
1447
+ const disambiguation = inputs.disambiguation ?? "compatible";
1448
+ const viewEnvironment = viewEnvironmentCell([
1449
+ direction,
1450
+ disambiguation,
1451
+ secondary.zones,
1452
+ stableLocale,
1453
+ stableWeekRules,
1454
+ state.timeZone
1455
+ ], () => Object.freeze({
1456
+ direction,
1457
+ disambiguation,
1458
+ locale: stableLocale,
1459
+ secondaryTimeZones: secondary.zones,
1460
+ timeZone: state.timeZone,
1461
+ weekRules: stableWeekRules
1462
+ }));
1463
+ const { clock } = inputs;
1464
+ const environment = environmentCell([
1465
+ clock,
1466
+ stableNow,
1467
+ viewEnvironment
1468
+ ], () => {
1469
+ if (stableNow !== void 0) return Object.freeze({
1470
+ ...viewEnvironment,
1471
+ now: stableNow
1472
+ });
1473
+ if (clock !== void 0) return Object.freeze({
1474
+ ...viewEnvironment,
1475
+ clock
1476
+ });
1477
+ return viewEnvironment;
1478
+ });
1479
+ const stableEvents = eventsInput(inputs.events);
1480
+ const eventSnapshot = eventSnapshotCell([stableEvents], () => snapshotCache.getSnapshot(stableEvents));
1481
+ const { pending, preview } = inputs.overlay;
1482
+ const visibleEvents = visibleEventsCell([
1483
+ eventSnapshot,
1484
+ pending,
1485
+ preview
1486
+ ], () => applyEventOverlay(applyEventOverlay(eventSnapshot, pending), preview));
1487
+ const resources = resourcesInput(inputs.resources ?? noResources);
1488
+ const resourceTree = resourceTreeCell([resources], () => createResourceTree(resources));
1489
+ const expandedResourceIds = expandedInput(state.expandedResourceIds);
1490
+ const annotationList = annotationsInput(inputs.annotations ?? noAnnotations);
1491
+ const annotationSnapshot = annotationSnapshotCell([annotationList], () => createAnnotationSnapshot(annotationList));
1492
+ const annotationSources = annotationSourcesInput(inputs.annotationSources ?? noAnnotations);
1493
+ const annotations = annotationsCell([annotationSnapshot, annotationSources], () => Object.freeze({
1494
+ snapshot: annotationSnapshot,
1495
+ sources: annotationSources
1496
+ }));
1497
+ const availabilityRules = availabilityInput(inputs.availability);
1498
+ const availability = availabilityCell([
1499
+ availabilityRules,
1500
+ resources,
1501
+ state.timeZone
1502
+ ], () => createAvailabilitySnapshot({
1503
+ availability: availabilityRules,
1504
+ resources,
1505
+ timeZone: state.timeZone
1506
+ }));
1507
+ const activeDefinition = viewsByName.get(state.view);
1508
+ const viewOverrides = inputs.viewOptions;
1509
+ const options = optionsInput(activeDefinition === void 0 ? void 0 : resolveViewOptions(activeDefinition, viewOverrides?.[state.view]));
1510
+ const range = rangeInput(activeDefinition?.strategy.getRange(state.anchorDate, viewEnvironment, options));
1511
+ const loadRange = loadRangeInput(activeDefinition === void 0 || range === void 0 ? void 0 : resolveViewLoadRange(activeDefinition.strategy, state.anchorDate, viewEnvironment, options, range));
1512
+ const { instant } = inputs;
1513
+ const today = todayInput(instant === null ? null : instant.toZonedDateTimeISO(state.timeZone).toPlainDate());
1514
+ const visibleRange = visibleRangeCell([
1515
+ activeDefinition,
1516
+ loadRange,
1517
+ range,
1518
+ viewEnvironment.timeZone
1519
+ ], () => activeDefinition === void 0 || range === void 0 || loadRange === void 0 ? null : Object.freeze({
1520
+ instantRange: resolveViewInstantRange(range, viewEnvironment.timeZone),
1521
+ loadInstantRange: resolveViewInstantRange(loadRange, viewEnvironment.timeZone),
1522
+ loadRange,
1523
+ range,
1524
+ view: activeDefinition.name
1525
+ }));
1526
+ const activeView = activeViewCell([
1527
+ activeDefinition,
1528
+ options,
1529
+ visibleRange,
1530
+ resourceTree,
1531
+ expandedResourceIds,
1532
+ today,
1533
+ viewEnvironment,
1534
+ visibleEvents
1535
+ ], () => {
1536
+ if (activeDefinition === void 0 || visibleRange === null) return null;
1537
+ const { instantRange, loadInstantRange, loadRange, range } = visibleRange;
1538
+ return Object.freeze({
1539
+ definition: activeDefinition,
1540
+ environment: viewEnvironment,
1541
+ events: visibleEvents,
1542
+ instantRange,
1543
+ loadInstantRange,
1544
+ loadRange,
1545
+ options,
1546
+ projection: activeDefinition.strategy.project({
1547
+ environment: viewEnvironment,
1548
+ expandedResourceIds,
1549
+ instantRange,
1550
+ loadRange,
1551
+ options,
1552
+ range,
1553
+ resources: resourceTree,
1554
+ snapshot: visibleEvents,
1555
+ today
1556
+ }),
1557
+ range,
1558
+ view: activeDefinition.name
1559
+ });
1560
+ });
1561
+ const diagnostics = diagnosticsInput(collectDiagnostics(state.view, activeDefinition !== void 0, eventSnapshot.issues, annotationSnapshot.issues, availability.issues, secondary.issues));
1562
+ committedInputs ??= { current: {
1563
+ activeView,
1564
+ allowAgentDelete: inputs.allowAgentDelete,
1565
+ availability,
1566
+ environment,
1567
+ eventSnapshot,
1568
+ onDiagnosticsChange: inputs.onDiagnosticsChange,
1569
+ onEventChange: inputs.onEventChange,
1570
+ onEventChangeResult: inputs.onEventChangeResult,
1571
+ onVisibleRangeChange: inputs.onVisibleRangeChange,
1572
+ policies: inputs.policies,
1573
+ resourceTree,
1574
+ viewOptions: viewOverrides
1575
+ } };
1576
+ const committed = committedInputs;
1577
+ const { binding, source } = connection;
1578
+ const actions = actionsCell([binding], () => {
1579
+ const created = createSemanticActions(binding, viewsByName, committed, transactions, readOnly);
1580
+ proposers.set(created.actions, created.proposeNow);
1581
+ return created.actions;
1582
+ });
1583
+ const isReadOnly = inputs.onEventChange === void 0;
1584
+ const interaction = interactionCell([
1585
+ actions,
1586
+ binding,
1587
+ isReadOnly,
1588
+ source
1589
+ ], () => Object.freeze({
1590
+ actions,
1591
+ announcements,
1592
+ changes: pendingChanges,
1593
+ isReadOnly,
1594
+ keyboard,
1595
+ pointerDraft,
1596
+ rangeOf: (anchor) => {
1597
+ const view = committed.current.activeView;
1598
+ return view === null ? null : view.definition.strategy.getRange(anchor, view.environment, view.options);
1599
+ },
1600
+ read: binding.read,
1601
+ requests: binding.subscribeRequests,
1602
+ source
1603
+ }));
1604
+ const model = modelCell([
1605
+ actions,
1606
+ activeDefinition,
1607
+ activeView,
1608
+ annotations,
1609
+ availability,
1610
+ diagnostics,
1611
+ environment,
1612
+ eventSnapshot,
1613
+ interaction,
1614
+ isReadOnly,
1615
+ resourceTree,
1616
+ resources,
1617
+ source,
1618
+ state,
1619
+ today,
1620
+ viewEnvironment,
1621
+ visibleEvents,
1622
+ visibleRange
1623
+ ], () => Object.freeze({
1624
+ actions,
1625
+ activeDefinition,
1626
+ activeView,
1627
+ annotations,
1628
+ availability,
1629
+ diagnostics,
1630
+ environment,
1631
+ eventSnapshot,
1632
+ interaction,
1633
+ isReadOnly,
1634
+ resourceTree,
1635
+ resources,
1636
+ source,
1637
+ state,
1638
+ today,
1639
+ viewEnvironment,
1640
+ visibleEvents,
1641
+ visibleRange
1642
+ }));
1643
+ committedModel ??= model;
1644
+ return model;
1645
+ }
1646
+ return Object.freeze({
1647
+ announcements,
1648
+ commit(model, inputs) {
1649
+ inputs.connection.binding.commit({
1650
+ controlled: inputs.connection.controlled,
1651
+ handlers: inputs.handlers
1652
+ });
1653
+ const record = committedOf(inputs, model);
1654
+ if (committedInputs === void 0) committedInputs = { current: record };
1655
+ else committedInputs.current = record;
1656
+ committedModel = model;
1657
+ },
1658
+ committed: () => committedModel,
1659
+ connect,
1660
+ derive,
1661
+ keyboard,
1662
+ overlay,
1663
+ pendingChanges,
1664
+ pointerDraft,
1665
+ proposeNow(proposal, detail) {
1666
+ const propose = committedModel === void 0 ? void 0 : proposers.get(committedModel.actions);
1667
+ if (propose === void 0) throw new Error("calendar-runtime-before-first-derive");
1668
+ return propose(proposal, detail);
1669
+ },
1670
+ latest() {
1671
+ const model = committedModel;
1672
+ if (model === void 0) return void 0;
1673
+ const state = model.interaction.read();
1674
+ const definition = viewsByName.get(state.view);
1675
+ if (definition === void 0) return Object.freeze({
1676
+ range: null,
1677
+ state
1678
+ });
1679
+ const environment = {
1680
+ ...model.viewEnvironment,
1681
+ timeZone: state.timeZone
1682
+ };
1683
+ const options = resolveViewOptions(definition, committedInputs?.current.viewOptions?.[state.view]);
1684
+ return Object.freeze({
1685
+ range: definition.strategy.getRange(state.anchorDate, environment, options),
1686
+ state
1687
+ });
1688
+ },
1689
+ reconcile: (eventSnapshot) => transactions.reconcile(eventSnapshot),
1690
+ reportDiagnostics(diagnostics) {
1691
+ committedInputs?.current.onDiagnosticsChange?.(diagnostics);
1692
+ },
1693
+ reportVisibleRange(visibleRange) {
1694
+ if (visibleRange === null || visibleRange === reportedRange) return;
1695
+ reportedRange = visibleRange;
1696
+ committedInputs?.current.onVisibleRangeChange?.(visibleRange);
1697
+ },
1698
+ transactions,
1699
+ views,
1700
+ viewsByName
1701
+ });
1702
+ }
1703
+ export { TODAY_SAMPLE_INTERVAL_MS, agentEventLabel, calendarAgentActions, calendarStateSlices, clockOf, createAnnouncerChannel, createCalendarPartIds, createCalendarPrimitive, createCalendarRuntime, createCalendarStore, createClockTicker, createDraftStore, createKeyboardSessionStore, createMemoCell, createStableCell, describeAgentEvent, describeAgentPlacement, eventLabel, eventsInRange, findEvent, getCalendarStoreInternals, mergeControlledState, parseInstant, parsePlainDate, parsePlainDateTime, parseTimeZone, readAgentInput, reportCallbackError, resolveCalendarStoreDefaults, resolveViewOptions, sameAvailability, sameElements, sameInstant, samePlainDate, sameRange, sameSecondaryTimeZones, sameSliceValue, sameWeekRules, shallowEqual, systemClock, visibleEventsOf };