@c9up/nebula 0.2.4 → 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.
Files changed (53) hide show
  1. package/README.md +4 -4
  2. package/dist/atoms/AspectRatio.d.ts +10 -4
  3. package/dist/atoms/AspectRatio.js +21 -6
  4. package/dist/atoms/NativeSelect.d.ts +16 -0
  5. package/dist/atoms/NativeSelect.js +4 -1
  6. package/dist/atoms/Progress.d.ts +9 -1
  7. package/dist/atoms/Progress.js +21 -5
  8. package/dist/atoms/Switch.d.ts +7 -1
  9. package/dist/atoms/Switch.js +7 -1
  10. package/dist/cli/diff.d.ts +46 -0
  11. package/dist/cli/diff.js +73 -2
  12. package/dist/console/DiffCommand.js +6 -11
  13. package/dist/molecules/Accordion.js +1 -2
  14. package/dist/molecules/Collapsible.js +1 -2
  15. package/dist/molecules/Resizable.d.ts +6 -0
  16. package/dist/molecules/Resizable.js +8 -2
  17. package/dist/organisms/Agenda.d.ts +200 -0
  18. package/dist/organisms/Agenda.js +762 -0
  19. package/dist/organisms/AlertDialog.js +4 -5
  20. package/dist/organisms/Chart.d.ts +103 -15
  21. package/dist/organisms/Chart.js +518 -99
  22. package/dist/organisms/Dialog.js +7 -7
  23. package/dist/organisms/Sidebar.d.ts +5 -7
  24. package/dist/organisms/Sidebar.js +23 -6
  25. package/dist/organisms/Sonner.js +11 -4
  26. package/dist/organisms/index.d.ts +2 -1
  27. package/dist/organisms/index.js +2 -1
  28. package/dist/primitives/floatingSurface.js +60 -36
  29. package/dist/primitives/menuParts.js +3 -3
  30. package/dist/primitives/portal.d.ts +15 -0
  31. package/dist/primitives/portal.js +18 -1
  32. package/nebula.css +1 -1
  33. package/package.json +1 -1
  34. package/registry.json +13 -0
  35. package/src/atoms/AspectRatio.ts +21 -6
  36. package/src/atoms/NativeSelect.ts +20 -1
  37. package/src/atoms/Progress.ts +21 -5
  38. package/src/atoms/Switch.ts +7 -1
  39. package/src/cli/diff.ts +123 -2
  40. package/src/console/DiffCommand.ts +12 -15
  41. package/src/molecules/Accordion.ts +1 -2
  42. package/src/molecules/Collapsible.ts +1 -3
  43. package/src/molecules/Resizable.ts +8 -2
  44. package/src/organisms/Agenda.ts +1061 -0
  45. package/src/organisms/AlertDialog.ts +3 -5
  46. package/src/organisms/Chart.ts +633 -125
  47. package/src/organisms/Dialog.ts +6 -7
  48. package/src/organisms/Sidebar.ts +28 -6
  49. package/src/organisms/Sonner.ts +11 -4
  50. package/src/organisms/index.ts +26 -0
  51. package/src/primitives/floatingSurface.ts +74 -40
  52. package/src/primitives/menuParts.ts +3 -3
  53. package/src/primitives/portal.ts +27 -1
@@ -0,0 +1,1061 @@
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
+
39
+ import {
40
+ component,
41
+ each,
42
+ html,
43
+ onMount,
44
+ onUnmount,
45
+ type ReadSignal,
46
+ signal,
47
+ } from "@c9up/aurora";
48
+ import type { Child } from "../lib/children.js";
49
+ import { cn } from "../lib/cn.js";
50
+ import { uid } from "../lib/id.js";
51
+ import { type Reactive, read } from "../lib/props.js";
52
+
53
+ /** A column of the grid: a day, a person on a day, a room. */
54
+ export interface AgendaColumn {
55
+ key: string;
56
+ label: string;
57
+ /** A second line under the label: who is away, how full the day is. */
58
+ hint?: string;
59
+ /** The calendar day it shows, `YYYY-MM-DD`: marks today and draws the now line. */
60
+ date?: string;
61
+ /** A public holiday: the header is marked. */
62
+ holiday?: boolean;
63
+ }
64
+
65
+ /**
66
+ * What a colour says. One meaning each, never decoration: an app maps its own
67
+ * states (free, booked, arrived, cancelled) onto these.
68
+ */
69
+ export type AgendaTone =
70
+ | "default"
71
+ | "primary"
72
+ | "success"
73
+ | "warning"
74
+ | "danger"
75
+ | "muted";
76
+
77
+ /** A span drawn behind the events: a consultation block, an absence. */
78
+ export interface AgendaRange {
79
+ key: string;
80
+ column: string;
81
+ /** `HH:mm`. */
82
+ start: string;
83
+ /** `HH:mm`, after `start`. */
84
+ end: string;
85
+ label?: string;
86
+ tone?: AgendaTone;
87
+ /** Hatched: time that is not available (an absence, a closed block). */
88
+ hatched?: boolean;
89
+ }
90
+
91
+ /** An event: an appointment, a free slot offered for booking. */
92
+ export interface AgendaEvent {
93
+ key: string;
94
+ column: string;
95
+ /** `HH:mm`. */
96
+ start: string;
97
+ /** `HH:mm`, after `start`. */
98
+ end: string;
99
+ title: string;
100
+ detail?: string;
101
+ tone?: AgendaTone;
102
+ /** Any CSS colour for the left edge: a category's own colour. */
103
+ accent?: string;
104
+ /** Drawn struck through: cancelled. */
105
+ struck?: boolean;
106
+ /** May be dragged to another time or column. */
107
+ movable?: boolean;
108
+ /** May have its end dragged. */
109
+ resizable?: boolean;
110
+ }
111
+
112
+ /** Where an event was dropped. */
113
+ export interface AgendaChange {
114
+ event: AgendaEvent;
115
+ column: string;
116
+ start: string;
117
+ end: string;
118
+ }
119
+
120
+ /** A free point of the grid, clicked. */
121
+ export interface AgendaSlot {
122
+ column: string;
123
+ start: string;
124
+ }
125
+
126
+ /**
127
+ * The words the agenda writes itself. `{title}`, `{column}`, `{start}` and
128
+ * `{end}` are replaced where they appear.
129
+ */
130
+ export interface AgendaLabels {
131
+ /** How a screen reader is told to use an event. */
132
+ keyboardHint: string;
133
+ /** Announced when an event is picked up. */
134
+ grabbed: string;
135
+ /** Announced at each step while it is held, and when it is dropped. */
136
+ moved: string;
137
+ /** Announced when Escape puts it back. */
138
+ cancelled: string;
139
+ /** The now line. */
140
+ now: string;
141
+ /** The handle that stretches an event. */
142
+ resize: string;
143
+ }
144
+
145
+ const DEFAULT_LABELS: AgendaLabels = {
146
+ keyboardHint:
147
+ "Arrow keys go from event to event. Enter opens one, Space picks it up.",
148
+ grabbed:
149
+ "{title} picked up. Arrow keys move it, Shift with Up or Down changes its end, Enter drops it, Escape puts it back.",
150
+ moved: "{title}: {column}, {start} to {end}.",
151
+ cancelled: "{title} put back.",
152
+ now: "Now",
153
+ resize: "Change the end of {title}",
154
+ };
155
+
156
+ export interface AgendaProps {
157
+ /** The grid's accessible name. */
158
+ label: string;
159
+ columns: Reactive<readonly AgendaColumn[]>;
160
+ events: Reactive<readonly AgendaEvent[]>;
161
+ ranges?: Reactive<readonly AgendaRange[]>;
162
+ /** First and last hour shown, `[7, 20]` by default: 07:00 to 20:00. */
163
+ hours?: readonly [number, number];
164
+ /** Minutes between two grid lines. Default `15`. */
165
+ step?: number;
166
+ /** Minutes an event moves by. Default: `step`. */
167
+ snap?: number;
168
+ /** Height of an hour. Default `"md"`. */
169
+ size?: "sm" | "md" | "lg";
170
+ /** BCP 47 locale for the hours. Default: the runtime's own. */
171
+ locale?: string;
172
+ labels?: Partial<AgendaLabels>;
173
+ /** The time it is: a clock for the now line, injectable for tests. */
174
+ now?: () => Date;
175
+ /** `HH:mm` scrolled to when mounted. Default: the first range or event. */
176
+ scrollTo?: string;
177
+ class?: Reactive<string>;
178
+ /**
179
+ * Classes of the body: its height. Default `"max-h-[40rem]"`, a body that
180
+ * scrolls on its own. Give `""` to let the agenda take its full height in a
181
+ * page that scrolls already: one scrollbar, the column headers staying in
182
+ * view (they are sticky, and the root clips without scrolling).
183
+ */
184
+ bodyClass?: string;
185
+ /** An event chosen: clicked, or Enter. */
186
+ onActivate?: (event: AgendaEvent) => void;
187
+ /** A range's label chosen. Without it, ranges are not interactive. */
188
+ onRangeActivate?: (range: AgendaRange) => void;
189
+ /** An empty point of the grid clicked. */
190
+ onSlotActivate?: (slot: AgendaSlot) => void;
191
+ /** An event dropped at another time or in another column (its end follows). */
192
+ onMove?: (change: AgendaChange) => void;
193
+ /** An event's end dragged, its start and column unchanged. */
194
+ onResize?: (change: AgendaChange) => void;
195
+ /** The content of an event, instead of its times, title and detail. */
196
+ renderEvent?: (event: ReadSignal<AgendaEvent>) => Child;
197
+ }
198
+
199
+ // ─── time and layout (pure) ──────────────────────────────────────────
200
+
201
+ const CLOCK = /^([01]\d|2[0-4]):([0-5]\d)$/;
202
+
203
+ /** Minutes since midnight of `HH:mm`, or `null` when it is not one. */
204
+ export function minutesOf(clock: string): number | null {
205
+ const match = CLOCK.exec(clock);
206
+ if (match === null) return null;
207
+ const minutes = Number(match[1]) * 60 + Number(match[2]);
208
+ return minutes > 24 * 60 ? null : minutes;
209
+ }
210
+
211
+ /** `HH:mm` of minutes since midnight. */
212
+ export function clockOf(minutes: number): string {
213
+ const hours = Math.floor(minutes / 60);
214
+ const rest = minutes % 60;
215
+ return `${String(hours).padStart(2, "0")}:${String(rest).padStart(2, "0")}`;
216
+ }
217
+
218
+ /** `YYYY-MM-DD` of a date, on its own wall clock. */
219
+ export function isoDay(date: Date): string {
220
+ return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`;
221
+ }
222
+
223
+ /** An event's place among those it overlaps: its lane, of how many. */
224
+ export interface Lane {
225
+ lane: number;
226
+ lanes: number;
227
+ }
228
+
229
+ /**
230
+ * Side-by-side lanes for the events of one column.
231
+ *
232
+ * Events that overlap, directly or through a chain, form a cluster; each takes
233
+ * the first lane free at its start, and every event of the cluster is drawn
234
+ * at the width of the cluster's lane count. Touching is not overlapping: an
235
+ * event ending at 09:00 and one starting at 09:00 share a lane.
236
+ */
237
+ export function lanesOf(
238
+ events: readonly { key: string; start: number; end: number }[],
239
+ ): Map<string, Lane> {
240
+ const sorted = [...events].sort(
241
+ (a, b) => a.start - b.start || b.end - a.end || a.key.localeCompare(b.key),
242
+ );
243
+ const result = new Map<string, Lane>();
244
+ let cluster: { key: string; lane: number }[] = [];
245
+ let laneEnds: number[] = [];
246
+ let clusterEnd = Number.NEGATIVE_INFINITY;
247
+ const close = (): void => {
248
+ for (const member of cluster) {
249
+ result.set(member.key, { lane: member.lane, lanes: laneEnds.length });
250
+ }
251
+ cluster = [];
252
+ laneEnds = [];
253
+ };
254
+ for (const event of sorted) {
255
+ if (event.start >= clusterEnd) close();
256
+ let lane = laneEnds.findIndex((end) => end <= event.start);
257
+ if (lane === -1) {
258
+ lane = laneEnds.length;
259
+ laneEnds.push(event.end);
260
+ } else {
261
+ laneEnds[lane] = event.end;
262
+ }
263
+ cluster.push({ key: event.key, lane });
264
+ clusterEnd = Math.max(clusterEnd, event.end);
265
+ }
266
+ close();
267
+ return result;
268
+ }
269
+
270
+ /** `value` down to a multiple of `snap`. */
271
+ export function snapDown(value: number, snap: number): number {
272
+ return Math.floor(value / snap) * snap;
273
+ }
274
+
275
+ /** `value` to the nearest multiple of `snap`. */
276
+ export function snapNearest(value: number, snap: number): number {
277
+ return Math.round(value / snap) * snap;
278
+ }
279
+
280
+ /**
281
+ * A move kept within the grid: the start between the first hour and the
282
+ * last minus the duration, the duration unchanged.
283
+ */
284
+ export function clampMove(
285
+ start: number,
286
+ duration: number,
287
+ from: number,
288
+ to: number,
289
+ ): { start: number; end: number } {
290
+ const kept = Math.min(Math.max(start, from), Math.max(from, to - duration));
291
+ return { start: kept, end: kept + duration };
292
+ }
293
+
294
+ /** A new end kept after the start by one snap at least, and within the grid. */
295
+ export function clampEnd(
296
+ start: number,
297
+ end: number,
298
+ snap: number,
299
+ to: number,
300
+ ): number {
301
+ return Math.min(Math.max(end, start + snap), to);
302
+ }
303
+
304
+ /** Replace `{name}` placeholders. */
305
+ function fill(
306
+ template: string,
307
+ values: Readonly<Record<string, string>>,
308
+ ): string {
309
+ return template.replace(/\{(\w+)\}/g, (whole, name: string) =>
310
+ Object.hasOwn(values, name) ? (values[name] ?? whole) : whole,
311
+ );
312
+ }
313
+
314
+ const HOUR_HEIGHT: Record<"sm" | "md" | "lg", string> = {
315
+ sm: "h-12",
316
+ md: "h-20",
317
+ lg: "h-32",
318
+ };
319
+
320
+ /**
321
+ * An event is opaque: the card's colour underneath, the tone's tint laid
322
+ * over it as a background image. A translucent fill alone let a range's
323
+ * label show through the event above it.
324
+ */
325
+ const EVENT_TONES: Record<AgendaTone, string> = {
326
+ default: "bg-card text-card-foreground border-border",
327
+ primary:
328
+ "bg-card bg-linear-to-r from-primary/15 to-primary/15 text-foreground border-primary",
329
+ success:
330
+ "bg-card bg-linear-to-r from-emerald-500/15 to-emerald-500/15 text-foreground border-emerald-600 dark:border-emerald-400",
331
+ warning:
332
+ "bg-card bg-linear-to-r from-amber-500/15 to-amber-500/15 text-foreground border-amber-600 dark:border-amber-400",
333
+ danger:
334
+ "bg-card bg-linear-to-r from-destructive/15 to-destructive/15 text-foreground border-destructive",
335
+ muted: "bg-muted text-muted-foreground border-muted-foreground/40",
336
+ };
337
+
338
+ const RANGE_TONES: Record<AgendaTone, string> = {
339
+ default: "bg-accent/40",
340
+ primary: "bg-primary/10",
341
+ success: "bg-emerald-500/10",
342
+ warning: "bg-amber-500/10",
343
+ danger: "bg-destructive/10",
344
+ muted: "bg-muted/60",
345
+ };
346
+
347
+ const HATCHED =
348
+ "bg-[repeating-linear-gradient(135deg,transparent_0_6px,var(--color-border)_6px_8px)]";
349
+
350
+ /** Where an event is drawn while it is held, before the caller is told. */
351
+ interface Draft {
352
+ key: string;
353
+ column: string;
354
+ start: number;
355
+ end: number;
356
+ }
357
+
358
+ // ─── component ───────────────────────────────────────────────────────
359
+
360
+ export const Agenda = component<AgendaProps>((props) => {
361
+ const labels: AgendaLabels = { ...DEFAULT_LABELS, ...props.labels };
362
+ const [firstHour, lastHour] = props.hours ?? [7, 20];
363
+ const from = firstHour * 60;
364
+ const to = lastHour * 60;
365
+ const span = Math.max(60, to - from);
366
+ const step = props.step ?? 15;
367
+ const snap = props.snap ?? step;
368
+ const clock = props.now ?? (() => new Date());
369
+
370
+ const areaId = uid("agenda-area");
371
+ const hintId = uid("agenda-hint");
372
+ const bodyId = uid("agenda-body");
373
+
374
+ const columns = (): readonly AgendaColumn[] => read(props.columns);
375
+ const events = (): readonly AgendaEvent[] => read(props.events);
376
+ const ranges = (): readonly AgendaRange[] => read(props.ranges) ?? [];
377
+
378
+ /** Placed once mounted: before that, ranges and events have no geometry. */
379
+ const placed = signal(false);
380
+ /** The event the keyboard is on; the only tabbable one. */
381
+ const cursor = signal<string | null>(null);
382
+ /** The event being held, by keyboard or pointer, and where it is drawn. */
383
+ const draft = signal<Draft | null>(null);
384
+ /** Held by the keyboard (as opposed to the pointer). */
385
+ const grabbed = signal(false);
386
+ const announcement = signal("");
387
+ const nowTick = signal(clock());
388
+
389
+ const hourFormat = new Intl.DateTimeFormat(props.locale, {
390
+ hour: "2-digit",
391
+ minute: "2-digit",
392
+ timeZone: "UTC",
393
+ });
394
+ const hourLabel = (minutes: number): string =>
395
+ hourFormat.format(new Date(Date.UTC(2000, 0, 1, 0, minutes)));
396
+
397
+ const columnIndex = (key: string): number =>
398
+ columns().findIndex((c) => c.key === key);
399
+ const columnLabel = (key: string): string =>
400
+ columns().find((c) => c.key === key)?.label ?? key;
401
+
402
+ /** The events that can be drawn: in a known column, with valid times. */
403
+ const drawable = (): { event: AgendaEvent; start: number; end: number }[] =>
404
+ events().flatMap((event) => {
405
+ const start = minutesOf(event.start);
406
+ const end = minutesOf(event.end);
407
+ if (start === null || end === null || end <= start) return [];
408
+ if (columnIndex(event.column) === -1) return [];
409
+ if (end <= from || start >= to) return [];
410
+ return [{ event, start, end }];
411
+ });
412
+
413
+ /** Lanes per event, each column apart. */
414
+ const lanes = (): Map<string, Lane> => {
415
+ const all = new Map<string, Lane>();
416
+ const byColumn = new Map<
417
+ string,
418
+ { key: string; start: number; end: number }[]
419
+ >();
420
+ for (const { event, start, end } of drawable()) {
421
+ const list = byColumn.get(event.column) ?? [];
422
+ list.push({ key: event.key, start, end });
423
+ byColumn.set(event.column, list);
424
+ }
425
+ for (const list of byColumn.values()) {
426
+ for (const [key, lane] of lanesOf(list)) all.set(key, lane);
427
+ }
428
+ return all;
429
+ };
430
+
431
+ const percent = (value: number): string => `${(value * 100).toFixed(4)}%`;
432
+
433
+ /** The CSS placing a span of `column` from `start` to `end`, in a lane. */
434
+ function geometry(
435
+ column: string,
436
+ start: number,
437
+ end: number,
438
+ lane: Lane = { lane: 0, lanes: 1 },
439
+ ): string {
440
+ const count = Math.max(1, columns().length);
441
+ const index = Math.max(0, columnIndex(column));
442
+ const top = (Math.max(start, from) - from) / span;
443
+ const height = (Math.min(end, to) - Math.max(start, from)) / span;
444
+ const left = (index + lane.lane / lane.lanes) / count;
445
+ const width = 1 / count / lane.lanes;
446
+ // A point in time (the now line) has no height of its own: its class gives it one.
447
+ const tall = end > start ? `height:${percent(height)};` : "";
448
+ return `top:${percent(top)};${tall}left:${percent(left)};width:${percent(width)}`;
449
+ }
450
+
451
+ function say(
452
+ template: string,
453
+ values: Readonly<Record<string, string>>,
454
+ ): void {
455
+ announcement(fill(template, values));
456
+ }
457
+
458
+ const current = (key: string): AgendaEvent | undefined =>
459
+ events().find((e) => e.key === key);
460
+
461
+ // ─── holding an event ────────────────────────────────────────────
462
+
463
+ function pickUp(event: AgendaEvent): boolean {
464
+ const start = minutesOf(event.start);
465
+ const end = minutesOf(event.end);
466
+ if (start === null || end === null) return false;
467
+ draft({ key: event.key, column: event.column, start, end });
468
+ return true;
469
+ }
470
+
471
+ function drop(): void {
472
+ const held = draft();
473
+ draft(null);
474
+ grabbed(false);
475
+ if (held === null) return;
476
+ const event = current(held.key);
477
+ if (event === undefined) return;
478
+ const change: AgendaChange = {
479
+ event,
480
+ column: held.column,
481
+ start: clockOf(held.start),
482
+ end: clockOf(held.end),
483
+ };
484
+ const moved =
485
+ change.column !== event.column || change.start !== event.start;
486
+ const stretched = change.end !== event.end;
487
+ say(labels.moved, {
488
+ title: event.title,
489
+ column: columnLabel(change.column),
490
+ start: change.start,
491
+ end: change.end,
492
+ });
493
+ if (moved) props.onMove?.(change);
494
+ else if (stretched) props.onResize?.(change);
495
+ }
496
+
497
+ function putBack(): void {
498
+ const held = draft();
499
+ draft(null);
500
+ grabbed(false);
501
+ const event = held === null ? undefined : current(held.key);
502
+ if (event !== undefined) say(labels.cancelled, { title: event.title });
503
+ }
504
+
505
+ function announceDraft(): void {
506
+ const held = draft();
507
+ const event = held === null ? undefined : current(held.key);
508
+ if (held === null || event === undefined) return;
509
+ say(labels.moved, {
510
+ title: event.title,
511
+ column: columnLabel(held.column),
512
+ start: clockOf(held.start),
513
+ end: clockOf(held.end),
514
+ });
515
+ }
516
+
517
+ // ─── keyboard ────────────────────────────────────────────────────
518
+
519
+ function focusEvent(key: string): void {
520
+ cursor(key);
521
+ queueMicrotask(() => {
522
+ const area = document.getElementById(areaId);
523
+ const target = [
524
+ ...(area?.querySelectorAll<HTMLElement>('[data-slot="agenda-event"]') ??
525
+ []),
526
+ ].find((element) => element.dataset.key === key);
527
+ target?.focus();
528
+ });
529
+ }
530
+
531
+ /** The event the arrows lead to from `event`, or `undefined`. */
532
+ function neighbour(event: AgendaEvent, key: string): AgendaEvent | undefined {
533
+ const all = drawable();
534
+ const startOf = (e: AgendaEvent): number => minutesOf(e.start) ?? 0;
535
+ const inColumn = (column: string): AgendaEvent[] =>
536
+ all
537
+ .filter((d) => d.event.column === column)
538
+ .map((d) => d.event)
539
+ .sort((a, b) => startOf(a) - startOf(b) || a.key.localeCompare(b.key));
540
+ const ordered = columns().flatMap((c) => inColumn(c.key));
541
+ if (key === "Home") return ordered[0];
542
+ if (key === "End") return ordered[ordered.length - 1];
543
+ if (key === "ArrowUp" || key === "ArrowDown") {
544
+ const list = inColumn(event.column);
545
+ const at = list.findIndex((e) => e.key === event.key);
546
+ return list[at + (key === "ArrowUp" ? -1 : 1)];
547
+ }
548
+ const direction = key === "ArrowLeft" ? -1 : 1;
549
+ const cols = columns();
550
+ for (
551
+ let index = columnIndex(event.column) + direction;
552
+ index >= 0 && index < cols.length;
553
+ index += direction
554
+ ) {
555
+ const column = cols[index];
556
+ if (column === undefined) break;
557
+ const list = inColumn(column.key);
558
+ if (list.length === 0) continue;
559
+ const target = startOf(event);
560
+ return list.reduce((best, e) =>
561
+ Math.abs(startOf(e) - target) < Math.abs(startOf(best) - target)
562
+ ? e
563
+ : best,
564
+ );
565
+ }
566
+ return undefined;
567
+ }
568
+
569
+ function onEventKeyDown(event: AgendaEvent, e: KeyboardEvent): void {
570
+ const held = draft();
571
+ if (grabbed() && held !== null) {
572
+ heldKeyDown(event, held, e);
573
+ return;
574
+ }
575
+ if (e.key === "Enter") {
576
+ e.preventDefault();
577
+ props.onActivate?.(event);
578
+ return;
579
+ }
580
+ if (e.key === " ") {
581
+ e.preventDefault();
582
+ if (
583
+ (event.movable === true || event.resizable === true) &&
584
+ pickUp(event)
585
+ ) {
586
+ grabbed(true);
587
+ say(labels.grabbed, { title: event.title });
588
+ } else {
589
+ props.onActivate?.(event);
590
+ }
591
+ return;
592
+ }
593
+ if (
594
+ [
595
+ "ArrowUp",
596
+ "ArrowDown",
597
+ "ArrowLeft",
598
+ "ArrowRight",
599
+ "Home",
600
+ "End",
601
+ ].includes(e.key)
602
+ ) {
603
+ e.preventDefault();
604
+ const next = neighbour(event, e.key);
605
+ if (next !== undefined) focusEvent(next.key);
606
+ }
607
+ }
608
+
609
+ function heldKeyDown(
610
+ event: AgendaEvent,
611
+ held: Draft,
612
+ e: KeyboardEvent,
613
+ ): void {
614
+ const duration = held.end - held.start;
615
+ const cols = columns();
616
+ let next: Draft | null = null;
617
+ if (e.key === "Escape") {
618
+ e.preventDefault();
619
+ putBack();
620
+ return;
621
+ }
622
+ if (e.key === "Enter" || e.key === " ") {
623
+ e.preventDefault();
624
+ drop();
625
+ return;
626
+ }
627
+ if ((e.key === "ArrowUp" || e.key === "ArrowDown") && e.shiftKey) {
628
+ if (event.resizable !== true) return;
629
+ const end = clampEnd(
630
+ held.start,
631
+ held.end + (e.key === "ArrowUp" ? -snap : snap),
632
+ snap,
633
+ to,
634
+ );
635
+ next = { ...held, end };
636
+ } else if (e.key === "ArrowUp" || e.key === "ArrowDown") {
637
+ if (event.movable !== true) return;
638
+ const moved = clampMove(
639
+ held.start + (e.key === "ArrowUp" ? -snap : snap),
640
+ duration,
641
+ from,
642
+ to,
643
+ );
644
+ next = { ...held, ...moved };
645
+ } else if (e.key === "ArrowLeft" || e.key === "ArrowRight") {
646
+ if (event.movable !== true) return;
647
+ const index = columnIndex(held.column) + (e.key === "ArrowLeft" ? -1 : 1);
648
+ const column = cols[index];
649
+ if (column === undefined) return;
650
+ next = { ...held, column: column.key };
651
+ } else if (e.key === "Tab") {
652
+ putBack();
653
+ return;
654
+ }
655
+ if (next === null) return;
656
+ e.preventDefault();
657
+ draft(next);
658
+ announceDraft();
659
+ }
660
+
661
+ // ─── pointer ─────────────────────────────────────────────────────
662
+
663
+ /** The column and minute under a point of the area, unsnapped. */
664
+ function pointAt(
665
+ x: number,
666
+ y: number,
667
+ ): { column: string; minutes: number } | null {
668
+ const area = document.getElementById(areaId);
669
+ const cols = columns();
670
+ if (area === null || cols.length === 0) return null;
671
+ const rect = area.getBoundingClientRect();
672
+ if (rect.width <= 0 || rect.height <= 0) return null;
673
+ const index = Math.min(
674
+ cols.length - 1,
675
+ Math.max(0, Math.floor(((x - rect.left) / rect.width) * cols.length)),
676
+ );
677
+ const column = cols[index];
678
+ if (column === undefined) return null;
679
+ return {
680
+ column: column.key,
681
+ minutes: from + ((y - rect.top) / rect.height) * span,
682
+ };
683
+ }
684
+
685
+ /** A pointer gesture in progress. */
686
+ let gesture: {
687
+ key: string;
688
+ mode: "move" | "resize";
689
+ pointerX: number;
690
+ pointerY: number;
691
+ /** Minutes between the event's start and the point it was taken by. */
692
+ offset: number;
693
+ started: boolean;
694
+ } | null = null;
695
+ /** A drag ends in a click on the same element: that click is not an activation. */
696
+ let swallowClick = false;
697
+
698
+ function onPointerDown(
699
+ event: AgendaEvent,
700
+ mode: "move" | "resize",
701
+ e: PointerEvent,
702
+ ): void {
703
+ if (e.button !== 0) return;
704
+ if (mode === "move" && event.movable !== true) return;
705
+ if (mode === "resize" && event.resizable !== true) return;
706
+ const point = pointAt(e.clientX, e.clientY);
707
+ const start = minutesOf(event.start);
708
+ if (point === null || start === null) return;
709
+ if (mode === "resize") e.stopPropagation();
710
+ gesture = {
711
+ key: event.key,
712
+ mode,
713
+ pointerX: e.clientX,
714
+ pointerY: e.clientY,
715
+ offset: point.minutes - start,
716
+ started: false,
717
+ };
718
+ const target = e.currentTarget;
719
+ if (target instanceof Element) target.setPointerCapture?.(e.pointerId);
720
+ }
721
+
722
+ function onPointerMove(e: PointerEvent): void {
723
+ if (gesture === null) return;
724
+ if (!gesture.started) {
725
+ const distance = Math.hypot(
726
+ e.clientX - gesture.pointerX,
727
+ e.clientY - gesture.pointerY,
728
+ );
729
+ if (distance < 4) return;
730
+ const event = current(gesture.key);
731
+ if (event === undefined || !pickUp(event)) {
732
+ gesture = null;
733
+ return;
734
+ }
735
+ gesture.started = true;
736
+ }
737
+ const held = draft();
738
+ const point = pointAt(e.clientX, e.clientY);
739
+ if (held === null || point === null) return;
740
+ if (gesture.mode === "resize") {
741
+ draft({
742
+ ...held,
743
+ end: clampEnd(held.start, snapNearest(point.minutes, snap), snap, to),
744
+ });
745
+ return;
746
+ }
747
+ const moved = clampMove(
748
+ snapNearest(point.minutes - gesture.offset, snap),
749
+ held.end - held.start,
750
+ from,
751
+ to,
752
+ );
753
+ draft({ ...held, column: point.column, ...moved });
754
+ }
755
+
756
+ function onPointerUp(): void {
757
+ if (gesture === null) return;
758
+ const started = gesture.started;
759
+ gesture = null;
760
+ if (!started) return;
761
+ // The click that follows this release, if it lands, is the drag's own.
762
+ swallowClick = true;
763
+ setTimeout(() => {
764
+ swallowClick = false;
765
+ }, 0);
766
+ drop();
767
+ }
768
+
769
+ function onPointerCancel(): void {
770
+ if (gesture === null) return;
771
+ const started = gesture.started;
772
+ gesture = null;
773
+ if (started) putBack();
774
+ }
775
+
776
+ function onAreaKeyDown(e: KeyboardEvent): void {
777
+ if (e.key === "Escape" && gesture !== null) {
778
+ gesture = null;
779
+ putBack();
780
+ }
781
+ }
782
+
783
+ function onAreaClick(e: MouseEvent): void {
784
+ if (props.onSlotActivate === undefined) return;
785
+ const target = e.target;
786
+ if (
787
+ target instanceof Element &&
788
+ target.closest(
789
+ "[data-slot='agenda-event'],[data-slot='agenda-range-label']",
790
+ ) !== null
791
+ )
792
+ return;
793
+ const point = pointAt(e.clientX, e.clientY);
794
+ if (point === null) return;
795
+ const start = snapDown(point.minutes, snap);
796
+ if (start < from || start >= to) return;
797
+ props.onSlotActivate({ column: point.column, start: clockOf(start) });
798
+ }
799
+
800
+ function onEventClick(event: AgendaEvent): void {
801
+ if (swallowClick) {
802
+ swallowClick = false;
803
+ return;
804
+ }
805
+ cursor(event.key);
806
+ props.onActivate?.(event);
807
+ }
808
+
809
+ // ─── mount ───────────────────────────────────────────────────────
810
+
811
+ let timer: ReturnType<typeof setInterval> | undefined;
812
+ onMount(() => {
813
+ placed(true);
814
+ timer = setInterval(() => nowTick(clock()), 60_000);
815
+ const body = document.getElementById(bodyId);
816
+ const first = [
817
+ ...ranges().map((r) => minutesOf(r.start)),
818
+ ...events().map((e) => minutesOf(e.start)),
819
+ ].filter((m): m is number => m !== null && m >= from && m < to);
820
+ const target =
821
+ props.scrollTo === undefined
822
+ ? first.length === 0
823
+ ? null
824
+ : Math.min(...first)
825
+ : minutesOf(props.scrollTo);
826
+ if (body !== null && target !== null) {
827
+ const area = document.getElementById(areaId);
828
+ const height = area?.getBoundingClientRect().height ?? 0;
829
+ body.scrollTop = Math.max(0, ((target - from) / span) * height - 16);
830
+ }
831
+ });
832
+ onUnmount(() => {
833
+ if (timer !== undefined) clearInterval(timer);
834
+ });
835
+
836
+ // ─── rendering ───────────────────────────────────────────────────
837
+
838
+ const hours = Array.from(
839
+ { length: Math.ceil(span / 60) },
840
+ (_unused, index) => from + index * 60,
841
+ );
842
+ const lines = Math.max(1, Math.round(60 / step));
843
+ const rowHeight = HOUR_HEIGHT[props.size ?? "md"];
844
+
845
+ /** The tabbable event: the cursor, else the first drawn. */
846
+ const tabbable = (): string | null => {
847
+ const all = drawable();
848
+ const at = cursor();
849
+ if (at !== null && all.some((d) => d.event.key === at)) return at;
850
+ return all[0]?.event.key ?? null;
851
+ };
852
+
853
+ const today = (): string => isoDay(nowTick());
854
+
855
+ function nowLine(): Child {
856
+ const at = nowTick();
857
+ const minutes = at.getHours() * 60 + at.getMinutes();
858
+ const column = columns().find((c) => c.date === today());
859
+ if (column === undefined || minutes < from || minutes >= to || !placed())
860
+ return null;
861
+ return html`<div
862
+ data-slot="agenda-now"
863
+ aria-hidden="true"
864
+ title="${labels.now}"
865
+ class="bg-destructive pointer-events-none absolute z-20 h-0.5"
866
+ .style="${geometry(column.key, minutes, minutes)}"
867
+ ></div>`;
868
+ }
869
+
870
+ function renderRange(range: ReadSignal<AgendaRange>): Child {
871
+ const style = (): string => {
872
+ const r = range();
873
+ const start = minutesOf(r.start) ?? from;
874
+ const end = minutesOf(r.end) ?? start;
875
+ return geometry(r.column, start, end);
876
+ };
877
+ const visible = (): boolean => {
878
+ const r = range();
879
+ const start = minutesOf(r.start);
880
+ const end = minutesOf(r.end);
881
+ return (
882
+ placed() &&
883
+ start !== null &&
884
+ end !== null &&
885
+ end > start &&
886
+ columnIndex(r.column) !== -1 &&
887
+ end > from &&
888
+ start < to
889
+ );
890
+ };
891
+ const label = (): Child => {
892
+ const r = range();
893
+ if (r.label === undefined) return null;
894
+ if (props.onRangeActivate === undefined) {
895
+ return html`<span class="text-muted-foreground block truncate px-1 pt-0.5 text-[0.7rem]">${r.label}</span>`;
896
+ }
897
+ return html`<button
898
+ type="button"
899
+ data-slot="agenda-range-label"
900
+ 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]"
901
+ @click="${() => props.onRangeActivate?.(range())}"
902
+ >${r.label}</button>`;
903
+ };
904
+ return html`<div
905
+ data-slot="agenda-range"
906
+ data-key="${() => range().key}"
907
+ ?hidden="${() => !visible()}"
908
+ class="${() => cn("pointer-events-none absolute z-0 border-l-2 border-transparent", RANGE_TONES[range().tone ?? "default"], range().hatched === true ? HATCHED : "")}"
909
+ .style="${style}"
910
+ >${label}</div>`;
911
+ }
912
+
913
+ function renderEvent(event: ReadSignal<AgendaEvent>): Child {
914
+ const held = (): Draft | null => {
915
+ const d = draft();
916
+ return d !== null && d.key === event().key ? d : null;
917
+ };
918
+ const style = (): string => {
919
+ const e = event();
920
+ const d = held();
921
+ const lane = d === null ? lanes().get(e.key) : undefined;
922
+ const start = d?.start ?? minutesOf(e.start) ?? from;
923
+ const end = d?.end ?? minutesOf(e.end) ?? start;
924
+ const accent =
925
+ e.accent === undefined ? "" : `;border-left-color:${e.accent}`;
926
+ return `${geometry(d?.column ?? e.column, start, end, lane)}${accent}`;
927
+ };
928
+ const times = (): string => {
929
+ const d = held();
930
+ const e = event();
931
+ return d === null
932
+ ? `${e.start}–${e.end}`
933
+ : `${clockOf(d.start)}–${clockOf(d.end)}`;
934
+ };
935
+ const name = (): string => {
936
+ const e = event();
937
+ return [e.title, e.detail, columnLabel(e.column), `${e.start}–${e.end}`]
938
+ .filter((part) => part !== undefined && part !== "")
939
+ .join(", ");
940
+ };
941
+ const content = (): Child =>
942
+ props.renderEvent === undefined
943
+ ? html`<span class="block truncate text-[0.7rem] tabular-nums opacity-80">${times}</span>
944
+ <span class="${() => cn("block truncate font-medium", event().struck === true ? "line-through" : "")}">${() => event().title}</span>
945
+ ${() => (event().detail === undefined ? null : html`<span class="text-muted-foreground block truncate">${() => event().detail}</span>`)}`
946
+ : props.renderEvent(event);
947
+ return html`<div
948
+ data-slot="agenda-event"
949
+ data-key="${() => event().key}"
950
+ data-tone="${() => event().tone ?? "default"}"
951
+ data-held="${() => (held() === null ? undefined : "")}"
952
+ role="button"
953
+ aria-label="${name}"
954
+ aria-describedby="${hintId}"
955
+ aria-pressed="${() => (held() !== null && grabbed() ? "true" : undefined)}"
956
+ tabindex="${() => (tabbable() === event().key ? 0 : -1)}"
957
+ ?hidden="${() => !placed()}"
958
+ class="${() =>
959
+ cn(
960
+ "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",
961
+ "focus-visible:ring-ring/50 focus-visible:z-30 focus-visible:ring-[3px]",
962
+ EVENT_TONES[event().tone ?? "default"],
963
+ event().movable === true ? "cursor-grab touch-none" : "",
964
+ held() === null
965
+ ? ""
966
+ : "z-30 cursor-grabbing opacity-90 shadow-lg ring-2 ring-primary",
967
+ )}"
968
+ .style="${style}"
969
+ @click="${() => onEventClick(event())}"
970
+ @focus="${() => cursor(event().key)}"
971
+ @blur="${() => {
972
+ if (grabbed() && held() !== null) putBack();
973
+ }}"
974
+ @keydown="${(e: KeyboardEvent) => onEventKeyDown(event(), e)}"
975
+ @pointerdown="${(e: PointerEvent) => onPointerDown(event(), "move", e)}"
976
+ >${content}${() =>
977
+ event().resizable === true
978
+ ? html`<span
979
+ data-slot="agenda-resize"
980
+ aria-hidden="true"
981
+ title="${() => fill(labels.resize, { title: event().title })}"
982
+ class="absolute inset-x-0 bottom-0 h-1.5 cursor-ns-resize touch-none opacity-0 group-hover:opacity-100 bg-foreground/20"
983
+ @pointerdown="${(e: PointerEvent) => onPointerDown(event(), "resize", e)}"
984
+ ></span>`
985
+ : null}</div>`;
986
+ }
987
+
988
+ function renderHeader(column: ReadSignal<AgendaColumn>): Child {
989
+ const isToday = (): boolean =>
990
+ column().date !== undefined && column().date === today();
991
+ return html`<div
992
+ data-slot="agenda-column"
993
+ data-key="${() => column().key}"
994
+ data-today="${() => (isToday() ? "" : undefined)}"
995
+ data-holiday="${() => (column().holiday === true ? "" : undefined)}"
996
+ class="${() =>
997
+ cn(
998
+ "min-w-0 flex-1 border-l px-2 py-1.5 text-center",
999
+ column().holiday === true ? "bg-amber-500/10" : "",
1000
+ )}"
1001
+ >
1002
+ <span class="${() => cn("block truncate text-sm font-medium", isToday() ? "text-primary" : "")}">${() => column().label}</span>
1003
+ ${() => (column().hint === undefined ? null : html`<span class="text-muted-foreground block truncate text-xs">${() => column().hint}</span>`)}
1004
+ </div>`;
1005
+ }
1006
+
1007
+ function renderColumnLines(column: ReadSignal<AgendaColumn>): Child {
1008
+ return html`<div
1009
+ data-key="${() => column().key}"
1010
+ class="${() => cn("min-w-0 flex-1 border-l", column().holiday === true ? "bg-amber-500/5" : "")}"
1011
+ >${hours.map(
1012
+ () =>
1013
+ html`<div class="${cn("flex flex-col border-b", rowHeight)}">${Array.from(
1014
+ { length: lines },
1015
+ (_unused, index) =>
1016
+ html`<div class="${cn("flex-1", index < lines - 1 ? "border-border/50 border-b border-dashed" : "")}"></div>`,
1017
+ )}</div>`,
1018
+ )}</div>`;
1019
+ }
1020
+
1021
+ return html`<div
1022
+ data-slot="agenda"
1023
+ role="group"
1024
+ aria-label="${props.label}"
1025
+ class="${() => cn("bg-background flex min-w-0 flex-col overflow-clip rounded-lg border", read(props.class))}"
1026
+ >
1027
+ <span id="${hintId}" hidden>${labels.keyboardHint}</span>
1028
+ <div role="status" aria-live="polite" class="sr-only">${() => announcement()}</div>
1029
+ <div data-slot="agenda-header" class="bg-card sticky top-0 z-30 flex rounded-t-lg border-b">
1030
+ <div class="w-14 shrink-0"></div>
1031
+ ${each(columns, (c) => c.key, renderHeader)}
1032
+ </div>
1033
+ <div id="${bodyId}" data-slot="agenda-body" class="${cn(props.bodyClass === "" ? "" : "overflow-y-auto", props.bodyClass ?? "max-h-[40rem]")}">
1034
+ <div class="flex">
1035
+ <div aria-hidden="true" class="w-14 shrink-0">${hours.map(
1036
+ (hour) =>
1037
+ 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>`,
1038
+ )}</div>
1039
+ <div
1040
+ id="${areaId}"
1041
+ data-slot="agenda-area"
1042
+ class="relative flex min-w-0 flex-1"
1043
+ @click="${onAreaClick}"
1044
+ @keydown="${onAreaKeyDown}"
1045
+ @pointermove="${onPointerMove}"
1046
+ @pointerup="${onPointerUp}"
1047
+ @pointercancel="${onPointerCancel}"
1048
+ >
1049
+ ${each(columns, (c) => c.key, renderColumnLines)}
1050
+ <div class="pointer-events-none absolute inset-0">${each(ranges, (r) => r.key, renderRange)}</div>
1051
+ <div class="absolute inset-0 pointer-events-none [&>*]:pointer-events-auto">${each(drawableEvents, (e) => e.key, renderEvent)}</div>
1052
+ ${nowLine}
1053
+ </div>
1054
+ </div>
1055
+ </div>
1056
+ </div>`;
1057
+
1058
+ function drawableEvents(): readonly AgendaEvent[] {
1059
+ return drawable().map((d) => d.event);
1060
+ }
1061
+ });