@c9up/nebula 0.2.5 → 0.2.6

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.
@@ -0,0 +1,762 @@
1
+ /**
2
+ * Agenda — a time grid of columns, with ranges behind and events on top.
3
+ *
4
+ * shadcn has no agenda; the usual React ones (FullCalendar, react-big-calendar)
5
+ * are whole libraries. This one keeps to what a booking screen needs: a day,
6
+ * a week, or several people side by side, with events that move and stretch
7
+ * by pointer and by keyboard alike.
8
+ *
9
+ * **Columns are the caller's.** A column is a key and a label: a day of the
10
+ * week, a practitioner on one day, a room. The agenda does not know whether it
11
+ * shows a week or a team, so the same component is the week of one person,
12
+ * the day of five, or five days of two. A column that carries a `date` gets
13
+ * the today mark and the now line.
14
+ *
15
+ * **Times are wall-clock text.** `"08:30"`, never a `Date`: a slot at half past
16
+ * eight is half past eight wherever the page is rendered, and a server in UTC
17
+ * hydrating for a browser in Zurich must draw the same grid. Dates, when a
18
+ * column has one, are `YYYY-MM-DD`.
19
+ *
20
+ * **Controlled.** Moving or stretching an event calls `onMove` or `onResize`
21
+ * with where it was dropped; the agenda never moves it itself. The caller
22
+ * updates `events` (at once, or once the server agrees) or does not, and the
23
+ * event goes back. A refused move therefore needs no undo.
24
+ *
25
+ * **Geometry.** The hour rows are real elements of a fixed height class, so the
26
+ * grid has its size in the server's markup. Ranges and events are placed in
27
+ * percentages of the grid through the CSSOM (`.style`), which a strict
28
+ * Content-Security-Policy does not govern; the server cannot write them, so
29
+ * they stay hidden until the agenda is mounted rather than drawn in the wrong
30
+ * place.
31
+ *
32
+ * **Keyboard.** One event is tabbable. The arrows walk the events — up and
33
+ * down within a column, left and right to the nearest one in the next column
34
+ * — Enter activates one, Space picks it up. Picked up, the arrows move it by
35
+ * the snap and across columns, Shift with Up or Down changes its end, Enter or
36
+ * Space drops it, Escape puts it back. Every step is announced.
37
+ */
38
+ import { component, each, html, onMount, onUnmount, signal, } from "@c9up/aurora";
39
+ import { cn } from "../lib/cn.js";
40
+ import { uid } from "../lib/id.js";
41
+ import { read } from "../lib/props.js";
42
+ const DEFAULT_LABELS = {
43
+ keyboardHint: "Arrow keys go from event to event. Enter opens one, Space picks it up.",
44
+ grabbed: "{title} picked up. Arrow keys move it, Shift with Up or Down changes its end, Enter drops it, Escape puts it back.",
45
+ moved: "{title}: {column}, {start} to {end}.",
46
+ cancelled: "{title} put back.",
47
+ now: "Now",
48
+ resize: "Change the end of {title}",
49
+ };
50
+ // ─── time and layout (pure) ──────────────────────────────────────────
51
+ const CLOCK = /^([01]\d|2[0-4]):([0-5]\d)$/;
52
+ /** Minutes since midnight of `HH:mm`, or `null` when it is not one. */
53
+ export function minutesOf(clock) {
54
+ const match = CLOCK.exec(clock);
55
+ if (match === null)
56
+ return null;
57
+ const minutes = Number(match[1]) * 60 + Number(match[2]);
58
+ return minutes > 24 * 60 ? null : minutes;
59
+ }
60
+ /** `HH:mm` of minutes since midnight. */
61
+ export function clockOf(minutes) {
62
+ const hours = Math.floor(minutes / 60);
63
+ const rest = minutes % 60;
64
+ return `${String(hours).padStart(2, "0")}:${String(rest).padStart(2, "0")}`;
65
+ }
66
+ /** `YYYY-MM-DD` of a date, on its own wall clock. */
67
+ export function isoDay(date) {
68
+ return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`;
69
+ }
70
+ /**
71
+ * Side-by-side lanes for the events of one column.
72
+ *
73
+ * Events that overlap, directly or through a chain, form a cluster; each takes
74
+ * the first lane free at its start, and every event of the cluster is drawn
75
+ * at the width of the cluster's lane count. Touching is not overlapping: an
76
+ * event ending at 09:00 and one starting at 09:00 share a lane.
77
+ */
78
+ export function lanesOf(events) {
79
+ const sorted = [...events].sort((a, b) => a.start - b.start || b.end - a.end || a.key.localeCompare(b.key));
80
+ const result = new Map();
81
+ let cluster = [];
82
+ let laneEnds = [];
83
+ let clusterEnd = Number.NEGATIVE_INFINITY;
84
+ const close = () => {
85
+ for (const member of cluster) {
86
+ result.set(member.key, { lane: member.lane, lanes: laneEnds.length });
87
+ }
88
+ cluster = [];
89
+ laneEnds = [];
90
+ };
91
+ for (const event of sorted) {
92
+ if (event.start >= clusterEnd)
93
+ close();
94
+ let lane = laneEnds.findIndex((end) => end <= event.start);
95
+ if (lane === -1) {
96
+ lane = laneEnds.length;
97
+ laneEnds.push(event.end);
98
+ }
99
+ else {
100
+ laneEnds[lane] = event.end;
101
+ }
102
+ cluster.push({ key: event.key, lane });
103
+ clusterEnd = Math.max(clusterEnd, event.end);
104
+ }
105
+ close();
106
+ return result;
107
+ }
108
+ /** `value` down to a multiple of `snap`. */
109
+ export function snapDown(value, snap) {
110
+ return Math.floor(value / snap) * snap;
111
+ }
112
+ /** `value` to the nearest multiple of `snap`. */
113
+ export function snapNearest(value, snap) {
114
+ return Math.round(value / snap) * snap;
115
+ }
116
+ /**
117
+ * A move kept within the grid: the start between the first hour and the
118
+ * last minus the duration, the duration unchanged.
119
+ */
120
+ export function clampMove(start, duration, from, to) {
121
+ const kept = Math.min(Math.max(start, from), Math.max(from, to - duration));
122
+ return { start: kept, end: kept + duration };
123
+ }
124
+ /** A new end kept after the start by one snap at least, and within the grid. */
125
+ export function clampEnd(start, end, snap, to) {
126
+ return Math.min(Math.max(end, start + snap), to);
127
+ }
128
+ /** Replace `{name}` placeholders. */
129
+ function fill(template, values) {
130
+ return template.replace(/\{(\w+)\}/g, (whole, name) => Object.hasOwn(values, name) ? (values[name] ?? whole) : whole);
131
+ }
132
+ const HOUR_HEIGHT = {
133
+ sm: "h-12",
134
+ md: "h-20",
135
+ lg: "h-32",
136
+ };
137
+ /**
138
+ * An event is opaque: the card's colour underneath, the tone's tint laid
139
+ * over it as a background image. A translucent fill alone let a range's
140
+ * label show through the event above it.
141
+ */
142
+ const EVENT_TONES = {
143
+ default: "bg-card text-card-foreground border-border",
144
+ primary: "bg-card bg-linear-to-r from-primary/15 to-primary/15 text-foreground border-primary",
145
+ success: "bg-card bg-linear-to-r from-emerald-500/15 to-emerald-500/15 text-foreground border-emerald-600 dark:border-emerald-400",
146
+ warning: "bg-card bg-linear-to-r from-amber-500/15 to-amber-500/15 text-foreground border-amber-600 dark:border-amber-400",
147
+ danger: "bg-card bg-linear-to-r from-destructive/15 to-destructive/15 text-foreground border-destructive",
148
+ muted: "bg-muted text-muted-foreground border-muted-foreground/40",
149
+ };
150
+ const RANGE_TONES = {
151
+ default: "bg-accent/40",
152
+ primary: "bg-primary/10",
153
+ success: "bg-emerald-500/10",
154
+ warning: "bg-amber-500/10",
155
+ danger: "bg-destructive/10",
156
+ muted: "bg-muted/60",
157
+ };
158
+ const HATCHED = "bg-[repeating-linear-gradient(135deg,transparent_0_6px,var(--color-border)_6px_8px)]";
159
+ // ─── component ───────────────────────────────────────────────────────
160
+ export const Agenda = component((props) => {
161
+ const labels = { ...DEFAULT_LABELS, ...props.labels };
162
+ const [firstHour, lastHour] = props.hours ?? [7, 20];
163
+ const from = firstHour * 60;
164
+ const to = lastHour * 60;
165
+ const span = Math.max(60, to - from);
166
+ const step = props.step ?? 15;
167
+ const snap = props.snap ?? step;
168
+ const clock = props.now ?? (() => new Date());
169
+ const areaId = uid("agenda-area");
170
+ const hintId = uid("agenda-hint");
171
+ const bodyId = uid("agenda-body");
172
+ const columns = () => read(props.columns);
173
+ const events = () => read(props.events);
174
+ const ranges = () => read(props.ranges) ?? [];
175
+ /** Placed once mounted: before that, ranges and events have no geometry. */
176
+ const placed = signal(false);
177
+ /** The event the keyboard is on; the only tabbable one. */
178
+ const cursor = signal(null);
179
+ /** The event being held, by keyboard or pointer, and where it is drawn. */
180
+ const draft = signal(null);
181
+ /** Held by the keyboard (as opposed to the pointer). */
182
+ const grabbed = signal(false);
183
+ const announcement = signal("");
184
+ const nowTick = signal(clock());
185
+ const hourFormat = new Intl.DateTimeFormat(props.locale, {
186
+ hour: "2-digit",
187
+ minute: "2-digit",
188
+ timeZone: "UTC",
189
+ });
190
+ const hourLabel = (minutes) => hourFormat.format(new Date(Date.UTC(2000, 0, 1, 0, minutes)));
191
+ const columnIndex = (key) => columns().findIndex((c) => c.key === key);
192
+ const columnLabel = (key) => columns().find((c) => c.key === key)?.label ?? key;
193
+ /** The events that can be drawn: in a known column, with valid times. */
194
+ const drawable = () => events().flatMap((event) => {
195
+ const start = minutesOf(event.start);
196
+ const end = minutesOf(event.end);
197
+ if (start === null || end === null || end <= start)
198
+ return [];
199
+ if (columnIndex(event.column) === -1)
200
+ return [];
201
+ if (end <= from || start >= to)
202
+ return [];
203
+ return [{ event, start, end }];
204
+ });
205
+ /** Lanes per event, each column apart. */
206
+ const lanes = () => {
207
+ const all = new Map();
208
+ const byColumn = new Map();
209
+ for (const { event, start, end } of drawable()) {
210
+ const list = byColumn.get(event.column) ?? [];
211
+ list.push({ key: event.key, start, end });
212
+ byColumn.set(event.column, list);
213
+ }
214
+ for (const list of byColumn.values()) {
215
+ for (const [key, lane] of lanesOf(list))
216
+ all.set(key, lane);
217
+ }
218
+ return all;
219
+ };
220
+ const percent = (value) => `${(value * 100).toFixed(4)}%`;
221
+ /** The CSS placing a span of `column` from `start` to `end`, in a lane. */
222
+ function geometry(column, start, end, lane = { lane: 0, lanes: 1 }) {
223
+ const count = Math.max(1, columns().length);
224
+ const index = Math.max(0, columnIndex(column));
225
+ const top = (Math.max(start, from) - from) / span;
226
+ const height = (Math.min(end, to) - Math.max(start, from)) / span;
227
+ const left = (index + lane.lane / lane.lanes) / count;
228
+ const width = 1 / count / lane.lanes;
229
+ // A point in time (the now line) has no height of its own: its class gives it one.
230
+ const tall = end > start ? `height:${percent(height)};` : "";
231
+ return `top:${percent(top)};${tall}left:${percent(left)};width:${percent(width)}`;
232
+ }
233
+ function say(template, values) {
234
+ announcement(fill(template, values));
235
+ }
236
+ const current = (key) => events().find((e) => e.key === key);
237
+ // ─── holding an event ────────────────────────────────────────────
238
+ function pickUp(event) {
239
+ const start = minutesOf(event.start);
240
+ const end = minutesOf(event.end);
241
+ if (start === null || end === null)
242
+ return false;
243
+ draft({ key: event.key, column: event.column, start, end });
244
+ return true;
245
+ }
246
+ function drop() {
247
+ const held = draft();
248
+ draft(null);
249
+ grabbed(false);
250
+ if (held === null)
251
+ return;
252
+ const event = current(held.key);
253
+ if (event === undefined)
254
+ return;
255
+ const change = {
256
+ event,
257
+ column: held.column,
258
+ start: clockOf(held.start),
259
+ end: clockOf(held.end),
260
+ };
261
+ const moved = change.column !== event.column || change.start !== event.start;
262
+ const stretched = change.end !== event.end;
263
+ say(labels.moved, {
264
+ title: event.title,
265
+ column: columnLabel(change.column),
266
+ start: change.start,
267
+ end: change.end,
268
+ });
269
+ if (moved)
270
+ props.onMove?.(change);
271
+ else if (stretched)
272
+ props.onResize?.(change);
273
+ }
274
+ function putBack() {
275
+ const held = draft();
276
+ draft(null);
277
+ grabbed(false);
278
+ const event = held === null ? undefined : current(held.key);
279
+ if (event !== undefined)
280
+ say(labels.cancelled, { title: event.title });
281
+ }
282
+ function announceDraft() {
283
+ const held = draft();
284
+ const event = held === null ? undefined : current(held.key);
285
+ if (held === null || event === undefined)
286
+ return;
287
+ say(labels.moved, {
288
+ title: event.title,
289
+ column: columnLabel(held.column),
290
+ start: clockOf(held.start),
291
+ end: clockOf(held.end),
292
+ });
293
+ }
294
+ // ─── keyboard ────────────────────────────────────────────────────
295
+ function focusEvent(key) {
296
+ cursor(key);
297
+ queueMicrotask(() => {
298
+ const area = document.getElementById(areaId);
299
+ const target = [
300
+ ...(area?.querySelectorAll('[data-slot="agenda-event"]') ??
301
+ []),
302
+ ].find((element) => element.dataset.key === key);
303
+ target?.focus();
304
+ });
305
+ }
306
+ /** The event the arrows lead to from `event`, or `undefined`. */
307
+ function neighbour(event, key) {
308
+ const all = drawable();
309
+ const startOf = (e) => minutesOf(e.start) ?? 0;
310
+ const inColumn = (column) => all
311
+ .filter((d) => d.event.column === column)
312
+ .map((d) => d.event)
313
+ .sort((a, b) => startOf(a) - startOf(b) || a.key.localeCompare(b.key));
314
+ const ordered = columns().flatMap((c) => inColumn(c.key));
315
+ if (key === "Home")
316
+ return ordered[0];
317
+ if (key === "End")
318
+ return ordered[ordered.length - 1];
319
+ if (key === "ArrowUp" || key === "ArrowDown") {
320
+ const list = inColumn(event.column);
321
+ const at = list.findIndex((e) => e.key === event.key);
322
+ return list[at + (key === "ArrowUp" ? -1 : 1)];
323
+ }
324
+ const direction = key === "ArrowLeft" ? -1 : 1;
325
+ const cols = columns();
326
+ for (let index = columnIndex(event.column) + direction; index >= 0 && index < cols.length; index += direction) {
327
+ const column = cols[index];
328
+ if (column === undefined)
329
+ break;
330
+ const list = inColumn(column.key);
331
+ if (list.length === 0)
332
+ continue;
333
+ const target = startOf(event);
334
+ return list.reduce((best, e) => Math.abs(startOf(e) - target) < Math.abs(startOf(best) - target)
335
+ ? e
336
+ : best);
337
+ }
338
+ return undefined;
339
+ }
340
+ function onEventKeyDown(event, e) {
341
+ const held = draft();
342
+ if (grabbed() && held !== null) {
343
+ heldKeyDown(event, held, e);
344
+ return;
345
+ }
346
+ if (e.key === "Enter") {
347
+ e.preventDefault();
348
+ props.onActivate?.(event);
349
+ return;
350
+ }
351
+ if (e.key === " ") {
352
+ e.preventDefault();
353
+ if ((event.movable === true || event.resizable === true) &&
354
+ pickUp(event)) {
355
+ grabbed(true);
356
+ say(labels.grabbed, { title: event.title });
357
+ }
358
+ else {
359
+ props.onActivate?.(event);
360
+ }
361
+ return;
362
+ }
363
+ if ([
364
+ "ArrowUp",
365
+ "ArrowDown",
366
+ "ArrowLeft",
367
+ "ArrowRight",
368
+ "Home",
369
+ "End",
370
+ ].includes(e.key)) {
371
+ e.preventDefault();
372
+ const next = neighbour(event, e.key);
373
+ if (next !== undefined)
374
+ focusEvent(next.key);
375
+ }
376
+ }
377
+ function heldKeyDown(event, held, e) {
378
+ const duration = held.end - held.start;
379
+ const cols = columns();
380
+ let next = null;
381
+ if (e.key === "Escape") {
382
+ e.preventDefault();
383
+ putBack();
384
+ return;
385
+ }
386
+ if (e.key === "Enter" || e.key === " ") {
387
+ e.preventDefault();
388
+ drop();
389
+ return;
390
+ }
391
+ if ((e.key === "ArrowUp" || e.key === "ArrowDown") && e.shiftKey) {
392
+ if (event.resizable !== true)
393
+ return;
394
+ const end = clampEnd(held.start, held.end + (e.key === "ArrowUp" ? -snap : snap), snap, to);
395
+ next = { ...held, end };
396
+ }
397
+ else if (e.key === "ArrowUp" || e.key === "ArrowDown") {
398
+ if (event.movable !== true)
399
+ return;
400
+ const moved = clampMove(held.start + (e.key === "ArrowUp" ? -snap : snap), duration, from, to);
401
+ next = { ...held, ...moved };
402
+ }
403
+ else if (e.key === "ArrowLeft" || e.key === "ArrowRight") {
404
+ if (event.movable !== true)
405
+ return;
406
+ const index = columnIndex(held.column) + (e.key === "ArrowLeft" ? -1 : 1);
407
+ const column = cols[index];
408
+ if (column === undefined)
409
+ return;
410
+ next = { ...held, column: column.key };
411
+ }
412
+ else if (e.key === "Tab") {
413
+ putBack();
414
+ return;
415
+ }
416
+ if (next === null)
417
+ return;
418
+ e.preventDefault();
419
+ draft(next);
420
+ announceDraft();
421
+ }
422
+ // ─── pointer ─────────────────────────────────────────────────────
423
+ /** The column and minute under a point of the area, unsnapped. */
424
+ function pointAt(x, y) {
425
+ const area = document.getElementById(areaId);
426
+ const cols = columns();
427
+ if (area === null || cols.length === 0)
428
+ return null;
429
+ const rect = area.getBoundingClientRect();
430
+ if (rect.width <= 0 || rect.height <= 0)
431
+ return null;
432
+ const index = Math.min(cols.length - 1, Math.max(0, Math.floor(((x - rect.left) / rect.width) * cols.length)));
433
+ const column = cols[index];
434
+ if (column === undefined)
435
+ return null;
436
+ return {
437
+ column: column.key,
438
+ minutes: from + ((y - rect.top) / rect.height) * span,
439
+ };
440
+ }
441
+ /** A pointer gesture in progress. */
442
+ let gesture = null;
443
+ /** A drag ends in a click on the same element: that click is not an activation. */
444
+ let swallowClick = false;
445
+ function onPointerDown(event, mode, e) {
446
+ if (e.button !== 0)
447
+ return;
448
+ if (mode === "move" && event.movable !== true)
449
+ return;
450
+ if (mode === "resize" && event.resizable !== true)
451
+ return;
452
+ const point = pointAt(e.clientX, e.clientY);
453
+ const start = minutesOf(event.start);
454
+ if (point === null || start === null)
455
+ return;
456
+ if (mode === "resize")
457
+ e.stopPropagation();
458
+ gesture = {
459
+ key: event.key,
460
+ mode,
461
+ pointerX: e.clientX,
462
+ pointerY: e.clientY,
463
+ offset: point.minutes - start,
464
+ started: false,
465
+ };
466
+ const target = e.currentTarget;
467
+ if (target instanceof Element)
468
+ target.setPointerCapture?.(e.pointerId);
469
+ }
470
+ function onPointerMove(e) {
471
+ if (gesture === null)
472
+ return;
473
+ if (!gesture.started) {
474
+ const distance = Math.hypot(e.clientX - gesture.pointerX, e.clientY - gesture.pointerY);
475
+ if (distance < 4)
476
+ return;
477
+ const event = current(gesture.key);
478
+ if (event === undefined || !pickUp(event)) {
479
+ gesture = null;
480
+ return;
481
+ }
482
+ gesture.started = true;
483
+ }
484
+ const held = draft();
485
+ const point = pointAt(e.clientX, e.clientY);
486
+ if (held === null || point === null)
487
+ return;
488
+ if (gesture.mode === "resize") {
489
+ draft({
490
+ ...held,
491
+ end: clampEnd(held.start, snapNearest(point.minutes, snap), snap, to),
492
+ });
493
+ return;
494
+ }
495
+ const moved = clampMove(snapNearest(point.minutes - gesture.offset, snap), held.end - held.start, from, to);
496
+ draft({ ...held, column: point.column, ...moved });
497
+ }
498
+ function onPointerUp() {
499
+ if (gesture === null)
500
+ return;
501
+ const started = gesture.started;
502
+ gesture = null;
503
+ if (!started)
504
+ return;
505
+ // The click that follows this release, if it lands, is the drag's own.
506
+ swallowClick = true;
507
+ setTimeout(() => {
508
+ swallowClick = false;
509
+ }, 0);
510
+ drop();
511
+ }
512
+ function onPointerCancel() {
513
+ if (gesture === null)
514
+ return;
515
+ const started = gesture.started;
516
+ gesture = null;
517
+ if (started)
518
+ putBack();
519
+ }
520
+ function onAreaKeyDown(e) {
521
+ if (e.key === "Escape" && gesture !== null) {
522
+ gesture = null;
523
+ putBack();
524
+ }
525
+ }
526
+ function onAreaClick(e) {
527
+ if (props.onSlotActivate === undefined)
528
+ return;
529
+ const target = e.target;
530
+ if (target instanceof Element &&
531
+ target.closest("[data-slot='agenda-event'],[data-slot='agenda-range-label']") !== null)
532
+ return;
533
+ const point = pointAt(e.clientX, e.clientY);
534
+ if (point === null)
535
+ return;
536
+ const start = snapDown(point.minutes, snap);
537
+ if (start < from || start >= to)
538
+ return;
539
+ props.onSlotActivate({ column: point.column, start: clockOf(start) });
540
+ }
541
+ function onEventClick(event) {
542
+ if (swallowClick) {
543
+ swallowClick = false;
544
+ return;
545
+ }
546
+ cursor(event.key);
547
+ props.onActivate?.(event);
548
+ }
549
+ // ─── mount ───────────────────────────────────────────────────────
550
+ let timer;
551
+ onMount(() => {
552
+ placed(true);
553
+ timer = setInterval(() => nowTick(clock()), 60_000);
554
+ const body = document.getElementById(bodyId);
555
+ const first = [
556
+ ...ranges().map((r) => minutesOf(r.start)),
557
+ ...events().map((e) => minutesOf(e.start)),
558
+ ].filter((m) => m !== null && m >= from && m < to);
559
+ const target = props.scrollTo === undefined
560
+ ? first.length === 0
561
+ ? null
562
+ : Math.min(...first)
563
+ : minutesOf(props.scrollTo);
564
+ if (body !== null && target !== null) {
565
+ const area = document.getElementById(areaId);
566
+ const height = area?.getBoundingClientRect().height ?? 0;
567
+ body.scrollTop = Math.max(0, ((target - from) / span) * height - 16);
568
+ }
569
+ });
570
+ onUnmount(() => {
571
+ if (timer !== undefined)
572
+ clearInterval(timer);
573
+ });
574
+ // ─── rendering ───────────────────────────────────────────────────
575
+ const hours = Array.from({ length: Math.ceil(span / 60) }, (_unused, index) => from + index * 60);
576
+ const lines = Math.max(1, Math.round(60 / step));
577
+ const rowHeight = HOUR_HEIGHT[props.size ?? "md"];
578
+ /** The tabbable event: the cursor, else the first drawn. */
579
+ const tabbable = () => {
580
+ const all = drawable();
581
+ const at = cursor();
582
+ if (at !== null && all.some((d) => d.event.key === at))
583
+ return at;
584
+ return all[0]?.event.key ?? null;
585
+ };
586
+ const today = () => isoDay(nowTick());
587
+ function nowLine() {
588
+ const at = nowTick();
589
+ const minutes = at.getHours() * 60 + at.getMinutes();
590
+ const column = columns().find((c) => c.date === today());
591
+ if (column === undefined || minutes < from || minutes >= to || !placed())
592
+ return null;
593
+ return html `<div
594
+ data-slot="agenda-now"
595
+ aria-hidden="true"
596
+ title="${labels.now}"
597
+ class="bg-destructive pointer-events-none absolute z-20 h-0.5"
598
+ .style="${geometry(column.key, minutes, minutes)}"
599
+ ></div>`;
600
+ }
601
+ function renderRange(range) {
602
+ const style = () => {
603
+ const r = range();
604
+ const start = minutesOf(r.start) ?? from;
605
+ const end = minutesOf(r.end) ?? start;
606
+ return geometry(r.column, start, end);
607
+ };
608
+ const visible = () => {
609
+ const r = range();
610
+ const start = minutesOf(r.start);
611
+ const end = minutesOf(r.end);
612
+ return (placed() &&
613
+ start !== null &&
614
+ end !== null &&
615
+ end > start &&
616
+ columnIndex(r.column) !== -1 &&
617
+ end > from &&
618
+ start < to);
619
+ };
620
+ const label = () => {
621
+ const r = range();
622
+ if (r.label === undefined)
623
+ return null;
624
+ if (props.onRangeActivate === undefined) {
625
+ return html `<span class="text-muted-foreground block truncate px-1 pt-0.5 text-[0.7rem]">${r.label}</span>`;
626
+ }
627
+ return html `<button
628
+ type="button"
629
+ data-slot="agenda-range-label"
630
+ class="text-muted-foreground hover:text-foreground focus-visible:ring-ring/50 pointer-events-auto block max-w-full truncate rounded px-1 pt-0.5 text-left text-[0.7rem] outline-none focus-visible:ring-[3px]"
631
+ @click="${() => props.onRangeActivate?.(range())}"
632
+ >${r.label}</button>`;
633
+ };
634
+ return html `<div
635
+ data-slot="agenda-range"
636
+ data-key="${() => range().key}"
637
+ ?hidden="${() => !visible()}"
638
+ class="${() => cn("pointer-events-none absolute z-0 border-l-2 border-transparent", RANGE_TONES[range().tone ?? "default"], range().hatched === true ? HATCHED : "")}"
639
+ .style="${style}"
640
+ >${label}</div>`;
641
+ }
642
+ function renderEvent(event) {
643
+ const held = () => {
644
+ const d = draft();
645
+ return d !== null && d.key === event().key ? d : null;
646
+ };
647
+ const style = () => {
648
+ const e = event();
649
+ const d = held();
650
+ const lane = d === null ? lanes().get(e.key) : undefined;
651
+ const start = d?.start ?? minutesOf(e.start) ?? from;
652
+ const end = d?.end ?? minutesOf(e.end) ?? start;
653
+ const accent = e.accent === undefined ? "" : `;border-left-color:${e.accent}`;
654
+ return `${geometry(d?.column ?? e.column, start, end, lane)}${accent}`;
655
+ };
656
+ const times = () => {
657
+ const d = held();
658
+ const e = event();
659
+ return d === null
660
+ ? `${e.start}–${e.end}`
661
+ : `${clockOf(d.start)}–${clockOf(d.end)}`;
662
+ };
663
+ const name = () => {
664
+ const e = event();
665
+ return [e.title, e.detail, columnLabel(e.column), `${e.start}–${e.end}`]
666
+ .filter((part) => part !== undefined && part !== "")
667
+ .join(", ");
668
+ };
669
+ const content = () => props.renderEvent === undefined
670
+ ? html `<span class="block truncate text-[0.7rem] tabular-nums opacity-80">${times}</span>
671
+ <span class="${() => cn("block truncate font-medium", event().struck === true ? "line-through" : "")}">${() => event().title}</span>
672
+ ${() => (event().detail === undefined ? null : html `<span class="text-muted-foreground block truncate">${() => event().detail}</span>`)}`
673
+ : props.renderEvent(event);
674
+ return html `<div
675
+ data-slot="agenda-event"
676
+ data-key="${() => event().key}"
677
+ data-tone="${() => event().tone ?? "default"}"
678
+ data-held="${() => (held() === null ? undefined : "")}"
679
+ role="button"
680
+ aria-label="${name}"
681
+ aria-describedby="${hintId}"
682
+ aria-pressed="${() => (held() !== null && grabbed() ? "true" : undefined)}"
683
+ tabindex="${() => (tabbable() === event().key ? 0 : -1)}"
684
+ ?hidden="${() => !placed()}"
685
+ class="${() => cn("group absolute z-10 cursor-default overflow-hidden rounded-md border border-l-4 px-1.5 py-0.5 text-xs leading-tight shadow-xs outline-none select-none", "focus-visible:ring-ring/50 focus-visible:z-30 focus-visible:ring-[3px]", EVENT_TONES[event().tone ?? "default"], event().movable === true ? "cursor-grab touch-none" : "", held() === null
686
+ ? ""
687
+ : "z-30 cursor-grabbing opacity-90 shadow-lg ring-2 ring-primary")}"
688
+ .style="${style}"
689
+ @click="${() => onEventClick(event())}"
690
+ @focus="${() => cursor(event().key)}"
691
+ @blur="${() => {
692
+ if (grabbed() && held() !== null)
693
+ putBack();
694
+ }}"
695
+ @keydown="${(e) => onEventKeyDown(event(), e)}"
696
+ @pointerdown="${(e) => onPointerDown(event(), "move", e)}"
697
+ >${content}${() => event().resizable === true
698
+ ? html `<span
699
+ data-slot="agenda-resize"
700
+ aria-hidden="true"
701
+ title="${() => fill(labels.resize, { title: event().title })}"
702
+ class="absolute inset-x-0 bottom-0 h-1.5 cursor-ns-resize touch-none opacity-0 group-hover:opacity-100 bg-foreground/20"
703
+ @pointerdown="${(e) => onPointerDown(event(), "resize", e)}"
704
+ ></span>`
705
+ : null}</div>`;
706
+ }
707
+ function renderHeader(column) {
708
+ const isToday = () => column().date !== undefined && column().date === today();
709
+ return html `<div
710
+ data-slot="agenda-column"
711
+ data-key="${() => column().key}"
712
+ data-today="${() => (isToday() ? "" : undefined)}"
713
+ data-holiday="${() => (column().holiday === true ? "" : undefined)}"
714
+ class="${() => cn("min-w-0 flex-1 border-l px-2 py-1.5 text-center", column().holiday === true ? "bg-amber-500/10" : "")}"
715
+ >
716
+ <span class="${() => cn("block truncate text-sm font-medium", isToday() ? "text-primary" : "")}">${() => column().label}</span>
717
+ ${() => (column().hint === undefined ? null : html `<span class="text-muted-foreground block truncate text-xs">${() => column().hint}</span>`)}
718
+ </div>`;
719
+ }
720
+ function renderColumnLines(column) {
721
+ return html `<div
722
+ data-key="${() => column().key}"
723
+ class="${() => cn("min-w-0 flex-1 border-l", column().holiday === true ? "bg-amber-500/5" : "")}"
724
+ >${hours.map(() => html `<div class="${cn("flex flex-col border-b", rowHeight)}">${Array.from({ length: lines }, (_unused, index) => html `<div class="${cn("flex-1", index < lines - 1 ? "border-border/50 border-b border-dashed" : "")}"></div>`)}</div>`)}</div>`;
725
+ }
726
+ return html `<div
727
+ data-slot="agenda"
728
+ role="group"
729
+ aria-label="${props.label}"
730
+ class="${() => cn("bg-background flex min-w-0 flex-col overflow-clip rounded-lg border", read(props.class))}"
731
+ >
732
+ <span id="${hintId}" hidden>${labels.keyboardHint}</span>
733
+ <div role="status" aria-live="polite" class="sr-only">${() => announcement()}</div>
734
+ <div data-slot="agenda-header" class="bg-card sticky top-0 z-30 flex rounded-t-lg border-b">
735
+ <div class="w-14 shrink-0"></div>
736
+ ${each(columns, (c) => c.key, renderHeader)}
737
+ </div>
738
+ <div id="${bodyId}" data-slot="agenda-body" class="${cn(props.bodyClass === "" ? "" : "overflow-y-auto", props.bodyClass ?? "max-h-[40rem]")}">
739
+ <div class="flex">
740
+ <div aria-hidden="true" class="w-14 shrink-0">${hours.map((hour) => html `<div class="${cn("text-muted-foreground -mt-2 pr-2 text-right text-[0.7rem] tabular-nums first:mt-0", rowHeight)}">${hourLabel(hour)}</div>`)}</div>
741
+ <div
742
+ id="${areaId}"
743
+ data-slot="agenda-area"
744
+ class="relative flex min-w-0 flex-1"
745
+ @click="${onAreaClick}"
746
+ @keydown="${onAreaKeyDown}"
747
+ @pointermove="${onPointerMove}"
748
+ @pointerup="${onPointerUp}"
749
+ @pointercancel="${onPointerCancel}"
750
+ >
751
+ ${each(columns, (c) => c.key, renderColumnLines)}
752
+ <div class="pointer-events-none absolute inset-0">${each(ranges, (r) => r.key, renderRange)}</div>
753
+ <div class="absolute inset-0 pointer-events-none [&>*]:pointer-events-auto">${each(drawableEvents, (e) => e.key, renderEvent)}</div>
754
+ ${nowLine}
755
+ </div>
756
+ </div>
757
+ </div>
758
+ </div>`;
759
+ function drawableEvents() {
760
+ return drawable().map((d) => d.event);
761
+ }
762
+ });