@moltenship/calendar-dnd 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,1433 @@
1
+ "use client";
2
+ import { belongsInTimeGridAllDayRow, createPlacementBetween, eventPlacement, formatPlacementRange, movePlacementToTarget, resizePlacementToTarget, showsInResource, splitEventsByDay, timeGridDateTimeAt, timedFragmentBox, timelineExtent } from "@moltenship/calendar-core";
3
+ import { comparePlainDates, instantInterval, plainDateInterval } from "@moltenship/calendar-temporal";
4
+ import { useCallback, useInsertionEffect, useRef } from "react";
5
+ //#region src/auto-scroll.ts
6
+ const EDGE = 48;
7
+ const MAXIMUM_STEP = 18;
8
+ /** Pixels to scroll this frame along one axis: faster the deeper the pointer is in an edge band. */
9
+ function step(position, start, end) {
10
+ if (position < start + EDGE) return -18 * Math.min(1, (start + EDGE - position) / EDGE);
11
+ if (position > end - EDGE) return MAXIMUM_STEP * Math.min(1, (position - (end - EDGE)) / EDGE);
12
+ return 0;
13
+ }
14
+ function scrollableAncestor(element) {
15
+ for (let current = element; current !== null; current = current.parentElement) {
16
+ const { overflowX, overflowY } = getComputedStyle(current);
17
+ const scrollsY = /auto|scroll|overlay/.test(overflowY) && current.scrollHeight > current.clientHeight;
18
+ const scrollsX = /auto|scroll|overlay/.test(overflowX) && current.scrollWidth > current.clientWidth;
19
+ if (scrollsY || scrollsX) return current;
20
+ }
21
+ return document.scrollingElement ?? document.documentElement;
22
+ }
23
+ function bounds(container) {
24
+ return container === document.scrollingElement || container === document.documentElement ? {
25
+ bottom: innerHeight,
26
+ left: 0,
27
+ right: innerWidth,
28
+ top: 0
29
+ } : container.getBoundingClientRect();
30
+ }
31
+ /** Whether a viewport point is inside `container` and clear of the bands that scroll it. */
32
+ function clearOfEdges(container, x, y) {
33
+ const rect = bounds(container);
34
+ return x >= rect.left && x <= rect.right && y >= rect.top && y <= rect.bottom && step(x, rect.left, rect.right) === 0 && step(y, rect.top, rect.bottom) === 0;
35
+ }
36
+ /** How long a point rests in an edge band before that edge scrolls. */
37
+ const ENTRY_DWELL_MS = 250;
38
+ /** Whether a viewport point is inside `container`, in a band near one of its edges. */
39
+ function inEdgeBand(container, x, y) {
40
+ const rect = bounds(container);
41
+ return x >= rect.left && x <= rect.right && y >= rect.top && y <= rect.bottom && (step(x, rect.left, rect.right) !== 0 || step(y, rect.top, rect.bottom) !== 0);
42
+ }
43
+ /**
44
+ * Whether a view's edges may scroll it, for a drag that came into the view from outside it: once
45
+ * the point has been clear of them, or has rested in one of their bands for a moment. So a drag
46
+ * that crosses an edge on its way in doesn't scroll the view, nor one that rests over a part of the
47
+ * view outside its scroller, such as a header; one held at an edge still does.
48
+ */
49
+ var EdgeArming = class {
50
+ #armed;
51
+ #since;
52
+ constructor(armed) {
53
+ this.#armed = armed;
54
+ }
55
+ get armed() {
56
+ return this.#armed;
57
+ }
58
+ /** The drag left the view: its edges wait again. */
59
+ disarm() {
60
+ this.#armed = false;
61
+ this.#since = void 0;
62
+ }
63
+ /** Takes the point's place at `time`, from `performance.now()`; returns whether edges scroll. */
64
+ update(container, x, y, time) {
65
+ if (this.#armed) return true;
66
+ if (clearOfEdges(container, x, y)) this.#armed = true;
67
+ else if (inEdgeBand(container, x, y)) {
68
+ this.#since ??= time;
69
+ this.#armed = time - this.#since >= ENTRY_DWELL_MS;
70
+ } else this.#since = void 0;
71
+ return this.#armed;
72
+ }
73
+ };
74
+ /**
75
+ * Scrolls `container` when a viewport point sits near its edges, and `sideways` in its place at
76
+ * the left and right edges: a scroller nested in it that scrolls sideways. Returns whether either
77
+ * moved, so the caller re-reads geometry only after a scroll.
78
+ */
79
+ function autoScroll(container, x, y, sideways = container) {
80
+ const rect = bounds(container);
81
+ const { scrollTop } = container;
82
+ const { scrollLeft } = sideways;
83
+ container.scrollTop += step(y, rect.top, rect.bottom);
84
+ sideways.scrollLeft += step(x, rect.left, rect.right);
85
+ return container.scrollTop !== scrollTop || sideways.scrollLeft !== scrollLeft;
86
+ }
87
+ //#endregion
88
+ //#region src/drags.ts
89
+ const monitors = /* @__PURE__ */ new Set();
90
+ /** Reports an application callback's error without breaking the gesture it heard about. */
91
+ function reportCallbackError(error) {
92
+ if (typeof reportError === "function") reportError(error);
93
+ else console.error(error);
94
+ }
95
+ /**
96
+ * Hears every event a calendar view starts to move by pointer, on the page, so a drop zone
97
+ * outside the calendar can take it, such as a list of unscheduled items or a bin, or an animation
98
+ * can follow it. Resizes and creates aren't offered. While a follower with `claims` is on a drag,
99
+ * the view counts only where it's the topmost thing under the pointer, so a sheet of zones over it
100
+ * hides it; off the view, covered or claimed, a copy of the event follows the pointer. The view
101
+ * scrolls only while the pointer is over it, and after the pointer has left, only once it has
102
+ * been clear of the edges again or rested at one. Followers without `claims` change none of that.
103
+ * Returns a function that stops listening.
104
+ */
105
+ function monitorCalendarDrags(monitor) {
106
+ monitors.add(monitor);
107
+ return () => {
108
+ monitors.delete(monitor);
109
+ };
110
+ }
111
+ /** The followers the monitors put on a drag that just started. */
112
+ function followersOf(drag) {
113
+ const followers = [];
114
+ for (const monitor of monitors) try {
115
+ const follower = monitor(drag);
116
+ if (follower) followers.push(follower);
117
+ } catch (error) {
118
+ reportCallbackError(error);
119
+ }
120
+ return followers;
121
+ }
122
+ /** Calls `notify` on each follower, reporting what throws instead of stopping the gesture. */
123
+ function tellFollowers(followers, notify) {
124
+ for (const follower of followers) try {
125
+ notify(follower);
126
+ } catch (error) {
127
+ reportCallbackError(error);
128
+ }
129
+ }
130
+ /** Whether a follower claims the point now. */
131
+ function claimed(followers) {
132
+ return followers.some((follower) => {
133
+ try {
134
+ return follower.claims?.() === true;
135
+ } catch (error) {
136
+ reportCallbackError(error);
137
+ return false;
138
+ }
139
+ });
140
+ }
141
+ //#endregion
142
+ //#region src/event-id.ts
143
+ /**
144
+ * Attributes that identify an event element, for spreading onto it. `data-event-id` holds the ID
145
+ * as text; numeric IDs add `data-event-id-type="number"`, so `1` and `"1"` stay distinct.
146
+ */
147
+ function eventIdAttributes(id) {
148
+ return typeof id === "number" ? {
149
+ "data-event-id": String(id),
150
+ "data-event-id-type": "number"
151
+ } : { "data-event-id": id };
152
+ }
153
+ /** The event ID an element carries through `eventIdAttributes`, or `null` without one. */
154
+ function eventIdOf(element) {
155
+ const id = element.getAttribute("data-event-id");
156
+ if (id === null) return null;
157
+ return element.getAttribute("data-event-id-type") === "number" ? Number(id) : id;
158
+ }
159
+ //#endregion
160
+ //#region src/gestures.ts
161
+ /** The snapped time under the pointer. The keyboard reaches the same targets through slots. */
162
+ function interactionTarget(target, snap) {
163
+ return target.kind === "day" ? target : {
164
+ at: timeGridDateTimeAt(target.column, target.y, { snap }),
165
+ kind: "time",
166
+ resourceId: target.resourceId
167
+ };
168
+ }
169
+ /** Whether two placements are the same range, kind and resources. */
170
+ function samePlacement(left, right) {
171
+ return left.kind === right.kind && left.start.toString() === right.start.toString() && left.end.toString() === right.end.toString() && left.resourceIds.length === right.resourceIds.length && left.resourceIds.every((resourceId) => right.resourceIds.includes(resourceId));
172
+ }
173
+ /**
174
+ * Where a dragged event lands. Moves within one axis keep the event's kind; dropping a timed event
175
+ * on a day cell makes it all-day, and dropping an all-day event on a time column makes it a
176
+ * one-hour timed event. Dropping in another resource swaps that resource in `resourceIds`.
177
+ */
178
+ function movedPlacement(original, grab, current, { snap, timeZone }) {
179
+ return movePlacementToTarget(original, interactionTarget(grab, snap), interactionTarget(current, snap), { timeZone });
180
+ }
181
+ /** The placement after dragging one edge; `null` while the pointer is over the other axis. */
182
+ function resizedPlacement(original, edge, grab, current, options) {
183
+ return resizePlacementToTarget(original, edge, interactionTarget(grab, options.snap), interactionTarget(current, options.snap), options);
184
+ }
185
+ /**
186
+ * The new event spanning the slots or day cells from where the drag started to where it is now;
187
+ * `null` while the pointer is over the other axis.
188
+ */
189
+ function createdPlacement(anchor, current, { snap }) {
190
+ const floor = {
191
+ ...snap,
192
+ mode: "floor"
193
+ };
194
+ return createPlacementBetween(interactionTarget(anchor, floor), interactionTarget(current, floor), { snap });
195
+ }
196
+ /**
197
+ * Where an item dragged in from outside lands, starting at the slot or day under the pointer. A
198
+ * new event is `duration` long over a time column and `days` long over day cells, in the resource
199
+ * it is dropped in. A moved event's start lands there, and its kind changes as an in-view drag's
200
+ * would; in another resource, that resource takes the place of its first.
201
+ */
202
+ function droppedPlacement(item, target, { snap, timeZone }) {
203
+ const at = interactionTarget(target, {
204
+ ...snap,
205
+ mode: "floor"
206
+ });
207
+ if (item.kind === "move") {
208
+ const { original } = item;
209
+ const resourceId = target.resourceId === void 0 ? void 0 : original.resourceIds[0] ?? null;
210
+ const grab = original.kind === "all-day" ? {
211
+ date: original.start,
212
+ kind: "day",
213
+ resourceId
214
+ } : {
215
+ at: original.kind === "timed" ? original.start.toZonedDateTimeISO(timeZone) : original.start.toZonedDateTime(timeZone),
216
+ kind: "time",
217
+ resourceId
218
+ };
219
+ return movePlacementToTarget(original, grab, at, { timeZone });
220
+ }
221
+ const resourceIds = target.resourceId == null ? [] : [target.resourceId];
222
+ return at.kind === "day" ? {
223
+ end: at.date.add({ days: item.days }),
224
+ kind: "all-day",
225
+ resourceIds,
226
+ start: at.date
227
+ } : {
228
+ end: at.at.add(item.duration).toInstant(),
229
+ kind: "timed",
230
+ resourceIds,
231
+ start: at.at.toInstant()
232
+ };
233
+ }
234
+ //#endregion
235
+ //#region src/resource-id.ts
236
+ /**
237
+ * Attributes that place an element in a resource, for spreading onto a resource's column, row, or
238
+ * cells. `data-resource-id` holds the ID as text, empty for the unassigned bucket (`null`); numeric
239
+ * IDs add `data-resource-id-type="number"`, so `1` and `"1"` stay distinct.
240
+ */
241
+ function resourceIdAttributes(id) {
242
+ if (id === null) return { "data-resource-id": "" };
243
+ return typeof id === "number" ? {
244
+ "data-resource-id": String(id),
245
+ "data-resource-id-type": "number"
246
+ } : { "data-resource-id": id };
247
+ }
248
+ /**
249
+ * The resource an element sits in, from the nearest `resourceIdAttributes`: `null` in the
250
+ * unassigned bucket, `undefined` outside any resource.
251
+ */
252
+ function resourceIdOf(element) {
253
+ const holder = element.closest("[data-resource-id]");
254
+ if (holder === null) return void 0;
255
+ const id = holder.getAttribute("data-resource-id");
256
+ if (id === "") return null;
257
+ return holder.getAttribute("data-resource-id-type") === "number" ? Number(id) : id;
258
+ }
259
+ //#endregion
260
+ //#region src/targets.ts
261
+ /** A view's time columns by ISO date, for matching `[data-date]` elements to them. */
262
+ function columnsByDate(columns) {
263
+ return new Map((columns ?? []).map((column) => [column.date.toString(), column]));
264
+ }
265
+ /** The cell's resource, left out in views without resources. */
266
+ function resourceOf(cell) {
267
+ const resourceId = resourceIdOf(cell);
268
+ return resourceId === void 0 ? {} : { resourceId };
269
+ }
270
+ /** Whether a placement shows in a cell's resource; cells outside any resource show all. */
271
+ function showsInCell(placement, cell) {
272
+ const resourceId = resourceIdOf(cell);
273
+ return resourceId === void 0 || showsInResource(placement.resourceIds, resourceId);
274
+ }
275
+ /** Whether a time column runs along the inline axis, as a timeline's date strip does. */
276
+ function isInline(cell) {
277
+ return cell.getAttribute("data-axis") === "inline";
278
+ }
279
+ /** Whether the inline axis runs from the right, as `dir="rtl"` on an ancestor sets. */
280
+ function isRightToLeft(cell) {
281
+ return cell.closest("[dir]")?.getAttribute("dir") === "rtl";
282
+ }
283
+ /** How far through its day a point is in a time column: down it, or from its inline start. */
284
+ function along(cell, x, y) {
285
+ const rect = cell.getBoundingClientRect();
286
+ if (!isInline(cell)) return rect.height > 0 ? (y - rect.top) / rect.height : 0;
287
+ if (rect.width <= 0) return 0;
288
+ return (isRightToLeft(cell) ? rect.right - x : x - rect.left) / rect.width;
289
+ }
290
+ function isTimeColumn(surface, cell) {
291
+ const date = cell.getAttribute("data-date");
292
+ return date !== null && !cell.hasAttribute("data-all-day") && surface.columns.has(date);
293
+ }
294
+ /** Day cells: month cells, or the all-day row of a time grid. */
295
+ function dayCells(surface) {
296
+ return [...surface.region.querySelectorAll("[data-date]")].filter((cell) => !isTimeColumn(surface, cell));
297
+ }
298
+ function timeColumns(surface) {
299
+ return [...surface.region.querySelectorAll("[data-date]")].filter((cell) => isTimeColumn(surface, cell));
300
+ }
301
+ /**
302
+ * The day cell or point in a time column under a viewport point, in the resource around the cell.
303
+ * Hit-testing every element at the point finds the cell beneath events that span several cells;
304
+ * a part marked `data-occludes`, such as a sticky header, hides the cells scrolled beneath it.
305
+ */
306
+ function targetAt(surface, x, y) {
307
+ for (const element of document.elementsFromPoint(x, y)) {
308
+ if (element.closest("[data-occludes]") !== null) return null;
309
+ const cell = element.closest("[data-date]");
310
+ if (cell === null || !surface.region.contains(cell)) continue;
311
+ const date = cell.getAttribute("data-date");
312
+ const resource = resourceOf(cell);
313
+ const column = isTimeColumn(surface, cell) ? surface.columns.get(date) : void 0;
314
+ if (column === void 0) return {
315
+ date: Temporal.PlainDate.from(date),
316
+ kind: "day",
317
+ ...resource
318
+ };
319
+ return {
320
+ column,
321
+ kind: "time",
322
+ y: along(cell, x, y),
323
+ ...resource
324
+ };
325
+ }
326
+ return null;
327
+ }
328
+ //#endregion
329
+ //#region src/ghost.ts
330
+ function clips(overflow) {
331
+ return overflow !== "" && overflow !== "visible";
332
+ }
333
+ /**
334
+ * The part of the viewport where a cell's content can paint. The preview is fixed-position, so it
335
+ * applies the clipping of the cell's scroll viewport and other overflow ancestors itself.
336
+ */
337
+ function visibleBounds(surface, cell, rectOf) {
338
+ let ancestors = surface.clippers.get(cell);
339
+ if (ancestors === void 0) {
340
+ const found = [];
341
+ for (let current = cell.parentElement; current !== null; current = current.parentElement) {
342
+ const { overflowX, overflowY } = getComputedStyle(current);
343
+ if (clips(overflowX) || clips(overflowY)) found.push(current);
344
+ }
345
+ surface.clippers.set(cell, found);
346
+ ancestors = found;
347
+ }
348
+ let bounds = {
349
+ bottom: innerHeight,
350
+ left: 0,
351
+ right: innerWidth,
352
+ top: 0
353
+ };
354
+ for (const ancestor of ancestors) {
355
+ const rect = rectOf(ancestor);
356
+ bounds = {
357
+ bottom: Math.min(bounds.bottom, rect.bottom),
358
+ left: Math.max(bounds.left, rect.left),
359
+ right: Math.min(bounds.right, rect.right),
360
+ top: Math.max(bounds.top, rect.top)
361
+ };
362
+ }
363
+ return bounds;
364
+ }
365
+ function isVisible({ height, left, top, visible, width }) {
366
+ return left < visible.right && left + width > visible.left && top < visible.bottom && top + height > visible.top;
367
+ }
368
+ function instantEndpoints(placement, timeZone) {
369
+ return placement.kind === "timed" ? {
370
+ end: placement.end,
371
+ start: placement.start
372
+ } : {
373
+ end: placement.end.toZonedDateTime(timeZone).toInstant(),
374
+ start: placement.start.toZonedDateTime(timeZone).toInstant()
375
+ };
376
+ }
377
+ function timeColumnRects(surface, placement, timeZone, rectOf) {
378
+ const { end, start } = instantEndpoints(placement, timeZone);
379
+ return timeColumns(surface).flatMap((cell) => {
380
+ if (isInline(cell) || !showsInCell(placement, cell)) return [];
381
+ const column = surface.columns.get(cell.getAttribute("data-date"));
382
+ const day = column.day.interval;
383
+ if (day === null) return [];
384
+ const from = Temporal.Instant.compare(start, day.start) > 0 ? start : day.start;
385
+ const to = Temporal.Instant.compare(end, day.end) < 0 ? end : day.end;
386
+ if (Temporal.Instant.compare(from, to) >= 0) return [];
387
+ const box = timedFragmentBox(column, instantInterval(from, to));
388
+ const rect = rectOf(cell);
389
+ return [{
390
+ height: box.height * rect.height,
391
+ left: rect.left,
392
+ top: rect.top + box.top * rect.height,
393
+ visible: visibleBounds(surface, cell, rectOf),
394
+ width: rect.width
395
+ }];
396
+ });
397
+ }
398
+ /**
399
+ * Boxes along a timeline's date strips, measured as the timeline lays out its bars: every kind of
400
+ * placement, all-day and day-long ones included, with floating ones on their wall clock.
401
+ */
402
+ function inlineStripRects(surface, strips, placement, rectOf) {
403
+ return strips.flatMap((cell) => {
404
+ if (!showsInCell(placement, cell)) return [];
405
+ const column = surface.columns.get(cell.getAttribute("data-date"));
406
+ const extent = timelineExtent([column], placement);
407
+ if (extent === null) return [];
408
+ const rect = rectOf(cell);
409
+ const width = (extent.end - extent.start) * rect.width;
410
+ const offset = extent.start * rect.width;
411
+ const left = isRightToLeft(cell) ? rect.right - offset - width : rect.left + offset;
412
+ return [{
413
+ height: rect.height,
414
+ left,
415
+ top: rect.top,
416
+ visible: visibleBounds(surface, cell, rectOf),
417
+ width
418
+ }];
419
+ });
420
+ }
421
+ function sameBounds(left, right) {
422
+ return left.bottom === right.bottom && left.left === right.left && left.right === right.right && left.top === right.top;
423
+ }
424
+ /**
425
+ * The rendered dates a placement has time on, from the projection's own day splitting: a date the
426
+ * zone skipped gets none, and a date that a jump back across midnight repeats keeps its share.
427
+ * Splitting stays within the rendered dates, however long the event is.
428
+ */
429
+ function touchedDates(placement, rendered, timeZone) {
430
+ if (rendered.length === 0) return /* @__PURE__ */ new Set();
431
+ const dates = rendered.map((date) => Temporal.PlainDate.from(date)).toSorted(comparePlainDates);
432
+ const range = plainDateInterval(dates[0], dates.at(-1).add({ days: 1 }));
433
+ const event = {
434
+ ...placement,
435
+ event: null,
436
+ id: "preview",
437
+ inputIndex: 0,
438
+ isReadOnly: false,
439
+ title: ""
440
+ };
441
+ return new Set(splitEventsByDay([event], range, timeZone).map(({ date }) => date.toString()));
442
+ }
443
+ /**
444
+ * Covers the day cells in the placement's dates. Neighbours on the same row merge when the same
445
+ * ancestors clip them.
446
+ */
447
+ function dayCellRects(surface, placement, timeZone, rectOf) {
448
+ const cells = dayCells(surface);
449
+ const dates = touchedDates(placement, cells.map((cell) => cell.getAttribute("data-date")), timeZone);
450
+ const rects = [];
451
+ for (const cell of cells) {
452
+ if (!dates.has(cell.getAttribute("data-date")) || !showsInCell(placement, cell)) continue;
453
+ const rect = rectOf(cell);
454
+ const visible = visibleBounds(surface, cell, rectOf);
455
+ const previous = rects.at(-1);
456
+ if (previous !== void 0 && sameBounds(previous.visible, visible) && Math.abs(previous.top - rect.top) < 1 && (Math.abs(previous.left + previous.width - rect.left) < 1 || Math.abs(rect.right - previous.left) < 1)) {
457
+ const left = Math.min(previous.left, rect.left);
458
+ rects[rects.length - 1] = {
459
+ ...previous,
460
+ left,
461
+ width: Math.max(previous.left + previous.width, rect.right) - left
462
+ };
463
+ } else rects.push({
464
+ height: rect.height,
465
+ left: rect.left,
466
+ top: rect.top,
467
+ visible,
468
+ width: rect.width
469
+ });
470
+ }
471
+ return rects;
472
+ }
473
+ /**
474
+ * Viewport boxes that preview a placement where the view will render it: along a timeline's date
475
+ * strips, in time columns, or in day cells for all-day and 24-hour-plus events, which a time grid
476
+ * shows in its all-day row. In a resource view only the placement's resources get boxes. Boxes
477
+ * outside their cell's scroll viewport are left out.
478
+ */
479
+ function ghostLayout(surface, placement, timeZone) {
480
+ const rects = /* @__PURE__ */ new Map();
481
+ const rectOf = (element) => {
482
+ let rect = rects.get(element);
483
+ if (rect === void 0) {
484
+ rect = element.getBoundingClientRect();
485
+ rects.set(element, rect);
486
+ }
487
+ return rect;
488
+ };
489
+ const strips = timeColumns(surface).filter(isInline);
490
+ const layout = strips.length > 0 ? {
491
+ axis: "time",
492
+ rects: inlineStripRects(surface, strips, placement, rectOf)
493
+ } : placement.kind !== "all-day" && surface.columns.size > 0 && !belongsInTimeGridAllDayRow(placement) ? {
494
+ axis: "time",
495
+ rects: timeColumnRects(surface, placement, timeZone, rectOf)
496
+ } : {
497
+ axis: "day",
498
+ rects: dayCellRects(surface, placement, timeZone, rectOf)
499
+ };
500
+ return {
501
+ ...layout,
502
+ rects: layout.rects.filter(isVisible)
503
+ };
504
+ }
505
+ /** How a preview shows what the policies say: rejected, flagged, or fine. */
506
+ function ghostValidity(check) {
507
+ if (check === null) return null;
508
+ if (check.status === "rejected") return "invalid";
509
+ return check.change.warnings !== void 0 && check.change.warnings.length > 0 ? "warning" : null;
510
+ }
511
+ /**
512
+ * Fixed-position preview segments, moved with transforms so a drag never re-renders the view, and
513
+ * clipped to their cells' scroll viewports. Segments are translucent clones of the dragged event,
514
+ * or range boxes for creates and day cells; style them through `[data-calendar-ghost]` or the
515
+ * `--calendar-ghost-*` custom properties. A clone's `[data-event-time]` shows `label`, and
516
+ * `data-invalid` or `data-warning` marks a drop the policies would reject or flag. A clone that
517
+ * follows the pointer outside the view, toward a drop zone of the app's, has `data-outside`.
518
+ */
519
+ var GhostLayer = class {
520
+ #className;
521
+ #origin = null;
522
+ #outside = false;
523
+ #region;
524
+ #segments = [];
525
+ #template = null;
526
+ constructor(region, className) {
527
+ this.#className = className;
528
+ this.#region = region;
529
+ }
530
+ /**
531
+ * Shows `rects`: copies of `template`, or range boxes without one. `outside` marks a copy that
532
+ * follows the pointer outside the view (`data-outside`).
533
+ */
534
+ render(rects, template, label, validity = null, outside = false) {
535
+ if (template !== this.#template || outside !== this.#outside) {
536
+ this.clear();
537
+ this.#template = template;
538
+ this.#outside = outside;
539
+ }
540
+ while (this.#segments.length < rects.length) this.#segments.push(this.#createSegment());
541
+ while (this.#segments.length > rects.length) this.#segments.pop().remove();
542
+ if (rects.length === 0) return;
543
+ const origin = this.#containingBlockOrigin();
544
+ rects.forEach((rect, index) => {
545
+ const segment = this.#segments[index];
546
+ const { style } = segment;
547
+ const { height, left, top, visible, width } = rect;
548
+ const insets = [
549
+ visible.top - top,
550
+ left + width - visible.right,
551
+ top + height - visible.bottom,
552
+ visible.left - left
553
+ ].map((inset) => Math.max(0, inset));
554
+ style.width = `${width}px`;
555
+ style.height = `${height}px`;
556
+ style.transform = `translate3d(${left - origin.left}px, ${top - origin.top}px, 0)`;
557
+ style.clipPath = insets.some((inset) => inset > 0) ? `inset(${insets.map((inset) => `${inset}px`).join(" ")})` : "";
558
+ segment.toggleAttribute("data-invalid", validity === "invalid");
559
+ segment.toggleAttribute("data-warning", validity === "warning");
560
+ segment.toggleAttribute("data-outside", outside);
561
+ if (label === null) return;
562
+ for (const time of segment.querySelectorAll("[data-event-time]")) time.textContent = label;
563
+ });
564
+ }
565
+ clear() {
566
+ for (const segment of this.#segments) segment.remove();
567
+ this.#segments.length = 0;
568
+ this.#origin?.remove();
569
+ this.#origin = null;
570
+ }
571
+ /**
572
+ * Where a fixed `left: 0; top: 0` box actually sits. It is the viewport origin unless an
573
+ * ancestor is transformed, which makes that ancestor the containing block of fixed elements.
574
+ */
575
+ #containingBlockOrigin() {
576
+ if (this.#origin === null) {
577
+ this.#origin = document.createElement("div");
578
+ this.#origin.setAttribute("aria-hidden", "true");
579
+ this.#origin.setAttribute("data-calendar-ghost-origin", "");
580
+ Object.assign(this.#origin.style, {
581
+ height: "0",
582
+ left: "0",
583
+ pointerEvents: "none",
584
+ position: "fixed",
585
+ top: "0",
586
+ visibility: "hidden",
587
+ width: "0"
588
+ });
589
+ this.#region.append(this.#origin);
590
+ }
591
+ return this.#origin.getBoundingClientRect();
592
+ }
593
+ #createSegment() {
594
+ const template = this.#template;
595
+ const segment = template === null ? document.createElement("div") : template.cloneNode(true);
596
+ for (const attribute of [
597
+ "data-dragging",
598
+ "data-event-id",
599
+ "data-event-id-type",
600
+ "id"
601
+ ]) segment.removeAttribute(attribute);
602
+ segment.setAttribute("aria-hidden", "true");
603
+ segment.setAttribute("data-calendar-ghost", template === null ? "range" : "event");
604
+ if (this.#className !== void 0) segment.classList.add(...this.#className.split(/\s+/).filter(Boolean));
605
+ Object.assign(segment.style, {
606
+ bottom: "auto",
607
+ boxSizing: "border-box",
608
+ left: "0",
609
+ margin: "0",
610
+ pointerEvents: "none",
611
+ position: "fixed",
612
+ right: "auto",
613
+ top: "0",
614
+ zIndex: "var(--calendar-ghost-z-index, 50)"
615
+ });
616
+ Object.assign(segment.style, template === null ? {
617
+ background: "var(--calendar-ghost-background, rgb(37 99 235 / 0.18))",
618
+ borderRadius: "var(--calendar-ghost-radius, 6px)"
619
+ } : {
620
+ boxShadow: "var(--calendar-ghost-shadow, 0 6px 16px rgb(0 0 0 / 0.18))",
621
+ opacity: "var(--calendar-ghost-opacity, 0.75)"
622
+ });
623
+ this.#region.append(segment);
624
+ return segment;
625
+ }
626
+ };
627
+ //#endregion
628
+ //#region src/outcome.ts
629
+ /**
630
+ * Announces what became of a proposal from what `onPropose` returned: the transaction's result, or
631
+ * from a handler that returns none, a commit of what was proposed. Resolves with the result, or
632
+ * `null` without one.
633
+ */
634
+ function settleProposal(returned, proposed, announce) {
635
+ if (returned === void 0) {
636
+ announce({
637
+ phase: "commit",
638
+ proposed
639
+ });
640
+ return Promise.resolve(null);
641
+ }
642
+ return Promise.resolve(returned).then((result) => {
643
+ announce(result.status === "committed" ? {
644
+ phase: "commit",
645
+ proposed: result.change.proposed,
646
+ warnings: result.change.warnings
647
+ } : {
648
+ phase: "reject",
649
+ reason: result.reason,
650
+ ...result.error === void 0 ? {} : { error: result.error }
651
+ });
652
+ return result;
653
+ });
654
+ }
655
+ //#endregion
656
+ //#region src/regions.ts
657
+ const regions = /* @__PURE__ */ new Set();
658
+ const observers = /* @__PURE__ */ new Set();
659
+ function isEnabled(region) {
660
+ return region.getOptions().disabled !== true;
661
+ }
662
+ function snapshot() {
663
+ return Object.freeze([...regions].map((region) => Object.freeze({
664
+ disabled: !isEnabled(region),
665
+ element: region.element
666
+ })));
667
+ }
668
+ /** Tells an observer the regions, reporting what it throws instead of breaking an attach. */
669
+ function tell(observer, current) {
670
+ try {
671
+ observer(current);
672
+ } catch (error) {
673
+ reportCallbackError(error);
674
+ }
675
+ }
676
+ function notify() {
677
+ if (observers.size === 0) return;
678
+ const current = snapshot();
679
+ for (const observer of observers) tell(observer, current);
680
+ }
681
+ /** Lists a region while it's attached, so drags from outside the calendar can find it. */
682
+ function registerRegion(region) {
683
+ regions.add(region);
684
+ notify();
685
+ return () => {
686
+ if (regions.delete(region)) notify();
687
+ };
688
+ }
689
+ /**
690
+ * Hears the calendar views on the page: once now, and again whenever a view's region attaches or
691
+ * detaches. A region that turns read-only attaches again, so `disabled` follows it. Returns a
692
+ * function that stops listening.
693
+ */
694
+ function observeCalendarRegions(observer) {
695
+ observers.add(observer);
696
+ tell(observer, snapshot());
697
+ return () => {
698
+ observers.delete(observer);
699
+ };
700
+ }
701
+ /** Whether a region is still attached and takes drops. */
702
+ function takesDrops(region) {
703
+ return regions.has(region) && isEnabled(region);
704
+ }
705
+ /**
706
+ * The region that takes drops under a viewport point, with the element hit there: the topmost
707
+ * one, so anything over the view, such as a sheet, a dialog or a read-only view, hides it.
708
+ * Elements the pointer goes through (`pointer-events: none`), as drag images do, don't count.
709
+ */
710
+ function regionAt(x, y) {
711
+ if (regions.size === 0) return null;
712
+ const [element] = document.elementsFromPoint(x, y);
713
+ if (element === void 0) return null;
714
+ for (const region of regions) if (region.element.contains(element)) return isEnabled(region) ? {
715
+ element,
716
+ region
717
+ } : null;
718
+ return null;
719
+ }
720
+ //#endregion
721
+ //#region src/attach-calendar-pointer.ts
722
+ const DEFAULT_SNAP$1 = {
723
+ increment: 15,
724
+ smallestUnit: "minute"
725
+ };
726
+ /** Pointer travel that turns a mouse or pen press into a drag; anything less is a click. */
727
+ const DRAG_DISTANCE = 4;
728
+ /**
729
+ * Touch drags start after a still long-press, about as long as the platforms' own, so a swipe keeps
730
+ * scrolling even when the finger rests a moment first.
731
+ */
732
+ const LONG_PRESS_MS = 450;
733
+ const TOUCH_TOLERANCE = 8;
734
+ /** The most of a long or wide event the copy that follows the pointer outside the view shows. */
735
+ const FLOATING_MAXIMUM = {
736
+ height: 120,
737
+ width: 320
738
+ };
739
+ const noFollowers = Object.freeze([]);
740
+ const pointerInput = Object.freeze({ input: "pointer" });
741
+ function preventDefault(event) {
742
+ event.preventDefault();
743
+ }
744
+ /** Swallows the click that follows a drag, so dropping an event does not also open it. */
745
+ function suppressNextClick() {
746
+ const swallow = (event) => {
747
+ event.preventDefault();
748
+ event.stopPropagation();
749
+ };
750
+ window.addEventListener("click", swallow, {
751
+ capture: true,
752
+ once: true
753
+ });
754
+ setTimeout(() => window.removeEventListener("click", swallow, { capture: true }));
755
+ }
756
+ /** The size and press offset of the copy that follows a moved event outside the view. */
757
+ function floatingOf(element, origin) {
758
+ const rect = element.getBoundingClientRect();
759
+ const width = Math.min(rect.width, FLOATING_MAXIMUM.width);
760
+ const height = Math.min(rect.height, FLOATING_MAXIMUM.height);
761
+ return {
762
+ height,
763
+ offset: {
764
+ x: Math.min(Math.max(origin.x - rect.left, 0), width),
765
+ y: Math.min(Math.max(origin.y - rect.top, 0), height)
766
+ },
767
+ width
768
+ };
769
+ }
770
+ /** Whether followers would hear nothing new: the same boxes, time range and policy answer. */
771
+ function samePreview(a, b) {
772
+ if (a === null || b === null) return a === b;
773
+ return a.label === b.label && a.validity === b.validity && a.rects.length === b.rects.length && a.rects.every((rect, index) => rect.x === b.rects[index].x && rect.y === b.rects[index].y && rect.width === b.rects[index].width && rect.height === b.rects[index].height);
774
+ }
775
+ /** A preview segment's box, for followers. */
776
+ function viewportRect({ height, left, top, width }) {
777
+ return {
778
+ height,
779
+ width,
780
+ x: left,
781
+ y: top
782
+ };
783
+ }
784
+ /** Where the copy sits under the pointer, anywhere in the viewport. */
785
+ function floatingRect({ height, offset, width }, point) {
786
+ return {
787
+ height,
788
+ left: point.x - offset.x,
789
+ top: point.y - offset.y,
790
+ visible: {
791
+ bottom: innerHeight,
792
+ left: 0,
793
+ right: innerWidth,
794
+ top: 0
795
+ },
796
+ width
797
+ };
798
+ }
799
+ /**
800
+ * The event an element renders. Without `data-event-id-type`, an ID that only exists as a number
801
+ * still resolves, which keeps all-numeric calendars working with plain `data-event-id`.
802
+ */
803
+ function resolveEvent(events, element) {
804
+ const id = eventIdOf(element);
805
+ const numeric = Number(id);
806
+ return events.get(id) ?? (typeof id === "string" && Number.isFinite(numeric) ? events.get(numeric) : void 0);
807
+ }
808
+ /**
809
+ * Adds pointer move, resize, and create to a rendered view through delegated listeners on one
810
+ * region. The view marks its parts with data attributes:
811
+ *
812
+ * - `data-event-id` on events (spread `eventIdAttributes(id)` to keep numeric IDs distinct), with
813
+ * `data-resize="start"` or `"end"` on resize handles;
814
+ * - `data-date` (an ISO date) on time-grid day columns and on day cells (month cells, or a time
815
+ * grid's all-day row, which also carries `data-all-day`); a time column with
816
+ * `data-axis="inline"`, such as a timeline's strip for one date, runs its day from the inline
817
+ * start, the right under `dir="rtl"`;
818
+ * - in a resource view, `data-resource-id` on each cell or an element around it (spread
819
+ * `resourceIdAttributes(id)`), so a drop in another resource swaps it in the event's
820
+ * `resourceIds` and a create starts in the resource it began in;
821
+ * - `data-event-time` on the element inside an event that shows its time range, which the
822
+ * preview relabels with the proposed range;
823
+ * - `data-occludes` on parts that sit over the cells, such as sticky headers: a gesture can't start
824
+ * or land on the cells scrolled beneath them;
825
+ * - `data-calendar-pointer="none"` on controls of their own inside the region, such as annotation
826
+ * marks, so pressing them never starts a drag.
827
+ *
828
+ * The preview moves without re-rendering. `onPropose` runs once per drop; a click (less than a few
829
+ * pixels of travel) is left alone, and Escape cancels. Touch drags start after a finger rests still
830
+ * for 450 ms, so a swipe scrolls; once one starts, the page holds still under it. Returns a function
831
+ * that detaches everything.
832
+ */
833
+ function attachCalendarPointer(region, getOptions) {
834
+ let session = null;
835
+ function placementAt(current, target) {
836
+ const { gesture, options } = current;
837
+ if (gesture.kind === "create") return createdPlacement(gesture.anchor, target, options);
838
+ return gesture.kind === "move" ? movedPlacement(gesture.original, gesture.grab, target, options) : resizedPlacement(gesture.original, gesture.edge, gesture.grab, target, options);
839
+ }
840
+ function announce(current, detail) {
841
+ const { check, gesture } = current;
842
+ current.announcer?.announce({
843
+ cause: gesture.kind !== "resize" ? gesture.kind : gesture.edge === "start" ? "resize-start" : "resize-end",
844
+ event: gesture.kind === "create" ? null : gesture.event,
845
+ input: "pointer",
846
+ original: gesture.kind === "create" ? null : gesture.original,
847
+ proposed: current.placement,
848
+ ...detail.phase === "start" || detail.phase === "step" ? { check } : void 0,
849
+ ...detail
850
+ });
851
+ }
852
+ /**
853
+ * Follows the view's latest columns: a view that scrolls through days renders new ones while a
854
+ * drag scrolls it, and their cells must map to times like the rest.
855
+ */
856
+ function refreshColumns(current) {
857
+ const { columns } = getOptions();
858
+ if (columns === current.surfaceColumns) return;
859
+ current.surfaceColumns = columns;
860
+ current.surface = {
861
+ ...current.surface,
862
+ columns: columnsByDate(columns)
863
+ };
864
+ }
865
+ /**
866
+ * Whether the view is the topmost thing under the pointer: anything over it, such as a sheet
867
+ * holding drop zones, hides it, as it does for drags in (`regionAt`).
868
+ */
869
+ function overView({ x, y }) {
870
+ const [top] = document.elementsFromPoint(x, y);
871
+ return top !== void 0 && region.contains(top);
872
+ }
873
+ /**
874
+ * Off the view, or over a drop zone that claims it, a moved event that a follower with `claims`
875
+ * follows shows as a copy under the pointer; elsewhere, such as over a header, nothing shows.
876
+ */
877
+ function showOutside(current) {
878
+ const { floating, gesture } = current;
879
+ if (floating === void 0 || gesture.kind !== "move" || !current.claimed && overView(current.point)) {
880
+ current.ghost.clear();
881
+ return;
882
+ }
883
+ current.ghost.render([floatingRect(floating, current.point)], gesture.element, null, null, true);
884
+ }
885
+ /** Shows where a drop would land; returns whether that changed. */
886
+ function preview(current, scrolled = false) {
887
+ refreshColumns(current);
888
+ current.claimed = claimed(current.followers);
889
+ const target = current.claimed || current.zones && !overView(current.point) ? null : targetAt(current.surface, current.point.x, current.point.y);
890
+ const placement = target === null ? null : placementAt(current, target);
891
+ if (placement === null) {
892
+ const changed = current.placement !== null;
893
+ current.placement = null;
894
+ current.check = null;
895
+ showOutside(current);
896
+ if (changed) {
897
+ getOptions().onPreview?.(null);
898
+ show(current, () => null);
899
+ }
900
+ return changed;
901
+ }
902
+ const changed = current.placement === null || !samePlacement(current.placement, placement);
903
+ if (!scrolled && !changed) return false;
904
+ current.placement = placement;
905
+ if (changed) {
906
+ const proposed = proposal(current);
907
+ current.check = proposed === null ? null : getOptions().check?.(proposed) ?? null;
908
+ getOptions().onPreview?.({
909
+ eventId: current.gesture.kind === "create" ? null : current.gesture.event.id,
910
+ proposed: placement
911
+ });
912
+ }
913
+ const { gesture } = current;
914
+ const layout = ghostLayout(current.surface, placement, current.options.timeZone);
915
+ const template = layout.axis === "time" && gesture.kind !== "create" ? gesture.element : null;
916
+ const label = template === null ? null : current.announcer?.formatRange(placement) ?? formatPlacementRange(placement, { timeZone: current.options.timeZone });
917
+ const validity = ghostValidity(current.check);
918
+ current.ghost.render(layout.rects, template, label, validity);
919
+ show(current, () => ({
920
+ label,
921
+ rects: layout.rects.map(viewportRect),
922
+ validity
923
+ }));
924
+ return changed;
925
+ }
926
+ /** Tells the followers what the preview shows now. */
927
+ function show(current, shown) {
928
+ if (current.followers.length === 0) return;
929
+ const preview = shown();
930
+ const same = samePreview(current.shown, preview);
931
+ current.shown = preview;
932
+ if (!same) tellFollowers(current.followers, (follower) => follower.preview?.(preview));
933
+ }
934
+ /**
935
+ * A drag that drop zones follow scrolls the view only over it, and once back in, only after the
936
+ * pointer has been clear of its edges or rested at one, so one on its way to a sidebar or back
937
+ * from it leaves the view be.
938
+ */
939
+ function trackEdges(current) {
940
+ if (!current.zones) return;
941
+ const { x, y } = current.point;
942
+ if (!overView(current.point)) current.edges.disarm();
943
+ else current.edges.update(current.scrollContainer, x, y, performance.now());
944
+ }
945
+ function scrollFrame() {
946
+ const current = session;
947
+ if (current === null) return;
948
+ trackEdges(current);
949
+ if (!(current.claimed || !current.edges.armed) && autoScroll(current.scrollContainer, current.point.x, current.point.y, current.sideways) && preview(current, true)) announce(current, { phase: "step" });
950
+ current.frame = requestAnimationFrame(scrollFrame);
951
+ }
952
+ function activate(current) {
953
+ clearTimeout(current.longPress);
954
+ current.active = true;
955
+ region.setAttribute("data-interaction", current.gesture.kind);
956
+ if (current.gesture.kind !== "create") current.gesture.element.setAttribute("data-dragging", "");
957
+ getSelection()?.removeAllRanges();
958
+ if (current.gesture.kind === "move") follow(current, current.gesture);
959
+ trackEdges(current);
960
+ current.frame = requestAnimationFrame(scrollFrame);
961
+ preview(current);
962
+ announce(current, { phase: "start" });
963
+ }
964
+ /** Offers a move to the monitors, for drop zones outside the calendar and animations. */
965
+ function follow(current, { element, event }) {
966
+ current.followers = followersOf({
967
+ element,
968
+ event,
969
+ origin: current.origin,
970
+ refresh: () => {
971
+ if (session === current && current.active && preview(current)) announce(current, { phase: "step" });
972
+ }
973
+ });
974
+ current.zones = current.followers.some((follower) => follower.claims !== void 0);
975
+ if (current.zones) current.floating = floatingOf(element, current.origin);
976
+ tellFollowers(current.followers, (follower) => follower.move?.(current.point));
977
+ }
978
+ /**
979
+ * Ends the gesture; `dropped` tells its followers a drop zone of theirs took it, and `landing`
980
+ * what the preview showed where a release in the view proposed the move.
981
+ */
982
+ function end(dropped = false, landing = null) {
983
+ const current = session;
984
+ if (current === null) return;
985
+ session = null;
986
+ if (current.placement !== null) getOptions().onPreview?.(null);
987
+ clearTimeout(current.longPress);
988
+ if (current.frame !== void 0) cancelAnimationFrame(current.frame);
989
+ current.ghost.clear();
990
+ region.removeAttribute("data-interaction");
991
+ if (current.gesture.kind !== "create") current.gesture.element.removeAttribute("data-dragging");
992
+ window.removeEventListener("pointermove", onPointerMove);
993
+ window.removeEventListener("pointerup", onPointerUp);
994
+ window.removeEventListener("pointercancel", onPointerCancel);
995
+ window.removeEventListener("keydown", onKeyDown, true);
996
+ current.touchTarget?.removeEventListener("touchmove", onTouchMove);
997
+ for (const type of [
998
+ "contextmenu",
999
+ "dragstart",
1000
+ "selectstart"
1001
+ ]) window.removeEventListener(type, preventDefault);
1002
+ tellFollowers(current.followers, (follower) => follower.end?.(dropped, landing));
1003
+ }
1004
+ /** Ends the gesture without proposing anything. */
1005
+ function cancel() {
1006
+ if (session?.active === true) announce(session, { phase: "cancel" });
1007
+ end();
1008
+ }
1009
+ /** Cancels when the browser takes over the gesture's own pointer, not another finger. */
1010
+ function onPointerCancel(event) {
1011
+ if (event.pointerId === session?.pointerId) cancel();
1012
+ }
1013
+ function proposal(current) {
1014
+ const { gesture, placement } = current;
1015
+ if (placement === null) return null;
1016
+ if (gesture.kind === "create") return {
1017
+ cause: "create",
1018
+ proposed: placement
1019
+ };
1020
+ if (samePlacement(placement, gesture.original)) return null;
1021
+ return {
1022
+ cause: gesture.kind === "move" ? "move" : gesture.edge === "start" ? "resize-start" : "resize-end",
1023
+ eventId: gesture.event.id,
1024
+ proposed: placement
1025
+ };
1026
+ }
1027
+ function onPointerMove(event) {
1028
+ const current = session;
1029
+ if (current === null || event.pointerId !== current.pointerId) return;
1030
+ current.point = {
1031
+ x: event.clientX,
1032
+ y: event.clientY
1033
+ };
1034
+ if (current.active) {
1035
+ tellFollowers(current.followers, (follower) => follower.move?.(current.point));
1036
+ trackEdges(current);
1037
+ if (preview(current)) announce(current, { phase: "step" });
1038
+ return;
1039
+ }
1040
+ const distance = Math.hypot(event.clientX - current.origin.x, event.clientY - current.origin.y);
1041
+ if (current.pointerType === "touch") {
1042
+ if (distance > TOUCH_TOLERANCE) end();
1043
+ } else if (distance > DRAG_DISTANCE) activate(current);
1044
+ }
1045
+ function onPointerUp(event) {
1046
+ const current = session;
1047
+ if (current === null || event.pointerId !== current.pointerId) return;
1048
+ if (!current.active) {
1049
+ end();
1050
+ return;
1051
+ }
1052
+ current.point = {
1053
+ x: event.clientX,
1054
+ y: event.clientY
1055
+ };
1056
+ tellFollowers(current.followers, (follower) => follower.move?.(current.point));
1057
+ preview(current, true);
1058
+ if (current.claimed) {
1059
+ end(true);
1060
+ suppressNextClick();
1061
+ return;
1062
+ }
1063
+ const proposed = proposal(current);
1064
+ end(false, proposed === null ? null : current.shown);
1065
+ suppressNextClick();
1066
+ if (proposed === null) {
1067
+ announce(current, { phase: "cancel" });
1068
+ return;
1069
+ }
1070
+ settleProposal(getOptions().onPropose(proposed, pointerInput), current.placement, (outcome) => announce(current, outcome));
1071
+ }
1072
+ function onKeyDown(event) {
1073
+ if (event.key !== "Escape" || session === null) return;
1074
+ event.preventDefault();
1075
+ event.stopPropagation();
1076
+ const wasActive = session.active;
1077
+ cancel();
1078
+ if (wasActive) window.addEventListener("pointerup", suppressNextClick, { once: true });
1079
+ }
1080
+ function gestureFor(pressed, target, events) {
1081
+ if (pressed.closest("[data-calendar-pointer=\"none\"]") !== null) return null;
1082
+ const element = pressed.closest("[data-event-id]");
1083
+ if (element === null || !region.contains(element)) return {
1084
+ anchor: target,
1085
+ kind: "create"
1086
+ };
1087
+ const event = resolveEvent(events, element);
1088
+ if (event === void 0 || event.isReadOnly) return null;
1089
+ const base = {
1090
+ element,
1091
+ event,
1092
+ grab: target,
1093
+ original: eventPlacement(event)
1094
+ };
1095
+ const handle = pressed.closest("[data-resize]");
1096
+ const edge = handle !== null && element.contains(handle) ? handle.getAttribute("data-resize") : null;
1097
+ return edge === "start" || edge === "end" ? {
1098
+ ...base,
1099
+ edge,
1100
+ kind: "resize"
1101
+ } : {
1102
+ ...base,
1103
+ kind: "move"
1104
+ };
1105
+ }
1106
+ function onPointerDown(event) {
1107
+ if (session !== null || event.button !== 0 || !event.isPrimary) return;
1108
+ const options = getOptions();
1109
+ if (options.disabled === true || !(event.target instanceof Element)) return;
1110
+ const surface = {
1111
+ clippers: /* @__PURE__ */ new Map(),
1112
+ columns: columnsByDate(options.columns),
1113
+ region
1114
+ };
1115
+ const target = targetAt(surface, event.clientX, event.clientY);
1116
+ const gesture = target === null ? null : gestureFor(event.target, target, options.events);
1117
+ if (gesture === null) return;
1118
+ const scrollContainer = options.scrollContainer?.current ?? scrollableAncestor(event.target);
1119
+ const current = {
1120
+ active: false,
1121
+ announcer: options.announcer,
1122
+ check: null,
1123
+ claimed: false,
1124
+ edges: new EdgeArming(true),
1125
+ followers: noFollowers,
1126
+ gesture,
1127
+ ghost: new GhostLayer(region, options.ghostClassName),
1128
+ options: {
1129
+ snap: options.snap ?? DEFAULT_SNAP$1,
1130
+ timeZone: options.timeZone
1131
+ },
1132
+ origin: {
1133
+ x: event.clientX,
1134
+ y: event.clientY
1135
+ },
1136
+ placement: null,
1137
+ point: {
1138
+ x: event.clientX,
1139
+ y: event.clientY
1140
+ },
1141
+ pointerId: event.pointerId,
1142
+ pointerType: event.pointerType,
1143
+ scrollContainer,
1144
+ shown: null,
1145
+ sideways: options.sidewaysScrollContainer?.current ?? scrollContainer,
1146
+ surface,
1147
+ surfaceColumns: options.columns,
1148
+ touchTarget: event.pointerType === "touch" && event.target !== region ? event.target : null,
1149
+ zones: false
1150
+ };
1151
+ session = current;
1152
+ window.addEventListener("pointermove", onPointerMove);
1153
+ window.addEventListener("pointerup", onPointerUp);
1154
+ window.addEventListener("pointercancel", onPointerCancel);
1155
+ window.addEventListener("keydown", onKeyDown, true);
1156
+ for (const type of [
1157
+ "contextmenu",
1158
+ "dragstart",
1159
+ "selectstart"
1160
+ ]) window.addEventListener(type, preventDefault);
1161
+ if (event.pointerType === "touch") {
1162
+ current.touchTarget?.addEventListener("touchmove", onTouchMove, { passive: false });
1163
+ current.longPress = setTimeout(() => activate(current), LONG_PRESS_MS);
1164
+ }
1165
+ }
1166
+ /**
1167
+ * Holds the page still under a drag that has started. The region listens from the start, not
1168
+ * from the long-press: Safari on iOS decides whether a touch can cancel scrolling when the touch
1169
+ * begins. A non-passive listener makes each touch on the region wait for the main thread before
1170
+ * it scrolls, so a region disabled when it's attached doesn't listen.
1171
+ */
1172
+ function onTouchMove(event) {
1173
+ if (session?.active === true) event.preventDefault();
1174
+ }
1175
+ region.addEventListener("pointerdown", onPointerDown);
1176
+ if (getOptions().disabled !== true) region.addEventListener("touchmove", onTouchMove, { passive: false });
1177
+ const unregister = registerRegion({
1178
+ element: region,
1179
+ getOptions
1180
+ });
1181
+ return () => {
1182
+ cancel();
1183
+ region.removeEventListener("pointerdown", onPointerDown);
1184
+ region.removeEventListener("touchmove", onTouchMove);
1185
+ unregister();
1186
+ };
1187
+ }
1188
+ //#endregion
1189
+ //#region src/drop.ts
1190
+ const DEFAULT_DURATION = { hours: 1 };
1191
+ const DEFAULT_SNAP = {
1192
+ increment: 15,
1193
+ smallestUnit: "minute"
1194
+ };
1195
+ function regionOver(region, hit, eventId) {
1196
+ const options = region.getOptions();
1197
+ const event = eventId === void 0 ? void 0 : options.events.get(eventId);
1198
+ const scrollContainer = options.scrollContainer?.current ?? scrollableAncestor(hit);
1199
+ return {
1200
+ edges: new EdgeArming(false),
1201
+ ghost: new GhostLayer(region.element, options.ghostClassName),
1202
+ moved: eventId === void 0 ? void 0 : event === void 0 || event.isReadOnly ? null : {
1203
+ event,
1204
+ original: eventPlacement(event)
1205
+ },
1206
+ options: {
1207
+ snap: options.snap ?? DEFAULT_SNAP,
1208
+ timeZone: options.timeZone
1209
+ },
1210
+ region,
1211
+ scrollContainer,
1212
+ sideways: options.sidewaysScrollContainer?.current ?? scrollContainer,
1213
+ surface: {
1214
+ clippers: /* @__PURE__ */ new Map(),
1215
+ columns: columnsByDate(options.columns),
1216
+ region: region.element
1217
+ },
1218
+ surfaceColumns: options.columns
1219
+ };
1220
+ }
1221
+ /**
1222
+ * Follows a drag that started outside the calendar, such as a task dragged from a list, over the
1223
+ * calendar views on the page, and drops it into one: the framework-agnostic half of external drag
1224
+ * and drop, which a drag library's binding drives. Every view that uses `useCalendarPointer` takes
1225
+ * part, through the options it passes: the preview shows range boxes in its slots, its `check`
1226
+ * marks them `data-invalid` or `data-warning`, its announcer speaks each step with `outside` set,
1227
+ * and its `onPropose` gets the drop. Read-only views take no part.
1228
+ *
1229
+ * Over a time column a drop creates a timed event starting at the slot under the point,
1230
+ * `duration` long; over day cells, an all-day event of `days` days. In a resource view it books
1231
+ * the resource it's dropped in. With `eventId`, it moves that event instead, unless it's
1232
+ * read-only.
1233
+ *
1234
+ * The topmost element under the point decides: anything over a view, such as a sheet or a
1235
+ * dialog, hides it. So the library's drag image must let the pointer through
1236
+ * (`pointer-events: none`), as dnd-kit's does. From the first `move` until `drop` or `cancel`, a
1237
+ * frame loop scrolls the view under the point near its edges, once the point has been clear of
1238
+ * them or rested at one for a moment, so crossing an edge on the way in doesn't scroll it.
1239
+ */
1240
+ function startCalendarDrop(source, { input = "pointer" } = {}) {
1241
+ const duration = Temporal.Duration.from(source.duration ?? DEFAULT_DURATION);
1242
+ if (duration.sign <= 0) throw new RangeError("calendar-drop-duration-must-be-positive");
1243
+ const days = source.days ?? 1;
1244
+ if (!Number.isInteger(days) || days < 1) throw new RangeError("calendar-drop-days-must-be-a-positive-integer");
1245
+ const detail = Object.freeze({ input });
1246
+ const outside = Object.freeze(source.title === void 0 ? {} : { title: source.title });
1247
+ let over = null;
1248
+ let heard = null;
1249
+ let point = null;
1250
+ let placement = null;
1251
+ let check = null;
1252
+ let frame;
1253
+ let ended = false;
1254
+ function item(current) {
1255
+ if (current.moved === void 0) return {
1256
+ days,
1257
+ duration,
1258
+ kind: "create"
1259
+ };
1260
+ return current.moved === null ? null : {
1261
+ kind: "move",
1262
+ original: current.moved.original
1263
+ };
1264
+ }
1265
+ function proposal(current) {
1266
+ if (placement === null) return null;
1267
+ if (current.moved === void 0) return {
1268
+ cause: "create",
1269
+ proposed: placement,
1270
+ ...source.event === void 0 ? {} : { event: source.event }
1271
+ };
1272
+ if (current.moved === null || samePlacement(placement, current.moved.original)) return null;
1273
+ return {
1274
+ cause: "move",
1275
+ eventId: source.eventId,
1276
+ proposed: placement
1277
+ };
1278
+ }
1279
+ function announce(to, phase, proposed = placement) {
1280
+ const { announcer } = to.region.getOptions();
1281
+ announcer?.announce({
1282
+ cause: to.moved === void 0 ? "create" : "move",
1283
+ event: to.moved?.event ?? null,
1284
+ input,
1285
+ original: to.moved?.original ?? null,
1286
+ outside,
1287
+ proposed,
1288
+ ...phase.phase === "start" || phase.phase === "step" ? { check } : void 0,
1289
+ ...phase
1290
+ });
1291
+ }
1292
+ /** Clears what the drag shows in the region it leaves. */
1293
+ function leave() {
1294
+ if (over === null) return;
1295
+ if (placement !== null) over.region.getOptions().onPreview?.(null);
1296
+ over.ghost.clear();
1297
+ over = null;
1298
+ }
1299
+ /** Follows the view's latest columns, as a view that renders more days as it scrolls has. */
1300
+ function refreshColumns(current) {
1301
+ const { columns } = current.region.getOptions();
1302
+ if (columns === current.surfaceColumns) return;
1303
+ current.surfaceColumns = columns;
1304
+ current.surface = {
1305
+ ...current.surface,
1306
+ columns: columnsByDate(columns)
1307
+ };
1308
+ }
1309
+ /** Previews the drop under the point; `scrolled` redraws it after the view scrolled. */
1310
+ function update(scrolled = false) {
1311
+ const hit = point === null ? null : regionAt(point.x, point.y);
1312
+ if (hit?.region !== over?.region) {
1313
+ const previous = placement;
1314
+ leave();
1315
+ placement = null;
1316
+ check = null;
1317
+ if (hit !== null) over = regionOver(hit.region, hit.element, source.eventId);
1318
+ if (previous !== null && heard !== null) announce(heard, { phase: "step" }, null);
1319
+ }
1320
+ const current = over;
1321
+ if (current === null || point === null) return;
1322
+ refreshColumns(current);
1323
+ const target = targetAt(current.surface, point.x, point.y);
1324
+ const dropped = target === null ? null : item(current);
1325
+ const next = target === null || dropped === null ? null : droppedPlacement(dropped, target, current.options);
1326
+ const changed = next === null ? placement !== null : placement === null || !samePlacement(placement, next);
1327
+ if (!changed && (!scrolled || next === null)) return;
1328
+ const options = current.region.getOptions();
1329
+ placement = next;
1330
+ if (next === null) {
1331
+ check = null;
1332
+ current.ghost.clear();
1333
+ options.onPreview?.(null);
1334
+ } else {
1335
+ if (changed) {
1336
+ const proposed = proposal(current);
1337
+ check = proposed === null ? null : options.check?.(proposed) ?? null;
1338
+ options.onPreview?.({
1339
+ eventId: source.eventId ?? null,
1340
+ proposed: next
1341
+ });
1342
+ }
1343
+ const layout = ghostLayout(current.surface, next, current.options.timeZone);
1344
+ current.ghost.render(layout.rects, null, null, ghostValidity(check));
1345
+ }
1346
+ if (!changed) return;
1347
+ if (next !== null && heard?.region !== current.region) {
1348
+ heard = {
1349
+ moved: current.moved,
1350
+ region: current.region
1351
+ };
1352
+ announce(heard, { phase: "start" });
1353
+ } else if (heard !== null) announce(heard, { phase: "step" }, heard.region === current.region ? next : null);
1354
+ }
1355
+ /** Whether the view's edges may scroll it yet; see `EdgeArming`. */
1356
+ function arm() {
1357
+ if (over === null || point === null) return false;
1358
+ return over.edges.update(over.scrollContainer, point.x, point.y, performance.now());
1359
+ }
1360
+ function scrollFrame() {
1361
+ frame = void 0;
1362
+ if (ended) return;
1363
+ if (over !== null && !takesDrops(over.region)) update();
1364
+ if (arm() && over !== null && point !== null) {
1365
+ if (autoScroll(over.scrollContainer, point.x, point.y, over.sideways)) update(true);
1366
+ }
1367
+ frame = requestAnimationFrame(scrollFrame);
1368
+ }
1369
+ /** Stops the drag; returns the region it was over. */
1370
+ function end() {
1371
+ const last = over;
1372
+ ended = true;
1373
+ if (frame !== void 0) cancelAnimationFrame(frame);
1374
+ frame = void 0;
1375
+ leave();
1376
+ placement = null;
1377
+ return last;
1378
+ }
1379
+ return {
1380
+ cancel() {
1381
+ if (ended) return;
1382
+ end();
1383
+ if (heard !== null) announce(heard, { phase: "cancel" });
1384
+ },
1385
+ drop() {
1386
+ if (ended) return Promise.resolve(null);
1387
+ const landed = placement;
1388
+ const target = over !== null && takesDrops(over.region) ? over : null;
1389
+ const proposed = target === null ? null : proposal(target);
1390
+ end();
1391
+ if (target === null || proposed === null || landed === null) {
1392
+ if (heard !== null) announce(heard, { phase: "cancel" }, null);
1393
+ return Promise.resolve(null);
1394
+ }
1395
+ const { onPropose } = target.region.getOptions();
1396
+ const to = heard ?? {
1397
+ moved: target.moved,
1398
+ region: target.region
1399
+ };
1400
+ return settleProposal(onPropose(proposed, detail), landed, (outcome) => announce(to, outcome, landed));
1401
+ },
1402
+ move(next) {
1403
+ if (ended) return;
1404
+ point = next;
1405
+ update();
1406
+ arm();
1407
+ frame ??= requestAnimationFrame(scrollFrame);
1408
+ },
1409
+ get placement() {
1410
+ return placement;
1411
+ }
1412
+ };
1413
+ }
1414
+ //#endregion
1415
+ //#region src/use-calendar-pointer.ts
1416
+ /**
1417
+ * Pointer move, resize, and create for a view region; see `attachCalendarPointer` for the data
1418
+ * attributes the view renders. Returns a ref for the region element. Options are read when a
1419
+ * gesture starts, and `columns` again as it moves, so changing them never re-attaches listeners,
1420
+ * and dragging never re-renders. `disabled` is the exception: a disabled region doesn't listen for
1421
+ * touch moves, so a read-only calendar's swipes never wait for its listener, and changing it
1422
+ * attaches the listeners again.
1423
+ */
1424
+ function useCalendarPointer(options) {
1425
+ const latest = useRef(options);
1426
+ useInsertionEffect(() => {
1427
+ latest.current = options;
1428
+ });
1429
+ const disabled = options.disabled === true;
1430
+ return useCallback((element) => element === null ? void 0 : attachCalendarPointer(element, () => latest.current), [disabled]);
1431
+ }
1432
+ //#endregion
1433
+ export { attachCalendarPointer, eventIdAttributes, eventIdOf, monitorCalendarDrags, observeCalendarRegions, resourceIdAttributes, resourceIdOf, startCalendarDrop, useCalendarPointer };