@moltenship/calendar-testing 0.0.0-stage → 1.0.0-rc.2

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,1643 @@
1
+ import { parseRecurrenceRule } from "@moltenship/calendar-recurrence";
2
+ import { StrictMode, act, createElement, useLayoutEffect, useSyncExternalStore } from "react";
3
+ import { createRoot, hydrateRoot } from "react-dom/client";
4
+ import { renderToString } from "react-dom/server";
5
+ import { eventIdOf, resourceIdOf, sameFocus } from "@moltenship/calendar";
6
+ //#region src/environment.ts
7
+ /** What `createTestEnvironment` uses for each option left out. */
8
+ const testDefaults = Object.freeze({
9
+ direction: "ltr",
10
+ locale: "en-US",
11
+ now: "2026-10-08T12:00:00Z",
12
+ timeZone: "UTC",
13
+ weekRules: Object.freeze({
14
+ firstDay: 1,
15
+ minimalDays: 4,
16
+ weekend: Object.freeze([6, 7])
17
+ })
18
+ });
19
+ /**
20
+ * Throws a clear error when the runtime has no `Temporal`. The package never installs a polyfill:
21
+ * add `if (!("Temporal" in globalThis)) await import("temporal-polyfill/global");` to the test
22
+ * setup, as apps do for browsers without it.
23
+ */
24
+ function requireTemporal() {
25
+ if (typeof globalThis.Temporal === "undefined") throw new Error("@moltenship/calendar-testing needs Temporal, and this runtime has none. Add `if (!(\"Temporal\" in globalThis)) await import(\"temporal-polyfill/global\");` to your test setup file.");
26
+ }
27
+ /**
28
+ * A bracketed time zone, such as `[Europe/Berlin]` or `[!Europe/Berlin]`; annotations with a `=`,
29
+ * such as `[u-ca=iso8601]`, name something else.
30
+ */
31
+ const zoneAnnotation = /\[!?[^\]=]+\]/u;
32
+ /** Whether ISO text names an exact time: a `Z` or an offset after the time, or a time zone. */
33
+ function isExact(text) {
34
+ if (zoneAnnotation.test(text)) return true;
35
+ const time = text.trim().split(/[Tt ]/u)[1] ?? "";
36
+ return /[zZ+-]/u.test(time.replace(/\[.*$/u, ""));
37
+ }
38
+ /**
39
+ * An instant from `value`. Text with `Z`, an offset or a time zone is exact, such as
40
+ * `"2026-10-08T09:00Z"` or `"2026-10-08[Europe/Berlin]"` (midnight there); text without is a wall
41
+ * time on `timeZone`'s clock, where a time in a DST gap resolves later, as `Root` does.
42
+ */
43
+ function toInstant(value, timeZone) {
44
+ requireTemporal();
45
+ if (typeof value !== "string") return "toInstant" in value ? value.toInstant() : Temporal.Instant.from(value);
46
+ if (!isExact(value)) return Temporal.PlainDateTime.from(value).toZonedDateTime(timeZone).toInstant();
47
+ return zoneAnnotation.test(value) ? Temporal.ZonedDateTime.from(value).toInstant() : Temporal.Instant.from(value);
48
+ }
49
+ /** A date from a `PlainDate` or ISO text. */
50
+ function toPlainDate(value) {
51
+ requireTemporal();
52
+ return Temporal.PlainDate.from(value);
53
+ }
54
+ /**
55
+ * Builds a deterministic environment. Every option has a default: Thursday 8 October 2026 at noon
56
+ * UTC, `"en-US"`, weeks from Monday (`{ firstDay: 1, minimalDays: 4, weekend: [6, 7] }`), left to
57
+ * right.
58
+ */
59
+ function createTestEnvironment(options = {}) {
60
+ requireTemporal();
61
+ const timeZone = options.timeZone ?? testDefaults.timeZone;
62
+ const locale = options.locale ?? testDefaults.locale;
63
+ const weekRules = options.weekRules ?? testDefaults.weekRules;
64
+ const direction = options.direction ?? testDefaults.direction;
65
+ const now = toInstant(options.now ?? testDefaults.now, timeZone);
66
+ const today = now.toZonedDateTimeISO(timeZone).toPlainDate();
67
+ const anchorDate = options.anchorDate === void 0 ? today : toPlainDate(options.anchorDate);
68
+ return Object.freeze({
69
+ anchorDate,
70
+ at(value) {
71
+ if (typeof value === "string" && /^\d{2}:\d{2}/u.test(value.trim())) return today.toPlainDateTime(Temporal.PlainTime.from(value)).toZonedDateTime(timeZone).toInstant();
72
+ return toInstant(value, timeZone);
73
+ },
74
+ direction,
75
+ locale,
76
+ now,
77
+ rootProps: Object.freeze({
78
+ defaultAnchorDate: anchorDate,
79
+ defaultTimeZone: timeZone,
80
+ direction,
81
+ locale,
82
+ now,
83
+ weekRules
84
+ }),
85
+ timeZone,
86
+ today,
87
+ weekRules
88
+ });
89
+ }
90
+ /**
91
+ * A clock for `Root`'s `clock` prop, or the harness's `clock` option, starting at `start`
92
+ * (8 October 2026 at noon UTC by default). Text without a zone or offset is a UTC wall time. `Root`
93
+ * and `useNow` sample a clock on an interval, a minute by default, so a test that moves it also
94
+ * advances fake timers; to show a new time at once, use a fixed `now` and the harness's `setNow`.
95
+ */
96
+ function createTestClock(start = testDefaults.now) {
97
+ let current = toInstant(start, "UTC");
98
+ return Object.freeze({
99
+ advance(duration) {
100
+ current = current.add(duration);
101
+ return current;
102
+ },
103
+ instant: () => current,
104
+ set(instant) {
105
+ current = toInstant(instant, "UTC");
106
+ }
107
+ });
108
+ }
109
+ //#endregion
110
+ //#region src/builders.ts
111
+ /** The start events get without one: 09:00 on the default environment's date. */
112
+ const defaultStart = "2026-10-08T09:00";
113
+ const defaultDate = "2026-10-08";
114
+ /** `data` as given, `null` when left out. */
115
+ function dataOf(input) {
116
+ return "data" in input ? input.data : null;
117
+ }
118
+ function identity(id, title, fallback) {
119
+ const named = title ?? (id === void 0 ? fallback : String(id));
120
+ return {
121
+ id: id ?? named,
122
+ title: named
123
+ };
124
+ }
125
+ /** A timed event in the canonical shape `createCanonicalEventAdapter` reads. */
126
+ function buildEvent(input = {}) {
127
+ const timeZone = input.timeZone ?? "UTC";
128
+ const start = toInstant(input.start ?? defaultStart, timeZone);
129
+ const end = input.end === void 0 ? start.toZonedDateTimeISO(timeZone).add(input.duration ?? { hours: 1 }).toInstant() : toInstant(input.end, timeZone);
130
+ return Object.freeze({
131
+ ...identity(input.id, input.title, "Event"),
132
+ data: dataOf(input),
133
+ end,
134
+ kind: "timed",
135
+ ...input.resourceIds === void 0 ? {} : { resourceIds: Object.freeze([...input.resourceIds]) },
136
+ ...input.timeZone === void 0 ? {} : { sourceTimeZone: input.timeZone },
137
+ start
138
+ });
139
+ }
140
+ /** An all-day event in the canonical shape. */
141
+ function buildAllDayEvent(input = {}) {
142
+ const start = toPlainDate(input.start ?? defaultDate);
143
+ const end = input.end === void 0 ? start.add({ days: input.days ?? 1 }) : toPlainDate(input.end);
144
+ return Object.freeze({
145
+ ...identity(input.id, input.title, "Event"),
146
+ data: dataOf(input),
147
+ end,
148
+ kind: "all-day",
149
+ ...input.resourceIds === void 0 ? {} : { resourceIds: Object.freeze([...input.resourceIds]) },
150
+ start
151
+ });
152
+ }
153
+ /** A resource in the canonical `CalendarResource` shape. */
154
+ function buildResource(input = {}) {
155
+ const { id, title } = identity(input.id, input.title, "Resource");
156
+ return Object.freeze({
157
+ ...input.availability === void 0 ? {} : { availability: input.availability },
158
+ data: dataOf(input),
159
+ id,
160
+ ...input.parentId === void 0 ? {} : { parentId: input.parentId },
161
+ ...input.timeZone === void 0 ? {} : { timeZone: input.timeZone },
162
+ title
163
+ });
164
+ }
165
+ function toHours(input) {
166
+ if (typeof input === "string") {
167
+ const [start, end] = input.split("-").map((part) => part.trim());
168
+ if (start === void 0 || end === void 0) throw new RangeError(`Hours must look like "09:00-17:00", not ${JSON.stringify(input)}`);
169
+ return Object.freeze({
170
+ end: Temporal.PlainTime.from(end),
171
+ start: Temporal.PlainTime.from(start)
172
+ });
173
+ }
174
+ return Object.freeze({
175
+ end: Temporal.PlainTime.from(input.end),
176
+ start: Temporal.PlainTime.from(input.start)
177
+ });
178
+ }
179
+ function toHoursList(input) {
180
+ return Object.freeze((typeof input === "string" || !Array.isArray(input) ? [input] : input).map(toHours));
181
+ }
182
+ const weekdays = Object.freeze([
183
+ 1,
184
+ 2,
185
+ 3,
186
+ 4,
187
+ 5
188
+ ]);
189
+ /** Working hours for `Root`'s `availability` or a resource's: Monday to Friday, 9 to 5 by default. */
190
+ function buildAvailability(input = {}) {
191
+ const days = Object.freeze([...input.days ?? weekdays]);
192
+ const weekly = Object.freeze(toHoursList(input.hours ?? "09:00-17:00").map((hours) => Object.freeze({
193
+ ...hours,
194
+ days
195
+ })));
196
+ const exceptions = Object.freeze((input.exceptions ?? []).map((exception) => Object.freeze({
197
+ date: toPlainDate(exception.date),
198
+ ...exception.hours === void 0 ? {} : { hours: toHoursList(exception.hours) },
199
+ ...exception.label === void 0 ? {} : { label: exception.label }
200
+ })));
201
+ return Object.freeze({
202
+ ...exceptions.length === 0 ? {} : { exceptions },
203
+ ...input.timeZone === void 0 ? {} : { timeZone: input.timeZone },
204
+ weekly
205
+ });
206
+ }
207
+ function parseRule(rule) {
208
+ if (typeof rule !== "string") return rule;
209
+ const { issues, rule: parsed } = parseRecurrenceRule(rule);
210
+ const errors = issues.filter(({ severity }) => severity === "error");
211
+ if (parsed === void 0 || errors.length > 0) {
212
+ const reasons = (errors.length > 0 ? errors : issues).map(({ message }) => message);
213
+ throw new RangeError(`Invalid RRULE ${JSON.stringify(rule)}: ${reasons.join("; ") || "no rule"}`);
214
+ }
215
+ return parsed;
216
+ }
217
+ /**
218
+ * Makes `event` the master of a series. Dates given as text take the event's kind: instants (wall
219
+ * times on its `sourceTimeZone`, or UTC) for a timed event, date-times for a floating one, dates
220
+ * for an all-day one. A date alone on a timed or floating series, such as `"2026-10-28"`, stays a
221
+ * date in `exceptionDates`, which drops every occurrence that day; in `recurrenceDates` it throws,
222
+ * as an extra occurrence of such a series needs a time.
223
+ */
224
+ function withRecurrence(event, recurrence) {
225
+ const zone = event.kind === "timed" ? event.sourceTimeZone ?? "UTC" : "UTC";
226
+ const toDate = (value, role) => {
227
+ if (typeof value !== "string") return value;
228
+ if (event.kind === "all-day") return Temporal.PlainDate.from(value);
229
+ if (!/[Tt ]/u.test(value)) {
230
+ if (role === "exception") return Temporal.PlainDate.from(value);
231
+ throw new RangeError(`An extra occurrence of a ${event.kind} series needs a time, not just the date ${JSON.stringify(value)}.`);
232
+ }
233
+ if (event.kind === "floating") return Temporal.PlainDateTime.from(value);
234
+ return toInstant(value, zone);
235
+ };
236
+ const result = {
237
+ ...recurrence.duration === void 0 ? {} : { duration: Temporal.Duration.from(recurrence.duration) },
238
+ ...recurrence.exceptionDates === void 0 ? {} : { exceptionDates: Object.freeze(recurrence.exceptionDates.map((value) => toDate(value, "exception"))) },
239
+ ...recurrence.recurrenceDates === void 0 ? {} : { recurrenceDates: Object.freeze(recurrence.recurrenceDates.map((value) => typeof value === "string" || !("start" in value) ? toDate(value, "extra") : value)) },
240
+ ...recurrence.rule === void 0 ? {} : { rule: parseRule(recurrence.rule) }
241
+ };
242
+ return Object.freeze({
243
+ ...event,
244
+ recurrence: Object.freeze(result)
245
+ });
246
+ }
247
+ /**
248
+ * A timed recurring series: `buildEvent`'s input, where `duration` sizes the first occurrence,
249
+ * plus the rule and dates. Give `timeZone`, so the series repeats on that zone's wall clock.
250
+ */
251
+ function buildRecurringEvent(input) {
252
+ const { exceptionDates, recurrenceDates, rule, ...event } = input;
253
+ return withRecurrence(buildEvent(event), {
254
+ exceptionDates,
255
+ recurrenceDates,
256
+ rule
257
+ });
258
+ }
259
+ //#endregion
260
+ //#region src/changes.ts
261
+ /** Whether a record has the canonical event shape: a kind and ends of its own. */
262
+ function isCanonicalEvent(record) {
263
+ return typeof record === "object" && record !== null && "id" in record && "kind" in record && "start" in record && "end" in record;
264
+ }
265
+ function placed(event, placement) {
266
+ const record = event;
267
+ const { sourceTimeZone: _sourceTimeZone, ...rest } = record;
268
+ const keepResources = record.resourceIds !== void 0 || placement.resourceIds.length > 0;
269
+ return Object.freeze({
270
+ ...placement.kind === "timed" ? record : rest,
271
+ end: placement.end,
272
+ kind: placement.kind,
273
+ ...keepResources ? { resourceIds: placement.resourceIds } : {},
274
+ ...placement.kind === "timed" && placement.sourceTimeZone !== void 0 ? { sourceTimeZone: placement.sourceTimeZone } : {},
275
+ start: placement.start
276
+ });
277
+ }
278
+ /**
279
+ * Applies a change `onEventChange` received to canonical events (`CalendarEvent`), as an app
280
+ * that saves at once would: a move or resize takes the proposed placement, a delete drops the
281
+ * event, and a create adds `createEvent`'s record placed where it was proposed, or the record the
282
+ * change carries, as an undone delete does. Returns a new array.
283
+ */
284
+ function applyCanonicalChange(events, change, options = {}) {
285
+ if (events.find((event) => !isCanonicalEvent(event)) !== void 0) throw new TypeError("applyCanonicalChange works on canonical CalendarEvent records; pass `applyChange` for your own event type.");
286
+ if (change.cause === "delete") return events.filter((event) => event.id !== change.eventId);
287
+ if (change.cause === "create") {
288
+ const taken = new Set(events.map((event) => event.id));
289
+ let sequence = 1;
290
+ while (taken.has(`new-${sequence}`)) sequence += 1;
291
+ const id = `new-${sequence}`;
292
+ const base = change.event ?? options.createEvent?.(change, id) ?? {
293
+ data: null,
294
+ id,
295
+ title: "New event"
296
+ };
297
+ return [...events, placed(base, change.proposed)];
298
+ }
299
+ return events.map((event) => event.id === change.eventId ? placed(event, change.proposed) : event);
300
+ }
301
+ //#endregion
302
+ //#region src/real-time.ts
303
+ /**
304
+ * Milliseconds on the page's own clock, read through the `performance` object as it was when the
305
+ * package loaded, so deadlines keep running when a test fakes `performance` later.
306
+ */
307
+ const page = globalThis.performance;
308
+ const now = page === void 0 ? void 0 : page.now.bind(page);
309
+ function realNow() {
310
+ return now?.() ?? 0;
311
+ }
312
+ //#endregion
313
+ //#region src/queries.ts
314
+ /** Thrown when a query finds nothing, or more than one thing where it needs one. */
315
+ var CalendarQueryError = class extends Error {
316
+ constructor(message) {
317
+ super(message);
318
+ this.name = "CalendarQueryError";
319
+ }
320
+ };
321
+ /** Text with the thin and no-break spaces `Intl` output uses made plain, and trimmed. */
322
+ function normalizeText(text) {
323
+ return (text ?? "").replace(/\s+/gu, " ").trim();
324
+ }
325
+ function describe(query) {
326
+ if (typeof query === "string" || typeof query === "number") return JSON.stringify(query);
327
+ if ("id" in query) return `{ id: ${JSON.stringify(query.id)} }`;
328
+ if ("title" in query) return `{ title: ${JSON.stringify(query.title)} }`;
329
+ return `{ start: ${String(query.start)} }`;
330
+ }
331
+ /** ISO text without its bracketed annotations, such as `[America/Toronto]`. */
332
+ const withoutAnnotations = (text) => text.replace(/\[[^\]]*\]/gu, "");
333
+ function startsAt(event, start, timeZone) {
334
+ if (typeof start === "string") {
335
+ const text = withoutAnnotations(start);
336
+ if (!/[Tt ]/u.test(text)) return event.kind === "all-day" && event.start.equals(toPlainDate(start));
337
+ if (event.kind === "floating") return !/[zZ+-]/u.test(text.split(/[Tt ]/u)[1] ?? "") && event.start.equals(Temporal.PlainDateTime.from(start));
338
+ return event.kind === "timed" && event.start.equals(toInstant(start, timeZone));
339
+ }
340
+ if (start instanceof Temporal.PlainDate) return event.kind === "all-day" && event.start.equals(start);
341
+ if (start instanceof Temporal.PlainDateTime) return event.kind === "floating" && event.start.equals(start);
342
+ return event.kind === "timed" && event.start.equals(toInstant(start, timeZone));
343
+ }
344
+ /** The events of `snapshot` a query names, as the calendar shows them, pending changes included. */
345
+ function findEvents(snapshot, query, timeZone) {
346
+ const events = snapshot.events.map((event) => snapshot.get(event.id) ?? event);
347
+ if (typeof query === "number") return events.filter(({ id }) => id === query);
348
+ if (typeof query === "string") {
349
+ const byId = events.filter(({ id }) => id === query);
350
+ return byId.length > 0 ? byId : events.filter(({ title }) => title === query);
351
+ }
352
+ if ("id" in query) return events.filter(({ id }) => id === query.id);
353
+ if ("title" in query) return events.filter(({ title }) => title === query.title);
354
+ return events.filter((event) => startsAt(event, query.start, timeZone));
355
+ }
356
+ /** The one event a query names; throws when it names none or several. */
357
+ function findEvent(snapshot, query, timeZone) {
358
+ const found = findEvents(snapshot, query, timeZone);
359
+ if (found.length === 1) return found[0];
360
+ const titles = snapshot.events.map(({ id, title }) => `${JSON.stringify(title)} (${JSON.stringify(id)})`);
361
+ if (found.length === 0) throw new CalendarQueryError(`No event matches ${describe(query)}. The calendar has ${titles.length === 0 ? "no events" : titles.join(", ")}.`);
362
+ throw new CalendarQueryError(`${found.length} events match ${describe(query)}: ${found.map(({ id }) => JSON.stringify(id)).join(", ")}. Name one by its ID.`);
363
+ }
364
+ /** Elements showing an event, in document order; a drag's floating copy isn't one of them. */
365
+ function eventElements(container, id) {
366
+ return [...container.querySelectorAll("[data-event-id]")].filter((element) => eventIdOf(element) === id && element.closest("[data-calendar-ghost]") === null);
367
+ }
368
+ /** Whether an element sits in a resource: always, when none is asked for. */
369
+ function inResource(element, resourceId) {
370
+ return resourceId === void 0 || resourceIdOf(element) === resourceId;
371
+ }
372
+ /** `[data-date]` elements for a date, in a resource. */
373
+ function dated(container, date, resourceId) {
374
+ const key = toPlainDate(date).toString();
375
+ return [...container.querySelectorAll(`[data-date="${key}"]`)].filter((element) => inResource(element, resourceId));
376
+ }
377
+ /**
378
+ * The cell for a day: a time grid's all-day cell (`data-all-day`), else a month's day, the first
379
+ * `data-date` element that isn't a timeline's strip.
380
+ */
381
+ function dayCell(container, date, resourceId) {
382
+ const cells = dated(container, date, resourceId);
383
+ return cells.find((cell) => cell.hasAttribute("data-all-day")) ?? cells.find((cell) => cell.getAttribute("data-axis") !== "inline") ?? null;
384
+ }
385
+ /**
386
+ * The column holding a day's time: a `data-date` element without `data-all-day`, a timeline's
387
+ * strip (`data-axis="inline"`) first. In a month, the day itself, which has no time to point at.
388
+ */
389
+ function timeColumn(container, date, resourceId) {
390
+ const cells = dated(container, date, resourceId).filter((cell) => !cell.hasAttribute("data-all-day"));
391
+ return cells.find((cell) => cell.getAttribute("data-axis") === "inline") ?? cells[0] ?? null;
392
+ }
393
+ /** Elements carrying a resource's `resourceIdAttributes`, in document order. */
394
+ function resourceElements(container, resourceId) {
395
+ return [...container.querySelectorAll("[data-resource-id]")].filter((element) => resourceIdOf(element) === resourceId);
396
+ }
397
+ //#endregion
398
+ //#region src/announcements.ts
399
+ const announcer = "[data-calendar-part=\"announcer\"]";
400
+ /**
401
+ * Records what every `Announcer` in a container says, in order: a live region's text after each
402
+ * change, as a screen reader reads it. Only the `Announcer` mounted last speaks, so the record
403
+ * follows whichever one changed. A message that repeats the last gets a trailing no-break space,
404
+ * so its region changes; it counts again.
405
+ */
406
+ function recordAnnouncements(container) {
407
+ const spoken = [];
408
+ const lastText = /* @__PURE__ */ new WeakMap();
409
+ let latest;
410
+ function read() {
411
+ for (const region of container.querySelectorAll(announcer)) {
412
+ const text = region.textContent ?? "";
413
+ if (text === (lastText.get(region) ?? "")) continue;
414
+ lastText.set(region, text);
415
+ const message = normalizeText(text);
416
+ if (message === "") continue;
417
+ spoken.push(message);
418
+ latest = region;
419
+ }
420
+ }
421
+ const observer = typeof MutationObserver === "function" ? new MutationObserver(read) : void 0;
422
+ observer?.observe(container, {
423
+ characterData: true,
424
+ childList: true,
425
+ subtree: true
426
+ });
427
+ return {
428
+ /** Every message so far, oldest first. */
429
+ all() {
430
+ read();
431
+ return [...spoken];
432
+ },
433
+ /** What the announcer that spoke last says now; `undefined` when it's silent or there's none. */
434
+ current() {
435
+ read();
436
+ const text = latest !== void 0 && container.contains(latest) ? normalizeText(latest.textContent) : "";
437
+ return text === "" ? void 0 : text;
438
+ },
439
+ stop: () => observer?.disconnect()
440
+ };
441
+ }
442
+ //#endregion
443
+ //#region src/keyboard.ts
444
+ /** `KeyboardEvent.code` for a key, on a US layout. */
445
+ function codeOf(key) {
446
+ if (key === " ") return "Space";
447
+ if (/^[a-z]$/iu.test(key)) return `Key${key.toUpperCase()}`;
448
+ if (/^\d$/u.test(key)) return `Digit${key}`;
449
+ return key;
450
+ }
451
+ function withResource(focus, resourceId) {
452
+ return resourceId === void 0 ? focus : {
453
+ ...focus,
454
+ resourceId
455
+ };
456
+ }
457
+ function createKeyboardDriver(context) {
458
+ const { container } = context;
459
+ async function press(key, modifiers = {}) {
460
+ const target = document.activeElement;
461
+ if (!(target instanceof HTMLElement) || target === document.body) throw new CalendarQueryError(`Nothing has focus to press ${JSON.stringify(key)} on; focus an event or a cell first.`);
462
+ await act(async () => {
463
+ target.dispatchEvent(new KeyboardEvent("keydown", {
464
+ bubbles: true,
465
+ cancelable: true,
466
+ code: codeOf(key),
467
+ key,
468
+ ...modifiers
469
+ }));
470
+ await Promise.resolve();
471
+ });
472
+ }
473
+ async function repeat(key, times) {
474
+ for (let index = 0; index < times; index += 1) await press(key);
475
+ }
476
+ async function arrows({ down = 0, left = 0, right = 0, up = 0 }) {
477
+ await repeat("ArrowUp", up);
478
+ await repeat("ArrowDown", down);
479
+ await repeat("ArrowLeft", left);
480
+ await repeat("ArrowRight", right);
481
+ }
482
+ async function step({ across = 0, down = 0 }) {
483
+ const later = context.direction() === "rtl" ? "ArrowLeft" : "ArrowRight";
484
+ const earlier = later === "ArrowLeft" ? "ArrowRight" : "ArrowLeft";
485
+ await repeat(down >= 0 ? "ArrowDown" : "ArrowUp", Math.abs(down));
486
+ await repeat(across >= 0 ? later : earlier, Math.abs(across));
487
+ }
488
+ /**
489
+ * Sets the calendar's focus, then moves DOM focus to the view's tab stop and checks that it
490
+ * landed there: the tab stop is the focused element when the view shows it, or else its entry.
491
+ * On failure, the focus goes back to what it was.
492
+ */
493
+ async function focusThrough(focus, matches, describeTarget) {
494
+ const before = context.focus();
495
+ const beforeElement = document.activeElement;
496
+ const tried = /* @__PURE__ */ new Set();
497
+ for (let attempt = 0; attempt < 20; attempt += 1) {
498
+ await act(async () => context.setFocus(focus));
499
+ const stop = [...container.querySelectorAll("[tabindex=\"0\"]")].find((element) => !tried.has(element) && element.closest("[data-calendar-part=\"toolbar\"]") === null);
500
+ if (stop === void 0) break;
501
+ tried.add(stop);
502
+ if (document.activeElement === stop) await act(async () => stop.blur());
503
+ await act(async () => stop.focus());
504
+ if (matches(context.focus())) return stop;
505
+ }
506
+ await act(async () => context.setFocus(before));
507
+ const restored = beforeElement instanceof HTMLElement && beforeElement.isConnected ? beforeElement : before === null ? void 0 : [...container.querySelectorAll("[tabindex=\"0\"]")].find((element) => element.closest("[data-calendar-part=\"toolbar\"]") === null);
508
+ await act(async () => {
509
+ if (restored !== void 0) restored.focus();
510
+ else if (document.activeElement instanceof HTMLElement) document.activeElement.blur();
511
+ });
512
+ throw new CalendarQueryError(`The view shows no ${describeTarget()}.`);
513
+ }
514
+ /** The day an event starts, or the first day shown when it started earlier. */
515
+ function firstShownDate(event) {
516
+ const start = event.kind === "all-day" ? event.start : event.kind === "floating" ? event.start.toPlainDate() : event.start.toZonedDateTimeISO(context.timeZone()).toPlainDate();
517
+ const range = context.visibleRange();
518
+ return range !== null && Temporal.PlainDate.compare(start, range.start) < 0 ? range.start : start;
519
+ }
520
+ function focusEvent(query, options = {}) {
521
+ const event = context.event(query);
522
+ const date = options.date === void 0 ? firstShownDate(event) : toPlainDate(options.date);
523
+ return focusThrough(withResource({
524
+ date,
525
+ eventId: event.id,
526
+ kind: "event"
527
+ }, options.resourceId), (now) => now?.kind === "event" && now.eventId === event.id && now.date.equals(date) && (options.resourceId === void 0 || now.resourceId === options.resourceId), () => `focusable part of event ${JSON.stringify(event.id)} on ${date.toString()}${options.resourceId === void 0 ? "" : ` in resource ${JSON.stringify(options.resourceId)}`}`);
528
+ }
529
+ function focusCell(cell) {
530
+ const date = toPlainDate(cell.date);
531
+ const focus = withResource(cell.time === void 0 ? {
532
+ date,
533
+ kind: "day"
534
+ } : {
535
+ date,
536
+ kind: "slot",
537
+ time: Temporal.PlainTime.from(cell.time)
538
+ }, cell.resourceId);
539
+ return focusThrough(focus, (now) => now !== null && sameFocus(now, cell.resourceId === void 0 ? withResource(focus, now.resourceId ?? void 0) : focus), () => `cell for ${date.toString()}${cell.time === void 0 ? "" : ` at ${String(cell.time)}`}${cell.resourceId === void 0 ? "" : ` in resource ${JSON.stringify(cell.resourceId)}`}`);
540
+ }
541
+ return Object.freeze({
542
+ arrows,
543
+ cancel: () => press("Escape"),
544
+ async createEvent(cell, steps = {}) {
545
+ await focusCell(cell);
546
+ await press(" ");
547
+ await step(steps);
548
+ await press("Enter");
549
+ },
550
+ drop: () => press("Enter"),
551
+ focusCell,
552
+ focusEvent,
553
+ grab: () => press(" "),
554
+ grabEdge: () => press(" ", { shiftKey: true }),
555
+ async moveEvent(event, { date, resourceId, ...steps }) {
556
+ await focusEvent(event, {
557
+ date,
558
+ resourceId
559
+ });
560
+ await press(" ");
561
+ await step(steps);
562
+ await press("Enter");
563
+ },
564
+ press,
565
+ async resizeEvent(event, { date, edge = "end", resourceId, ...steps }) {
566
+ await focusEvent(event, {
567
+ date,
568
+ resourceId
569
+ });
570
+ await press(" ", { shiftKey: true });
571
+ if (edge === "start") await press(" ", { shiftKey: true });
572
+ await step(steps);
573
+ await press("Enter");
574
+ },
575
+ step
576
+ });
577
+ }
578
+ //#endregion
579
+ //#region src/placement.ts
580
+ function wall(instant, timeZone) {
581
+ return instant.toZonedDateTimeISO(timeZone).toPlainDateTime().toString({ smallestUnit: "minute" });
582
+ }
583
+ /** Summarizes where a normalized event shows. */
584
+ function summarizePlacement(event, timeZone) {
585
+ const start = event.start.toString();
586
+ const end = event.end.toString();
587
+ const range = `${start}/${end}`;
588
+ return Object.freeze({
589
+ end,
590
+ id: event.id,
591
+ isPending: event.isPending === true,
592
+ kind: event.kind,
593
+ range,
594
+ resourceIds: event.resourceIds,
595
+ start,
596
+ title: event.title,
597
+ wallRange: event.kind === "timed" ? `${wall(event.start, timeZone)}/${wall(event.end, timeZone)}` : range
598
+ });
599
+ }
600
+ //#endregion
601
+ //#region src/pointer.ts
602
+ /** Thrown where pointer drivers need a layout the environment doesn't have, as in jsdom. */
603
+ var PointerLayoutError = class extends Error {
604
+ constructor(what) {
605
+ super(`${what} has no size, so there's nowhere to point. jsdom and happy-dom don't lay pages out: run pointer tests in a browser, such as Vitest's browser mode, and use the keyboard driver elsewhere.`);
606
+ this.name = "PointerLayoutError";
607
+ }
608
+ };
609
+ const minute = 1 / 1440;
610
+ function boxOf(element, what) {
611
+ const box = element.getBoundingClientRect();
612
+ if (box.width <= 0 || box.height <= 0) throw new PointerLayoutError(what);
613
+ return box;
614
+ }
615
+ function middle(box) {
616
+ return {
617
+ x: box.left + box.width / 2,
618
+ y: box.top + box.height / 2
619
+ };
620
+ }
621
+ function toPoint(target, what) {
622
+ return "getBoundingClientRect" in target ? middle(boxOf(target, what)) : target;
623
+ }
624
+ /** How far through its day a wall time is: `0` at midnight, `1` at the next. */
625
+ function dayFraction(time) {
626
+ return (time.hour * 60 + time.minute + time.second / 60) / 1440;
627
+ }
628
+ function isInline(column) {
629
+ return column.getAttribute("data-axis") === "inline";
630
+ }
631
+ function isRightToLeft(column) {
632
+ return column.closest("[dir]")?.getAttribute("dir") === "rtl";
633
+ }
634
+ /** The point at `fraction` of a time column's day, across its middle. */
635
+ function alongColumn(column, fraction) {
636
+ const box = boxOf(column, "The time column");
637
+ if (!isInline(column)) return {
638
+ x: box.left + box.width / 2,
639
+ y: box.top + fraction * box.height
640
+ };
641
+ return {
642
+ x: isRightToLeft(column) ? box.right - fraction * box.width : box.left + fraction * box.width,
643
+ y: box.top + box.height / 2
644
+ };
645
+ }
646
+ /** How far through its day a point in a time column is. */
647
+ function fractionAt(column, point) {
648
+ const box = boxOf(column, "The time column");
649
+ if (!isInline(column)) return (point.y - box.top) / box.height;
650
+ return (isRightToLeft(column) ? box.right - point.x : point.x - box.left) / box.width;
651
+ }
652
+ function plus(point, from, to) {
653
+ return {
654
+ x: point.x + to.x - from.x,
655
+ y: point.y + to.y - from.y
656
+ };
657
+ }
658
+ const nextFrame = () => new Promise((resolve) => {
659
+ if (typeof requestAnimationFrame === "function") requestAnimationFrame(() => resolve());
660
+ else setTimeout(resolve, 16);
661
+ });
662
+ function createPointerDriver(context) {
663
+ const { container } = context;
664
+ function send(target, type, point, pointerType) {
665
+ target.dispatchEvent(new PointerEvent(type, {
666
+ bubbles: true,
667
+ button: type === "pointermove" ? -1 : 0,
668
+ buttons: type === "pointerup" ? 0 : 1,
669
+ cancelable: true,
670
+ clientX: point.x,
671
+ clientY: point.y,
672
+ composed: true,
673
+ isPrimary: true,
674
+ pointerId: pointerType === "mouse" ? 1 : 2,
675
+ pointerType
676
+ }));
677
+ }
678
+ /** Waits until the region under `element` says a drag runs (`data-interaction`). */
679
+ async function started(element, timeout) {
680
+ const deadline = realNow() + timeout;
681
+ while (element.closest("[data-interaction]") === null) {
682
+ if (realNow() > deadline) throw new Error(`The long press didn't start a drag within ${timeout} ms.`);
683
+ await act(nextFrame);
684
+ }
685
+ }
686
+ /**
687
+ * Presses at `from`, moves toward `to` in steps and lets go there. `to` is measured again after
688
+ * each frame, so a view that scrolls under the pointer, as auto-scroll at an edge does, still
689
+ * gets the release where `to` is then.
690
+ */
691
+ async function dragTo(from, to, pressed, options) {
692
+ const { pointerType = "mouse", steps = 4, timeout = 2e3 } = options;
693
+ const target = document.elementFromPoint(from.x, from.y) ?? pressed;
694
+ await act(async () => send(target, "pointerdown", from, pointerType));
695
+ if (pointerType === "touch") await started(target, timeout);
696
+ let point = from;
697
+ for (let index = 1; index <= steps; index += 1) {
698
+ const end = to();
699
+ point = {
700
+ x: from.x + (end.x - from.x) * index / steps,
701
+ y: from.y + (end.y - from.y) * index / steps
702
+ };
703
+ await act(async () => send(target, "pointermove", point, pointerType));
704
+ await act(nextFrame);
705
+ }
706
+ for (let index = 0; index < 5; index += 1) {
707
+ const end = to();
708
+ if (Math.abs(end.x - point.x) < .5 && Math.abs(end.y - point.y) < .5) break;
709
+ point = end;
710
+ await act(async () => send(target, "pointermove", point, pointerType));
711
+ await act(nextFrame);
712
+ }
713
+ await act(async () => send(target, "pointerup", point, pointerType));
714
+ }
715
+ async function drag(from, to, options = {}) {
716
+ const start = toPoint(from, "The element to drag from");
717
+ toPoint(to, "The element to drag to");
718
+ await dragTo(start, () => toPoint(to, "The element to drag to"), "getBoundingClientRect" in from ? from : container, options);
719
+ }
720
+ function shown(id) {
721
+ const elements = eventElements(container, id);
722
+ if (elements.length === 0) throw new CalendarQueryError(`The view shows no element for event ${JSON.stringify(id)}.`);
723
+ return elements;
724
+ }
725
+ /** Scrolls `element` into view and returns its middle, which must be on top there. */
726
+ function pressPoint(element, what) {
727
+ boxOf(element, what);
728
+ element.scrollIntoView({
729
+ block: "nearest",
730
+ inline: "nearest"
731
+ });
732
+ const point = middle(boxOf(element, what));
733
+ const hit = document.elementFromPoint(point.x, point.y);
734
+ if (hit === null || !element.contains(hit)) throw new CalendarQueryError(`${what}'s middle is covered or off screen${hit === null ? "" : ` (by ${hit.tagName.toLowerCase()})`}: make the calendar taller, or scroll it first.`);
735
+ return point;
736
+ }
737
+ /** Checks a drop point lands on `cell`, as the pointer layer's hit test would find it. */
738
+ function assertLands(point, cell, what) {
739
+ for (const element of document.elementsFromPoint(point.x, point.y)) {
740
+ if (element.closest("[data-occludes]") !== null) break;
741
+ const found = element.closest("[data-date]");
742
+ if (found === null) continue;
743
+ if (found === cell) return;
744
+ break;
745
+ }
746
+ throw new CalendarQueryError(`The drop point for ${what} is off screen or covered: make the calendar taller, or scroll it there first.`);
747
+ }
748
+ function columnFor(cell, date = toPlainDate(cell.date)) {
749
+ const found = timeColumn(container, date, cell.resourceId);
750
+ if (found === null) throw new CalendarQueryError(`The view shows no time column for ${date.toString()}.`);
751
+ return found;
752
+ }
753
+ function dayFor(cell, date = toPlainDate(cell.date)) {
754
+ const found = dayCell(container, date, cell.resourceId);
755
+ if (found === null) throw new CalendarQueryError(`The view shows no day cell for ${date.toString()}.`);
756
+ return found;
757
+ }
758
+ /**
759
+ * A point just past an event's start, along its time column's axis, below or beside its start
760
+ * handle, which would resize instead.
761
+ */
762
+ function nearStart(element, column) {
763
+ const box = boxOf(element, "The event");
764
+ const handle = element.querySelector("[data-resize=\"start\"]")?.getBoundingClientRect();
765
+ let point;
766
+ if (!isInline(column)) point = {
767
+ x: box.left + box.width / 2,
768
+ y: (handle?.bottom ?? box.top) + 2
769
+ };
770
+ else if (isRightToLeft(column)) point = {
771
+ x: (handle?.left ?? box.right) - 2,
772
+ y: box.top + box.height / 2
773
+ };
774
+ else point = {
775
+ x: (handle?.right ?? box.left) + 2,
776
+ y: box.top + box.height / 2
777
+ };
778
+ const hit = document.elementFromPoint(point.x, point.y);
779
+ if (hit === null || !element.contains(hit) || hit.closest("[data-resize]") !== null) throw new CalendarQueryError("The event is too short to press past its start: move it a shorter way, or make it taller.");
780
+ return point;
781
+ }
782
+ /** The `data-date` cell under a point, beneath anything inside `inside`. */
783
+ function cellAt(point, inside) {
784
+ const cell = document.elementsFromPoint(point.x, point.y).find((element) => element instanceof HTMLElement && element.hasAttribute("data-date") && !inside.contains(element));
785
+ if (cell === void 0) throw new CalendarQueryError("No day or time cell is under the press.");
786
+ return cell;
787
+ }
788
+ /**
789
+ * Whether a cell runs through a day's hours: a timeline's strip, or a time grid's column,
790
+ * which holds its events, while a month's day and an all-day cell sit beside theirs.
791
+ */
792
+ function isTimeColumn(cell, event) {
793
+ return !cell.hasAttribute("data-all-day") && (isInline(cell) || cell.contains(event));
794
+ }
795
+ function dateOf(value) {
796
+ if (value instanceof Temporal.Instant) return value.toZonedDateTimeISO(context.timeZone()).toPlainDate();
797
+ return Temporal.PlainDate.from(value);
798
+ }
799
+ function wallTime(value) {
800
+ if (value instanceof Temporal.Instant) return value.toZonedDateTimeISO(context.timeZone()).toPlainTime();
801
+ return value instanceof Temporal.PlainDateTime ? value.toPlainTime() : Temporal.PlainTime.from("00:00");
802
+ }
803
+ /** The point `total` days into `to`'s date, a fraction carrying the time, in its time column. */
804
+ function inColumn(to, total) {
805
+ const days = Math.floor(total);
806
+ const column = columnFor(to, toPlainDate(to.date).add({ days }));
807
+ return {
808
+ column,
809
+ point: () => alongColumn(column, total - days)
810
+ };
811
+ }
812
+ /**
813
+ * Where a press in day cell `from` lands in the cell for `date`, in `to`'s resource: as far
814
+ * into that cell as the press is into `from`.
815
+ */
816
+ function onDay(grab, from, to, date) {
817
+ const cell = dayFor(to, date);
818
+ const fromMiddle = middle(boxOf(from, "The day under the press"));
819
+ return {
820
+ cell,
821
+ point: () => plus(grab, fromMiddle, middle(boxOf(cell, "The target day")))
822
+ };
823
+ }
824
+ /** `to` in the resource the press is in, unless it names one. */
825
+ function inPressedResource(to, from) {
826
+ if (to.resourceId !== void 0) return to;
827
+ const resourceId = resourceIdOf(from);
828
+ return resourceId === void 0 ? to : {
829
+ ...to,
830
+ resourceId
831
+ };
832
+ }
833
+ /** Checks the drop lands where it should, then drags there from `grab`. */
834
+ async function dropAt(grab, target, pressed, what, options = {}) {
835
+ assertLands(target.point(), target.cell ?? target.column, what);
836
+ await dragTo(grab, target.point, pressed, options);
837
+ }
838
+ return Object.freeze({
839
+ async createEvent(from, to, options) {
840
+ if (from.time === void 0 || to.time === void 0) {
841
+ const first = dayFor(from);
842
+ const last = dayFor(to);
843
+ const start = middle(boxOf(first, "The first day"));
844
+ assertLands(start, first, "the create's start");
845
+ await dropAt(start, {
846
+ cell: last,
847
+ point: () => middle(boxOf(last, "The last day"))
848
+ }, first, "the create's end", options);
849
+ return;
850
+ }
851
+ const firstColumn = columnFor(from);
852
+ const lastColumn = columnFor(to);
853
+ const start = alongColumn(firstColumn, dayFraction(Temporal.PlainTime.from(from.time)) + minute);
854
+ const end = dayFraction(Temporal.PlainTime.from(to.time)) + minute;
855
+ assertLands(start, firstColumn, "the create's start");
856
+ await dropAt(start, {
857
+ column: lastColumn,
858
+ point: () => alongColumn(lastColumn, end)
859
+ }, firstColumn, "the create's end", options);
860
+ },
861
+ drag,
862
+ async moveEvent(query, target, options) {
863
+ const event = context.event(query);
864
+ const element = shown(event.id)[0];
865
+ const grab = pressPoint(element, "The event");
866
+ const from = cellAt(grab, element);
867
+ const to = inPressedResource(target, from);
868
+ const pressed = toPlainDate(from.getAttribute("data-date"));
869
+ const daysIn = dateOf(event.start).until(pressed).days;
870
+ if (isTimeColumn(from, element)) {
871
+ const start = dayFraction(wallTime(event.start));
872
+ const at = to.time === void 0 ? start : dayFraction(Temporal.PlainTime.from(to.time));
873
+ let press = grab;
874
+ let into = daysIn + fractionAt(from, grab) - start;
875
+ if (Math.floor(at + into) !== Math.floor(at)) {
876
+ press = nearStart(element, from);
877
+ into = daysIn + fractionAt(from, press) - start;
878
+ }
879
+ await dropAt(press, inColumn(to, at + into), element, "the event", options);
880
+ return;
881
+ }
882
+ if (to.time !== void 0 && !from.hasAttribute("data-all-day")) throw new CalendarQueryError("This view has no times to drop on: move the event by its date alone.");
883
+ if (to.time !== void 0) {
884
+ const column = columnFor(to);
885
+ const at = dayFraction(Temporal.PlainTime.from(to.time)) + minute / 2;
886
+ await dropAt(grab, {
887
+ column,
888
+ point: () => alongColumn(column, at)
889
+ }, element, "the event", options);
890
+ return;
891
+ }
892
+ await dropAt(grab, onDay(grab, from, to, toPlainDate(to.date).add({ days: daysIn })), element, "the event", options);
893
+ },
894
+ async resizeEvent(query, target, options) {
895
+ const { edge = "end" } = target;
896
+ const event = context.event(query);
897
+ const elements = shown(event.id);
898
+ const handles = elements.flatMap((element) => [...element.querySelectorAll(`[data-resize="${edge}"]`)]);
899
+ const handle = edge === "end" ? handles.at(-1) : handles[0];
900
+ if (handle === void 0) throw new CalendarQueryError(`The event has no ${edge} handle: is the calendar read-only, or does the view not resize this event?`);
901
+ const element = elements.find((candidate) => candidate.contains(handle));
902
+ const grab = pressPoint(handle, "The resize handle");
903
+ const from = cellAt(grab, element);
904
+ const to = inPressedResource(target, from);
905
+ const pressed = toPlainDate(from.getAttribute("data-date"));
906
+ const edgeValue = edge === "end" ? event.end : event.start;
907
+ if (isTimeColumn(from, element) && to.time === void 0) throw new CalendarQueryError(`This view resizes by time: give the ${edge} a \`time\` as well as a date.`);
908
+ if (isTimeColumn(from, element) && to.time !== void 0) {
909
+ const into = dateOf(edgeValue).until(pressed).days + fractionAt(from, grab) - dayFraction(wallTime(edgeValue));
910
+ await dropAt(grab, inColumn(to, dayFraction(Temporal.PlainTime.from(to.time)) + into), handle, "the edge", options);
911
+ return;
912
+ }
913
+ const endsOnTheDayBefore = event.kind === "all-day" || wallTime(edgeValue).equals(Temporal.PlainTime.from("00:00"));
914
+ const days = (edge === "end" && endsOnTheDayBefore ? dateOf(edgeValue).subtract({ days: 1 }) : dateOf(edgeValue)).until(toPlainDate(to.date)).days;
915
+ await dropAt(grab, onDay(grab, from, to, pressed.add({ days })), handle, "the edge", options);
916
+ }
917
+ });
918
+ }
919
+ //#endregion
920
+ //#region src/inspect.ts
921
+ /** A macrotask that fake timers don't hold back where `MessageChannel` exists. */
922
+ function tick() {
923
+ return new Promise((resolve) => {
924
+ if (typeof MessageChannel !== "function") {
925
+ setTimeout(resolve, 0);
926
+ return;
927
+ }
928
+ const channel = new MessageChannel();
929
+ channel.port1.onmessage = () => {
930
+ channel.port1.close();
931
+ resolve();
932
+ };
933
+ channel.port2.postMessage(null);
934
+ });
935
+ }
936
+ function createInspection(context) {
937
+ const { container } = context;
938
+ const spoken = recordAnnouncements(container);
939
+ const timeZone = () => context.meta().environment.timeZone;
940
+ const find = (query) => findEvent(context.meta().eventSnapshot, query, timeZone());
941
+ function getAllEvents(query) {
942
+ const { id } = find(query);
943
+ const elements = eventElements(container, id);
944
+ if (elements.length === 0) throw new CalendarQueryError(`The view doesn't show event ${JSON.stringify(id)}.`);
945
+ return elements;
946
+ }
947
+ function resourceId(query) {
948
+ if (query === null || typeof query !== "object") return query;
949
+ const match = context.meta().resources.filter((resource) => resource?.title === query.title);
950
+ if (match.length !== 1) throw new CalendarQueryError(`${match.length === 0 ? "No" : match.length} resources are titled ${JSON.stringify(query.title)}.`);
951
+ return match[0].id;
952
+ }
953
+ const keyboard = createKeyboardDriver({
954
+ container,
955
+ direction: () => context.meta().environment.direction,
956
+ event: find,
957
+ focus: context.focus,
958
+ setFocus: context.setFocus,
959
+ timeZone,
960
+ visibleRange: context.visibleRange
961
+ });
962
+ const pointer = createPointerDriver({
963
+ container,
964
+ event: find,
965
+ timeZone
966
+ });
967
+ return Object.freeze({
968
+ announcements: () => spoken.all(),
969
+ dispose: () => spoken.stop(),
970
+ getAllEvents,
971
+ getDayCell(date, options = {}) {
972
+ const cell = dayCell(container, date, options.resourceId);
973
+ if (cell === null) throw new CalendarQueryError(`The view shows no day cell for ${String(date)}.`);
974
+ return cell;
975
+ },
976
+ getEvent: (query) => getAllEvents(query)[0],
977
+ getResource(query) {
978
+ const id = resourceId(query);
979
+ const elements = resourceElements(container, id);
980
+ const element = elements.find((candidate) => candidate.querySelector("[data-date]:not([data-all-day])")) ?? elements[0];
981
+ if (element === void 0) throw new CalendarQueryError(`The view doesn't show resource ${JSON.stringify(id)}.`);
982
+ return element;
983
+ },
984
+ getTimeColumn(date, options = {}) {
985
+ const column = timeColumn(container, date, options.resourceId);
986
+ if (column === null) throw new CalendarQueryError(`The view shows no time column for ${String(date)}.`);
987
+ return column;
988
+ },
989
+ keyboard,
990
+ lastAnnouncement: () => spoken.current(),
991
+ placementOf: (query) => summarizePlacement(find(query), timeZone()),
992
+ pointer,
993
+ queryEvent(query) {
994
+ const found = findEvents(context.meta().eventSnapshot, query, timeZone());
995
+ const event = found.length > 1 ? find(query) : found[0];
996
+ return event === void 0 ? null : eventElements(container, event.id)[0] ?? null;
997
+ },
998
+ async settled({ timeout = 5e3 } = {}) {
999
+ context.ensureMounted();
1000
+ const started = realNow();
1001
+ for (;;) {
1002
+ await act(tick);
1003
+ if (context.pending().size === 0) break;
1004
+ if (realNow() - started > timeout) {
1005
+ const pending = [...context.pending().values()].map(({ change, phase }) => `${change.cause} ${change.eventId === null ? "new" : JSON.stringify(change.eventId)} (${phase})`).join(", ");
1006
+ throw new Error(`Changes were still pending after ${timeout} ms: ${pending}.`);
1007
+ }
1008
+ }
1009
+ await act(tick);
1010
+ }
1011
+ });
1012
+ }
1013
+ //#endregion
1014
+ //#region src/harness.ts
1015
+ /** React's flag for test environments, which tells it to expect `act`. */
1016
+ const reactGlobals = globalThis;
1017
+ /** Thrown when a client render doesn't match the server's markup. */
1018
+ var HydrationMismatchError = class extends Error {
1019
+ /** What React reported: recoverable errors and hydration warnings. */
1020
+ errors;
1021
+ serverMarkup;
1022
+ constructor(errors, serverMarkup) {
1023
+ const reasons = errors.map((error) => error instanceof Error ? error.message : String(error).split("\n")[0]);
1024
+ super(`Hydration didn't match the server's markup:\n- ${reasons.join("\n- ")}`);
1025
+ this.name = "HydrationMismatchError";
1026
+ this.errors = errors;
1027
+ this.serverMarkup = serverMarkup;
1028
+ }
1029
+ };
1030
+ const mounted = /* @__PURE__ */ new Set();
1031
+ /** Unmounts every calendar the harness rendered and removes the containers it made. */
1032
+ async function cleanup() {
1033
+ for (const harness of mounted) await harness.unmount();
1034
+ }
1035
+ /** A tiny external store, so the calendar re-renders when the harness changes its inputs. */
1036
+ function createCell(initial) {
1037
+ let value = initial;
1038
+ const listeners = /* @__PURE__ */ new Set();
1039
+ const get = () => value;
1040
+ const set = (next) => {
1041
+ value = next;
1042
+ for (const listener of listeners) listener();
1043
+ };
1044
+ const subscribe = (listener) => {
1045
+ listeners.add(listener);
1046
+ return () => {
1047
+ listeners.delete(listener);
1048
+ };
1049
+ };
1050
+ return {
1051
+ get,
1052
+ set,
1053
+ subscribe
1054
+ };
1055
+ }
1056
+ function isThenable(value) {
1057
+ return typeof value === "object" && value !== null && typeof value.then === "function";
1058
+ }
1059
+ function setUp(Calendar, initialOptions) {
1060
+ reactGlobals.IS_REACT_ACT_ENVIRONMENT ??= true;
1061
+ const environment = initialOptions.environment ?? createTestEnvironment();
1062
+ const initialEvents = initialOptions.events ?? [];
1063
+ const options = createCell(initialOptions);
1064
+ const events = createCell(initialEvents);
1065
+ const now = createCell(environment.now);
1066
+ const changes = [];
1067
+ const results = [];
1068
+ let diagnostics = [];
1069
+ let observed;
1070
+ function apply(change) {
1071
+ const { applyChange, createEvent } = options.get();
1072
+ events.set(applyChange === void 0 ? applyCanonicalChange(events.get(), change, { createEvent }) : applyChange(events.get(), change));
1073
+ }
1074
+ const onEventChange = (change) => {
1075
+ changes.push(change);
1076
+ const outcome = options.get().onEventChange?.(change);
1077
+ if (isThenable(outcome)) return Promise.resolve(outcome).then(() => apply(change));
1078
+ apply(change);
1079
+ };
1080
+ const onEventChangeResult = (result, detail) => {
1081
+ results.push(Object.freeze({
1082
+ detail,
1083
+ result
1084
+ }));
1085
+ options.get().onEventChangeResult?.(result, detail);
1086
+ };
1087
+ const onDiagnosticsChange = (next) => {
1088
+ diagnostics = next;
1089
+ options.get().rootProps?.onDiagnosticsChange?.(next);
1090
+ };
1091
+ /** Reads what the calendar shows, from inside `Root`, after each commit. */
1092
+ function Observer() {
1093
+ const context = Calendar.useCalendar();
1094
+ const pending = Calendar.useCalendarPendingChanges();
1095
+ const visibleRange = Calendar.useVisibleRange();
1096
+ useLayoutEffect(() => {
1097
+ observed = {
1098
+ context,
1099
+ pending,
1100
+ visibleRange
1101
+ };
1102
+ });
1103
+ return null;
1104
+ }
1105
+ function Harness() {
1106
+ const current = useSyncExternalStore(options.subscribe, options.get, options.get);
1107
+ const shown = useSyncExternalStore(events.subscribe, events.get, () => initialEvents);
1108
+ const instant = useSyncExternalStore(now.subscribe, now.get, now.get);
1109
+ const { children, clock, messages, readOnly, resources, rootProps, view } = current;
1110
+ const { now: _now, ...fixed } = environment.rootProps;
1111
+ const props = {
1112
+ ...fixed,
1113
+ defaultView: view ?? Calendar.views[0]?.name,
1114
+ ...resources === void 0 ? {} : { resources },
1115
+ ...clock === void 0 ? { now: instant } : { clock },
1116
+ ...rootProps,
1117
+ events: shown,
1118
+ onDiagnosticsChange,
1119
+ onEventChangeResult,
1120
+ ...readOnly ? {} : { onEventChange }
1121
+ };
1122
+ return createElement(Calendar.Root, props, createElement(Observer), children ?? createElement(Calendar.ActiveView), messages === void 0 ? null : createElement(Calendar.Announcer, { messages }));
1123
+ }
1124
+ function element() {
1125
+ const { strictMode, wrapper } = options.get();
1126
+ const harness = createElement(Harness);
1127
+ const wrapped = wrapper === void 0 ? harness : createElement(wrapper, null, harness);
1128
+ return strictMode ? createElement(StrictMode, null, wrapped) : wrapped;
1129
+ }
1130
+ function seen() {
1131
+ if (observed === void 0) throw new Error("The calendar hasn't rendered yet.");
1132
+ return observed;
1133
+ }
1134
+ function harness(container, root, recoverableErrors, ownsContainer) {
1135
+ let active = true;
1136
+ const ensureMounted = () => {
1137
+ if (!active) throw new Error("The calendar was unmounted.");
1138
+ };
1139
+ const inspection = createInspection({
1140
+ container,
1141
+ ensureMounted,
1142
+ focus: () => seen().context.state.focus,
1143
+ meta: () => seen().context.meta,
1144
+ pending: () => seen().pending,
1145
+ setFocus: (focus) => seen().context.actions.setFocus(focus),
1146
+ visibleRange: () => seen().visibleRange
1147
+ });
1148
+ const entry = { async unmount() {
1149
+ if (!active) return;
1150
+ active = false;
1151
+ inspection.dispose();
1152
+ mounted.delete(entry);
1153
+ await act(async () => root.unmount());
1154
+ if (ownsContainer) container.remove();
1155
+ } };
1156
+ mounted.add(entry);
1157
+ const { dispose: _dispose, ...inspect } = inspection;
1158
+ return Object.freeze({
1159
+ ...inspect,
1160
+ get actions() {
1161
+ return seen().context.actions;
1162
+ },
1163
+ async act(callback) {
1164
+ ensureMounted();
1165
+ let value;
1166
+ await act(async () => {
1167
+ value = await callback(seen().context.actions);
1168
+ });
1169
+ return value;
1170
+ },
1171
+ changes,
1172
+ container,
1173
+ get diagnostics() {
1174
+ return diagnostics;
1175
+ },
1176
+ environment,
1177
+ events: () => events.get(),
1178
+ meta: () => seen().context.meta,
1179
+ pendingChanges: () => seen().pending,
1180
+ async propose(proposal, detail) {
1181
+ ensureMounted();
1182
+ let result;
1183
+ await act(async () => {
1184
+ result = await seen().context.actions.proposeEventChange(proposal, detail);
1185
+ });
1186
+ return result;
1187
+ },
1188
+ recoverableErrors,
1189
+ async rerender(next) {
1190
+ ensureMounted();
1191
+ await act(async () => {
1192
+ if (next.events !== void 0) events.set(next.events);
1193
+ options.set({
1194
+ ...options.get(),
1195
+ ...next
1196
+ });
1197
+ });
1198
+ },
1199
+ results,
1200
+ async setEvents(next) {
1201
+ ensureMounted();
1202
+ await act(async () => events.set(next));
1203
+ },
1204
+ async setNow(next) {
1205
+ ensureMounted();
1206
+ if (options.get().clock !== void 0) throw new Error("This calendar reads a clock: move the clock instead of calling setNow.");
1207
+ const { timeZone } = environment;
1208
+ const instant = typeof next === "string" && /^\d{2}:\d{2}/u.test(next.trim()) ? now.get().toZonedDateTimeISO(timeZone).toPlainDate().toPlainDateTime(Temporal.PlainTime.from(next)).toZonedDateTime(timeZone).toInstant() : toInstant(next, timeZone);
1209
+ await act(async () => now.set(instant));
1210
+ },
1211
+ state: () => seen().context.state,
1212
+ unmount: () => entry.unmount()
1213
+ });
1214
+ }
1215
+ return {
1216
+ element,
1217
+ harness
1218
+ };
1219
+ }
1220
+ function containerFor(options) {
1221
+ if (options.container !== void 0) return {
1222
+ container: options.container,
1223
+ owns: false
1224
+ };
1225
+ const container = document.createElement("div");
1226
+ document.body.append(container);
1227
+ return {
1228
+ container,
1229
+ owns: true
1230
+ };
1231
+ }
1232
+ /**
1233
+ * Renders `Calendar.Root` with a deterministic environment and controlled events, inside `act`.
1234
+ * Saved changes are applied to the events; every change and result is recorded. Unmount it with
1235
+ * `unmount()`, or every one at once with `cleanup()` after each test.
1236
+ */
1237
+ async function renderCalendar(Calendar, options = {}) {
1238
+ const { element, harness } = setUp(Calendar, options);
1239
+ const { container, owns } = containerFor(options);
1240
+ const recoverableErrors = [];
1241
+ const root = createRoot(container, {
1242
+ identifierPrefix: options.identifierPrefix,
1243
+ onRecoverableError: (error) => recoverableErrors.push(error)
1244
+ });
1245
+ const rendered = harness(container, root, recoverableErrors, owns);
1246
+ await act(async () => root.render(element()));
1247
+ return rendered;
1248
+ }
1249
+ /** Whether a console message is one of React's hydration warnings. */
1250
+ function isHydrationWarning(args) {
1251
+ return args.some((arg) => typeof arg === "string" && /hydrat/iu.test(arg));
1252
+ }
1253
+ /**
1254
+ * Renders the calendar with `renderToString`, puts that markup in a container and hydrates it,
1255
+ * as a server-rendered page does. Throws a `HydrationMismatchError` when React reports a
1256
+ * mismatch: a recoverable error, or a hydration warning such as a differing attribute, which
1257
+ * React only logs. The console is watched while hydration runs, then restored; any `console.error`
1258
+ * then that mentions hydration counts. React's development build logs those warnings and its
1259
+ * production build doesn't, so test with the development build. The server render runs in the
1260
+ * test's own environment, so code that checks for `window` takes its browser branch there too.
1261
+ */
1262
+ async function hydrateCalendar(Calendar, options = {}) {
1263
+ const { element, harness } = setUp(Calendar, options);
1264
+ const serverMarkup = renderToString(element(), { identifierPrefix: options.identifierPrefix });
1265
+ const { container, owns } = containerFor(options);
1266
+ container.innerHTML = serverMarkup;
1267
+ const problems = [];
1268
+ const recoverableErrors = [];
1269
+ const consoleError = console.error;
1270
+ let root;
1271
+ console.error = (...args) => {
1272
+ if (isHydrationWarning(args)) problems.push(args.map(String).join(" "));
1273
+ consoleError.apply(console, args);
1274
+ };
1275
+ try {
1276
+ await act(async () => {
1277
+ root = hydrateRoot(container, element(), {
1278
+ identifierPrefix: options.identifierPrefix,
1279
+ onRecoverableError: (error) => {
1280
+ recoverableErrors.push(error);
1281
+ problems.push(error);
1282
+ }
1283
+ });
1284
+ });
1285
+ } catch (error) {
1286
+ try {
1287
+ await act(async () => root?.unmount());
1288
+ } catch {}
1289
+ if (owns) container.remove();
1290
+ throw error;
1291
+ } finally {
1292
+ console.error = consoleError;
1293
+ }
1294
+ const hydrated = harness(container, root, recoverableErrors, owns);
1295
+ if (problems.length > 0) {
1296
+ await hydrated.unmount();
1297
+ throw new HydrationMismatchError(problems, serverMarkup);
1298
+ }
1299
+ return Object.freeze(Object.defineProperties({ serverMarkup }, Object.getOwnPropertyDescriptors(hydrated)));
1300
+ }
1301
+ //#endregion
1302
+ //#region src/fixtures.ts
1303
+ const sequence = (count) => Array.from({ length: count }, (_, index) => index);
1304
+ /**
1305
+ * Thursday 8 October 2026 in UTC, as busy as a day gets: 30 timed events and 3 all-day ones.
1306
+ *
1307
+ * - `b1`–`b8` ("Back-to-back"): half hours from 08:00 to 12:00 whose ends touch, overlapping none.
1308
+ * - `l1` ("Long"): 12:00–18:00, under everything from noon to six.
1309
+ * - `m1`–`m3` ("Lunch"): 12:00–13:00; with `l1`, four at once.
1310
+ * - `s1`–`s4` ("Stack"): from 13:00, 60, 45, 90 and 30 minutes long; with `l1`, five at once.
1311
+ * - `c1`–`c8` ("Staircase"): 45 minutes each, from 15:00 every 15 minutes, each overlapping the two
1312
+ * before it, and `l1`.
1313
+ * - `q1`–`q3` ("Short"): 5, 10 and 15 minutes, at 18:00, 18:15 and 18:30.
1314
+ * - `n1` ("Overnight", 22:30–00:30 the next day) under `e1` ("Late", 23:45–24:00), and `n2`
1315
+ * ("Overnight", from 23:00 the day before to 01:00).
1316
+ * - `a1` "Holiday" and `a2` "On call" on the day, `a3` "Conference week" from Monday 5 to Sunday
1317
+ * 11 October ("All day").
1318
+ *
1319
+ * For overlap layouts, "+N more", lists and performance budgets.
1320
+ */
1321
+ function denseDayFixture() {
1322
+ requireTemporal();
1323
+ const environment = createTestEnvironment({ now: "2026-10-08T12:00:00Z" });
1324
+ const at = (time) => `2026-10-08T${time}Z`;
1325
+ const timed = (id, start, minutes, group) => buildEvent({
1326
+ data: { group },
1327
+ duration: { minutes },
1328
+ id,
1329
+ start,
1330
+ title: `${group} ${id}`
1331
+ });
1332
+ const clock = (minutes) => Temporal.PlainTime.from("00:00").add({ minutes }).toString({ smallestUnit: "minute" });
1333
+ const events = [
1334
+ ...sequence(8).map((index) => timed(`b${index + 1}`, at(clock(480 + index * 30)), 30, "Back-to-back")),
1335
+ timed("l1", at("12:00"), 360, "Long"),
1336
+ ...sequence(3).map((index) => timed(`m${index + 1}`, at("12:00"), 60, "Lunch")),
1337
+ ...[
1338
+ 60,
1339
+ 45,
1340
+ 90,
1341
+ 30
1342
+ ].map((minutes, index) => timed(`s${index + 1}`, at("13:00"), minutes, "Stack")),
1343
+ ...sequence(8).map((index) => timed(`c${index + 1}`, at(clock(900 + index * 15)), 45, "Staircase")),
1344
+ ...[
1345
+ 5,
1346
+ 10,
1347
+ 15
1348
+ ].map((minutes, index) => timed(`q${index + 1}`, at(clock(1080 + index * 15)), minutes, "Short")),
1349
+ timed("n1", at("22:30"), 120, "Overnight"),
1350
+ timed("e1", at("23:45"), 15, "Late"),
1351
+ buildEvent({
1352
+ data: { group: "Overnight" },
1353
+ end: at("01:00"),
1354
+ id: "n2",
1355
+ start: "2026-10-07T23:00:00Z",
1356
+ title: "Overnight n2"
1357
+ }),
1358
+ buildAllDayEvent({
1359
+ data: { group: "All day" },
1360
+ id: "a1",
1361
+ start: "2026-10-08",
1362
+ title: "Holiday"
1363
+ }),
1364
+ buildAllDayEvent({
1365
+ data: { group: "All day" },
1366
+ id: "a2",
1367
+ start: "2026-10-08",
1368
+ title: "On call"
1369
+ }),
1370
+ buildAllDayEvent({
1371
+ data: { group: "All day" },
1372
+ end: "2026-10-12",
1373
+ id: "a3",
1374
+ start: "2026-10-05",
1375
+ title: "Conference week"
1376
+ })
1377
+ ];
1378
+ return Object.freeze({
1379
+ environment,
1380
+ events: Object.freeze(events)
1381
+ });
1382
+ }
1383
+ /**
1384
+ * A week in New York, Monday to Sunday, with a DST change on the Sunday. The calendar opens on the
1385
+ * Monday at noon.
1386
+ *
1387
+ * - `d1`–`d7` ("Daily", "Standup <date>"): 09:00–09:30 every day, the same on the wall clock
1388
+ * before and after the change.
1389
+ * - `t1` ("Change", "In the changing hour"): in the fall, 30 minutes from the first 01:30, EDT,
1390
+ * to 01:00 EST, when the clocks go back (05:30Z–06:00Z); in the spring, 02:30, a time that
1391
+ * doesn't exist, so 03:30–04:00 EDT (07:30Z–08:00Z).
1392
+ * - `t2` ("Change", "Across the change"): 00:30–04:00 on the wall clock, 4½ hours in the fall and
1393
+ * 2½ in the spring.
1394
+ * - `a1` ("All day", "Weekend away"): Saturday to Monday.
1395
+ */
1396
+ function dstWeekFixture(options = {}) {
1397
+ requireTemporal();
1398
+ const { change = "fall" } = options;
1399
+ if (change !== "fall" && change !== "spring") throw new RangeError(`A DST week changes in the "fall" or the "spring", not ${JSON.stringify(change)}.`);
1400
+ const timeZone = "America/New_York";
1401
+ const sunday = Temporal.PlainDate.from(change === "fall" ? "2026-11-01" : "2026-03-08");
1402
+ const monday = sunday.subtract({ days: 6 });
1403
+ const environment = createTestEnvironment({
1404
+ anchorDate: monday,
1405
+ now: `${monday.toString()}T12:00`,
1406
+ timeZone
1407
+ });
1408
+ const events = [
1409
+ ...sequence(7).map((index) => {
1410
+ const date = monday.add({ days: index }).toString();
1411
+ return buildEvent({
1412
+ data: { group: "Daily" },
1413
+ duration: { minutes: 30 },
1414
+ id: `d${index + 1}`,
1415
+ start: `${date}T09:00`,
1416
+ timeZone,
1417
+ title: `Standup ${date}`
1418
+ });
1419
+ }),
1420
+ buildEvent({
1421
+ data: { group: "Change" },
1422
+ duration: { minutes: 30 },
1423
+ id: "t1",
1424
+ start: `${sunday.toString()}T${change === "fall" ? "01:30" : "02:30"}`,
1425
+ timeZone,
1426
+ title: "In the changing hour"
1427
+ }),
1428
+ buildEvent({
1429
+ data: { group: "Change" },
1430
+ end: `${sunday.toString()}T04:00`,
1431
+ id: "t2",
1432
+ start: `${sunday.toString()}T00:30`,
1433
+ timeZone,
1434
+ title: "Across the change"
1435
+ }),
1436
+ buildAllDayEvent({
1437
+ data: { group: "All day" },
1438
+ end: sunday.add({ days: 2 }),
1439
+ id: "a1",
1440
+ start: sunday.subtract({ days: 1 }),
1441
+ title: "Weekend away"
1442
+ })
1443
+ ];
1444
+ return Object.freeze({
1445
+ environment,
1446
+ events: Object.freeze(events)
1447
+ });
1448
+ }
1449
+ /**
1450
+ * Three series in three zones, for a calendar in UTC that opens on Monday 19 October 2026. Berlin's
1451
+ * clocks go back on 25 October and Los Angeles' on 1 November, so in the week of 26 October
1452
+ * Berlin's occurrences have moved an hour later in UTC and Los Angeles' haven't yet; each stays put
1453
+ * on its own wall clock. Tokyo has no DST.
1454
+ *
1455
+ * - `berlin-standup` ("Berlin", "Standup (Berlin)"): 09:00–09:15 in Berlin on weekdays, from
1456
+ * Monday 19 October.
1457
+ * - `la-review` ("Los Angeles", "Review (Los Angeles)"): 10:00–11:00 in Los Angeles every Tuesday,
1458
+ * from 20 October.
1459
+ * - `tokyo-check-in` ("Tokyo", "Check-in (Tokyo)"): 08:00–08:30 in Tokyo for ten days from Tuesday
1460
+ * 20 October, but not on the 24th; COUNT counts the skipped day, so nine occurrences.
1461
+ *
1462
+ * The masters are series, not events a calendar shows: expand them first.
1463
+ */
1464
+ function multiZoneSeriesFixture() {
1465
+ requireTemporal();
1466
+ const environment = createTestEnvironment({
1467
+ anchorDate: "2026-10-19",
1468
+ now: "2026-10-19T07:00:00Z"
1469
+ });
1470
+ const series = [
1471
+ buildRecurringEvent({
1472
+ data: { group: "Berlin" },
1473
+ duration: { minutes: 15 },
1474
+ id: "berlin-standup",
1475
+ rule: "FREQ=WEEKLY;BYDAY=MO,TU,WE,TH,FR",
1476
+ start: "2026-10-19T09:00",
1477
+ timeZone: "Europe/Berlin",
1478
+ title: "Standup (Berlin)"
1479
+ }),
1480
+ buildRecurringEvent({
1481
+ data: { group: "Los Angeles" },
1482
+ duration: { hours: 1 },
1483
+ id: "la-review",
1484
+ rule: "FREQ=WEEKLY;BYDAY=TU",
1485
+ start: "2026-10-20T10:00",
1486
+ timeZone: "America/Los_Angeles",
1487
+ title: "Review (Los Angeles)"
1488
+ }),
1489
+ buildRecurringEvent({
1490
+ data: { group: "Tokyo" },
1491
+ duration: { minutes: 30 },
1492
+ exceptionDates: ["2026-10-24"],
1493
+ id: "tokyo-check-in",
1494
+ rule: "FREQ=DAILY;COUNT=10",
1495
+ start: "2026-10-20T08:00",
1496
+ timeZone: "Asia/Tokyo",
1497
+ title: "Check-in (Tokyo)"
1498
+ })
1499
+ ];
1500
+ return Object.freeze({
1501
+ environment,
1502
+ series: Object.freeze(series)
1503
+ });
1504
+ }
1505
+ /**
1506
+ * Thursday 8 October 2026 for a team and two rooms, in UTC, with working hours from 09:00 to 18:00
1507
+ * on weekdays and the rooms' parent expanded.
1508
+ *
1509
+ * - Resources ("Team"): `ana` in Lisbon, `ben` in New York with his own hours, 08:00–16:00 there
1510
+ * (12:00–20:00 UTC), and `chen` in Shanghai. ("Rooms"): `rooms`, the parent of `orchid` and
1511
+ * `lotus`.
1512
+ * - `ana-1` "Design review" (Ana, 09:00–10:00), `ben-1` "Planning" (Ben, 14:00–16:00) and `chen-1`
1513
+ * "Early sync" (Chen, 02:00–02:30), all "Work".
1514
+ * - `meet-1` "Interview" (Ana and Orchid, 11:00–12:00) and `meet-2` "All hands" (Ben, Chen and
1515
+ * Lotus, 15:00–16:30), "Meeting".
1516
+ * - `open-1` "Unassigned task" (no resource, 10:00–11:00), and `leave-1` "Chen away" (Chen, all
1517
+ * day).
1518
+ */
1519
+ function resourceDayFixture() {
1520
+ requireTemporal();
1521
+ const environment = createTestEnvironment({ now: "2026-10-08T08:00:00Z" });
1522
+ const weekdays = [
1523
+ 1,
1524
+ 2,
1525
+ 3,
1526
+ 4,
1527
+ 5
1528
+ ];
1529
+ const team = { group: "Team" };
1530
+ const rooms = { group: "Rooms" };
1531
+ const resources = [
1532
+ buildResource({
1533
+ data: team,
1534
+ id: "ana",
1535
+ timeZone: "Europe/Lisbon",
1536
+ title: "Ana"
1537
+ }),
1538
+ buildResource({
1539
+ availability: buildAvailability({
1540
+ days: weekdays,
1541
+ hours: "08:00-16:00"
1542
+ }),
1543
+ data: team,
1544
+ id: "ben",
1545
+ timeZone: "America/New_York",
1546
+ title: "Ben"
1547
+ }),
1548
+ buildResource({
1549
+ data: team,
1550
+ id: "chen",
1551
+ timeZone: "Asia/Shanghai",
1552
+ title: "Chen"
1553
+ }),
1554
+ buildResource({
1555
+ data: rooms,
1556
+ id: "rooms",
1557
+ title: "Rooms"
1558
+ }),
1559
+ buildResource({
1560
+ data: rooms,
1561
+ id: "orchid",
1562
+ parentId: "rooms",
1563
+ title: "Orchid"
1564
+ }),
1565
+ buildResource({
1566
+ data: rooms,
1567
+ id: "lotus",
1568
+ parentId: "rooms",
1569
+ title: "Lotus"
1570
+ })
1571
+ ];
1572
+ const at = (time) => `2026-10-08T${time}Z`;
1573
+ const work = { group: "Work" };
1574
+ const meeting = { group: "Meeting" };
1575
+ const events = [
1576
+ buildEvent({
1577
+ data: work,
1578
+ id: "ana-1",
1579
+ resourceIds: ["ana"],
1580
+ start: at("09:00"),
1581
+ title: "Design review"
1582
+ }),
1583
+ buildEvent({
1584
+ data: work,
1585
+ duration: { hours: 2 },
1586
+ id: "ben-1",
1587
+ resourceIds: ["ben"],
1588
+ start: at("14:00"),
1589
+ title: "Planning"
1590
+ }),
1591
+ buildEvent({
1592
+ data: work,
1593
+ duration: { minutes: 30 },
1594
+ id: "chen-1",
1595
+ resourceIds: ["chen"],
1596
+ start: at("02:00"),
1597
+ title: "Early sync"
1598
+ }),
1599
+ buildEvent({
1600
+ data: meeting,
1601
+ id: "meet-1",
1602
+ resourceIds: ["ana", "orchid"],
1603
+ start: at("11:00"),
1604
+ title: "Interview"
1605
+ }),
1606
+ buildEvent({
1607
+ data: meeting,
1608
+ duration: { minutes: 90 },
1609
+ id: "meet-2",
1610
+ resourceIds: [
1611
+ "ben",
1612
+ "chen",
1613
+ "lotus"
1614
+ ],
1615
+ start: at("15:00"),
1616
+ title: "All hands"
1617
+ }),
1618
+ buildEvent({
1619
+ data: { group: "Unassigned" },
1620
+ id: "open-1",
1621
+ start: at("10:00"),
1622
+ title: "Unassigned task"
1623
+ }),
1624
+ buildAllDayEvent({
1625
+ data: { group: "Leave" },
1626
+ id: "leave-1",
1627
+ resourceIds: ["chen"],
1628
+ start: "2026-10-08",
1629
+ title: "Chen away"
1630
+ })
1631
+ ];
1632
+ return Object.freeze({
1633
+ environment,
1634
+ events: Object.freeze(events),
1635
+ resources: Object.freeze(resources),
1636
+ rootProps: Object.freeze({
1637
+ availability: buildAvailability({ hours: "09:00-18:00" }),
1638
+ defaultExpandedResourceIds: Object.freeze(["rooms"])
1639
+ })
1640
+ });
1641
+ }
1642
+ //#endregion
1643
+ export { CalendarQueryError, HydrationMismatchError, PointerLayoutError, applyCanonicalChange, buildAllDayEvent, buildAvailability, buildEvent, buildRecurringEvent, buildResource, cleanup, createTestClock, createTestEnvironment, denseDayFixture, dstWeekFixture, hydrateCalendar, multiZoneSeriesFixture, normalizeText, renderCalendar, resourceDayFixture, withRecurrence };