@lavalogic/scoria 0.38.12 → 0.38.13

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 (94) hide show
  1. package/dist/Components/AccordionGroup.svelte +46 -46
  2. package/dist/Components/AccordionGroupButton.svelte +76 -76
  3. package/dist/Components/Action.svelte +136 -136
  4. package/dist/Components/AppointmentCalendar/AppointmentCalendar.svelte +712 -702
  5. package/dist/Components/Base/BaseModal.svelte +125 -125
  6. package/dist/Components/Base/ContextWrapper.svelte +72 -72
  7. package/dist/Components/Base/Pagination.svelte +198 -198
  8. package/dist/Components/Base/Snippets.svelte +36 -36
  9. package/dist/Components/BigRadioSet.svelte +38 -38
  10. package/dist/Components/Bubble.svelte +101 -101
  11. package/dist/Components/Button.svelte +209 -209
  12. package/dist/Components/Checkbox.svelte +86 -86
  13. package/dist/Components/Contexts/ContextMenu.svelte +164 -164
  14. package/dist/Components/Contexts/ContextMenuDivider.svelte +15 -15
  15. package/dist/Components/Contexts/ContextMenuOption.svelte +60 -60
  16. package/dist/Components/Contexts/ToastContainer.svelte +65 -65
  17. package/dist/Components/Contexts/Tooltip.svelte +37 -37
  18. package/dist/Components/DataMatrixIcon.svelte +112 -112
  19. package/dist/Components/DateInput.svelte +148 -148
  20. package/dist/Components/DatePicker.svelte +300 -300
  21. package/dist/Components/DesktopModal.svelte +90 -90
  22. package/dist/Components/Dial.svelte +204 -204
  23. package/dist/Components/DimensionInput.svelte +170 -170
  24. package/dist/Components/DragMenu/DragMenuHolder.svelte +119 -119
  25. package/dist/Components/DragMenu/DraggableCard.svelte +77 -77
  26. package/dist/Components/FileCard.svelte +24 -24
  27. package/dist/Components/FileUpload.svelte +236 -236
  28. package/dist/Components/GridInputSet.svelte +29 -29
  29. package/dist/Components/HorizontalTabGroup.svelte +82 -82
  30. package/dist/Components/HorizontalTabGroupButton.svelte +44 -44
  31. package/dist/Components/Icon.svelte +128 -128
  32. package/dist/Components/Icons.js +357 -357
  33. package/dist/Components/LoadingAnimation.svelte +29 -29
  34. package/dist/Components/LoadingModal.svelte +45 -45
  35. package/dist/Components/LoadingOverlay.svelte +25 -25
  36. package/dist/Components/Modal.svelte +258 -258
  37. package/dist/Components/MultiSelect.svelte +220 -220
  38. package/dist/Components/Nav/NavServiceMenuList.svelte +43 -43
  39. package/dist/Components/Nav/NavTab.svelte +62 -62
  40. package/dist/Components/Nav/ServicesNav.svelte +80 -80
  41. package/dist/Components/NumberInput.svelte +157 -157
  42. package/dist/Components/PageHeading.svelte +25 -25
  43. package/dist/Components/PasswordInput.svelte +88 -88
  44. package/dist/Components/Portal.svelte +36 -36
  45. package/dist/Components/QuerySelect.svelte +366 -366
  46. package/dist/Components/SingleSelect.svelte +250 -250
  47. package/dist/Components/StepButton.svelte +70 -70
  48. package/dist/Components/StepForm.svelte +140 -140
  49. package/dist/Components/Switch.svelte +69 -69
  50. package/dist/Components/Table/Body/Rows/ColumnHighlight.svelte +51 -51
  51. package/dist/Components/Table/Body/Rows/ColumnList.svelte +59 -59
  52. package/dist/Components/Table/Body/Rows/Columns/AccessorComponent.svelte +79 -79
  53. package/dist/Components/Table/Body/Rows/Columns/ExpandCell.svelte +120 -120
  54. package/dist/Components/Table/Body/Rows/Columns/ProgressCell.svelte +105 -105
  55. package/dist/Components/Table/Body/Rows/Columns/TableAction.svelte +87 -87
  56. package/dist/Components/Table/Body/Rows/Columns/TableCheckbox.svelte +126 -126
  57. package/dist/Components/Table/Body/Rows/Columns/TableColumn.svelte +159 -159
  58. package/dist/Components/Table/Body/Rows/Columns/TableDatePicker.svelte +246 -246
  59. package/dist/Components/Table/Body/Rows/Columns/TableNumberInput.svelte +216 -216
  60. package/dist/Components/Table/Body/Rows/Columns/TableRowSelectionCheckbox.svelte +179 -179
  61. package/dist/Components/Table/Body/Rows/Columns/TableTextInput.svelte +197 -197
  62. package/dist/Components/Table/Body/Rows/Columns/ValidityCell.svelte +190 -190
  63. package/dist/Components/Table/Body/Rows/TableRow.svelte +290 -290
  64. package/dist/Components/Table/Headers/HighlightAllHeader.svelte +41 -41
  65. package/dist/Components/Table/Headers/SelectAllHeader.svelte +30 -30
  66. package/dist/Components/Table/Misc/SidePanel.svelte +35 -35
  67. package/dist/Components/Table/Misc/ToolboxPanel.svelte +100 -100
  68. package/dist/Components/Table/Misc/ToolboxPanelModal.svelte +107 -107
  69. package/dist/Components/TextArea.svelte +130 -130
  70. package/dist/Components/TextInput.svelte +176 -176
  71. package/dist/Components/ThreeStateRadio.svelte +131 -131
  72. package/dist/Components/Touch/BoolCard.svelte +45 -45
  73. package/dist/Components/Touch/DateModal.svelte +209 -209
  74. package/dist/Components/Touch/EditCard.svelte +59 -59
  75. package/dist/Components/Touch/InfoCard.svelte +31 -31
  76. package/dist/Components/Touch/InfoTextCard.svelte +28 -28
  77. package/dist/Components/Touch/ModalExplanation.svelte +17 -17
  78. package/dist/Components/Touch/NumberKeyboard.svelte +225 -225
  79. package/dist/Components/Touch/NumberModal.svelte +79 -79
  80. package/dist/Components/Touch/PlusMinusCard.svelte +46 -46
  81. package/dist/Components/Touch/SummaryCard.svelte +93 -93
  82. package/dist/Components/Touch/TextAreaModal.svelte +95 -95
  83. package/dist/Components/Touch/TextModal.svelte +106 -106
  84. package/dist/Components/Touch/TouchCard.svelte +33 -33
  85. package/dist/Components/Touch/TouchModal.svelte +274 -274
  86. package/dist/Components/Touch/UtilityButton.svelte +109 -109
  87. package/dist/Components/VerticalTabGroup.svelte +79 -79
  88. package/dist/Components/VerticalTabGroupButton.svelte +58 -58
  89. package/dist/Helpers/Datamatrix.d.ts +19 -19
  90. package/dist/Helpers/Datamatrix.js +291 -291
  91. package/dist/Types/Examples/ExampleModal.svelte +35 -35
  92. package/dist/scss/_motion.scss +57 -57
  93. package/dist/scss/_sizing.scss +85 -85
  94. package/package.json +30 -30
@@ -1,704 +1,714 @@
1
- <svelte:options runes />
2
-
3
- <script lang="ts">
4
- import { Colour } from '../../scss/colours.js';
5
- import { Size } from '../../Types/Internal/Size.js';
6
- import Button from '../Button.svelte';
7
- import Icon from '../Icon.svelte';
8
- import LoadingOverlay from '../LoadingOverlay.svelte';
9
- import { CalendarViewMode } from './AppointmentCalendarProps.js';
10
- import type {
11
- AppointmentCalendarProps,
12
- CalendarAppointment,
13
- DragSelection,
14
- } from './AppointmentCalendarProps.js';
15
-
16
- let {
17
- doors,
18
- appointments,
19
- selectedDate,
20
- viewMode,
21
- ondatechange,
22
- onviewmodechange,
23
- ondragcreate,
24
- onappointmentclick,
25
- onappointmentmove,
26
- startHour = 0,
27
- endHour = 24,
28
- slotIntervalMinutes = 15,
29
- isLoading = false,
30
- headerExtra,
31
- }: AppointmentCalendarProps = $props();
32
-
33
- /**
34
- * `selectedDate` is always read by the component, never written. The
35
- * runtime type may be either a plain `Date` or a `SvelteDate`; both
36
- * expose the same `Date` interface that we use here. Cast to `Date`
37
- * for narrowing inside the script.
38
- */
39
- const selected = $derived(selectedDate as Date);
40
-
41
- /**
42
- * Today's reference Date hoisted out of the per-cell loops so that
43
- * rendering the month grid does not allocate 42 fresh `Date`
44
- * instances on every state change. `$derived` does not invalidate
45
- * over time on its own; if you need real day-rollover semantics
46
- * track it with a `SvelteDate` and a `setInterval`.
47
- */
48
- const today = $derived(new Date());
49
-
50
- // ---- Date helpers ----
51
-
52
- const dayNames = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
53
- const monthNames = [
54
- 'January',
55
- 'February',
56
- 'March',
57
- 'April',
58
- 'May',
59
- 'June',
60
- 'July',
61
- 'August',
62
- 'September',
63
- 'October',
64
- 'November',
65
- 'December',
66
- ];
67
-
68
- function formatDate(d: Date): string {
69
- if (viewMode === CalendarViewMode.Month) {
70
- return `${monthNames[d.getMonth()]} ${d.getFullYear()}`;
71
- }
72
- return `${dayNames[d.getDay()]} ${d.getDate()} ${monthNames[d.getMonth()]} ${d.getFullYear()}`;
73
- }
74
-
75
- function sameDay(a: Date, b: Date): boolean {
76
- return (
77
- a.getFullYear() === b.getFullYear() &&
78
- a.getMonth() === b.getMonth() &&
79
- a.getDate() === b.getDate()
80
- );
81
- }
82
-
83
- function addDays(d: Date, n: number): Date {
84
- // eslint-disable-next-line svelte/prefer-svelte-reactivity
85
- const result = new Date(d);
86
- result.setDate(result.getDate() + n);
87
- return result;
88
- }
89
-
90
- function navigateDate(direction: number): void {
91
- if (viewMode === CalendarViewMode.Day) {
92
- ondatechange(addDays(selected, direction));
93
- } else if (viewMode === CalendarViewMode.Week) {
94
- ondatechange(addDays(selected, direction * 7));
95
- } else {
96
- // eslint-disable-next-line svelte/prefer-svelte-reactivity
97
- const d = new Date(selected);
98
- d.setMonth(d.getMonth() + direction);
99
- ondatechange(d);
100
- }
101
- }
102
-
103
- function goToToday(): void {
104
- ondatechange(new Date());
105
- }
106
-
107
- // ---- Time slot generation ----
108
-
109
- const timeSlots: Array<{ hour: number; minute: number; label: string }> = $derived.by(() => {
110
- const slots: Array<{ hour: number; minute: number; label: string }> = [];
111
- for (let h = startHour; h < endHour; h++) {
112
- for (let m = 0; m < 60; m += slotIntervalMinutes) {
113
- const hh = String(h).padStart(2, '0');
114
- const mm = String(m).padStart(2, '0');
115
- slots.push({ hour: h, minute: m, label: `${hh}:${mm}` });
116
- }
117
- }
118
- return slots;
119
- });
120
-
121
- // ---- Appointment positioning (day view) ----
122
-
123
- type PositionedAppointment = CalendarAppointment & {
124
- readonly topPercent: number;
125
- readonly heightPercent: number;
126
- };
127
-
128
- /**
129
- * Build a `YYYY-MM-DD` key for date bucketing. Avoids `toISOString`
130
- * timezone conversions that would smear appointments across days.
131
- */
132
- function dayKey(d: Date): string {
133
- const y = d.getFullYear();
134
- const m = String(d.getMonth() + 1).padStart(2, '0');
135
- const day = String(d.getDate()).padStart(2, '0');
136
- return `${y}-${m}-${day}`;
137
- }
138
-
139
- /**
140
- * Precomputed `Map<doorId, Map<dayKey, PositionedAppointment[]>>` for
141
- * day and week views. Replaces the previous per-cell
142
- * `appointments.filter(...)` calls which were `O(doors * appointments)`
143
- * per render and allocated a fresh `Date` per appointment per pass.
144
- */
145
- const positionedByDoorAndDay = $derived.by(() => {
146
- const totalMinutes = (endHour - startHour) * 60;
147
- // Local indexes built inside a $derived; outer reactivity already covers reads.
148
- // eslint-disable-next-line svelte/prefer-svelte-reactivity
149
- const byDoor = new Map<number, Map<string, Array<PositionedAppointment>>>();
150
- for (const apt of appointments) {
151
- const from = new Date(apt.dateFrom);
152
- const to = new Date(apt.dateTo);
153
- const startMin = (from.getHours() - startHour) * 60 + from.getMinutes();
154
- const endMin = (to.getHours() - startHour) * 60 + to.getMinutes();
155
- const durationMin = Math.max(endMin - startMin, slotIntervalMinutes);
156
- const positioned: PositionedAppointment = {
157
- ...apt,
158
- topPercent: (Math.max(0, startMin) / totalMinutes) * 100,
159
- heightPercent: (Math.min(durationMin, totalMinutes - startMin) / totalMinutes) * 100,
160
- };
161
- const key = dayKey(from);
162
- let perDay = byDoor.get(apt.segmentId);
163
- if (!perDay) {
164
- // eslint-disable-next-line svelte/prefer-svelte-reactivity
165
- perDay = new Map();
166
- byDoor.set(apt.segmentId, perDay);
167
- }
168
- const list = perDay.get(key);
169
- if (list) {
170
- list.push(positioned);
171
- } else {
172
- perDay.set(key, [positioned]);
173
- }
174
- }
175
- return byDoor;
176
- });
177
-
178
- function appointmentsAt(doorId: number, day: Date): ReadonlyArray<PositionedAppointment> {
179
- return positionedByDoorAndDay.get(doorId)?.get(dayKey(day)) ?? [];
180
- }
181
-
182
- /**
183
- * Precomputed appointment-count badges per day for the month view.
184
- * Replaces the previous `O(cells * doors * appointments)` recomputation
185
- * which scaled to ~42 000 ops on a single render with 10 doors and
186
- * 100 appointments.
187
- */
188
- const countsByDay = $derived.by(() => {
189
- // Local indexes built inside a $derived; outer reactivity already covers reads.
190
- // eslint-disable-next-line svelte/prefer-svelte-reactivity
191
- const map = new Map<string, Array<{ doorId: number; doorName: string; count: number }>>();
192
- // One scan over appointments builds a nested Map<dayKey, Map<doorId, count>>.
193
- // eslint-disable-next-line svelte/prefer-svelte-reactivity
194
- const intermediate = new Map<string, Map<number, number>>();
195
- for (const apt of appointments) {
196
- const key = dayKey(new Date(apt.dateFrom));
197
- let perDay = intermediate.get(key);
198
- if (!perDay) {
199
- // eslint-disable-next-line svelte/prefer-svelte-reactivity
200
- perDay = new Map();
201
- intermediate.set(key, perDay);
202
- }
203
- perDay.set(apt.segmentId, (perDay.get(apt.segmentId) ?? 0) + 1);
204
- }
205
- // Flatten to the door-ordered list the markup expects.
206
- for (const [key, perDay] of intermediate) {
207
- const list: Array<{ doorId: number; doorName: string; count: number }> = [];
208
- for (const door of doors) {
209
- const count = perDay.get(door.id);
210
- if (count) {
211
- list.push({ doorId: door.id, doorName: door.name, count });
212
- }
213
- }
214
- if (list.length > 0) {
215
- map.set(key, list);
216
- }
217
- }
218
- return map;
219
- });
220
-
221
- function countsAt(day: Date): ReadonlyArray<{ doorId: number; doorName: string; count: number }> {
222
- return countsByDay.get(dayKey(day)) ?? [];
223
- }
224
-
225
- // ---- Click and drag logic ----
226
-
227
- let isDragging = $state(false);
228
- let dragDoorId: number | null = $state(null);
229
- let dragStartSlotIndex: number | null = $state(null);
230
- let dragEndSlotIndex: number | null = $state(null);
231
-
232
- function onSlotMouseDown(doorId: number, slotIndex: number): void {
233
- if (!ondragcreate || appointmentDragStarted) {
234
- return;
235
- }
236
- isDragging = true;
237
- dragDoorId = doorId;
238
- dragStartSlotIndex = slotIndex;
239
- dragEndSlotIndex = slotIndex;
240
- }
241
-
242
- function onSlotMouseEnter(doorId: number, slotIndex: number): void {
243
- // Appointment move drag
244
- if (appointmentDragStarted) {
245
- isDraggingAppointment = true;
246
- moveTargetDoorId = doorId;
247
- moveTargetSlotIndex = slotIndex;
248
- return;
249
- }
250
- // Slot drag-create
251
- if (!isDragging || doorId !== dragDoorId) {
252
- return;
253
- }
254
- dragEndSlotIndex = slotIndex;
255
- }
256
-
257
- function onSlotMouseUp(): void {
258
- // ---- Handle appointment drag-move ----
259
- if (
260
- isDraggingAppointment &&
261
- draggedAppointment &&
262
- moveTargetDoorId != null &&
263
- moveTargetSlotIndex != null
264
- ) {
265
- const slot = timeSlots[moveTargetSlotIndex];
266
- // eslint-disable-next-line svelte/prefer-svelte-reactivity
267
- const newDateFrom = new Date(selected);
268
- newDateFrom.setHours(slot.hour, slot.minute, 0, 0);
269
- const newDateTo = new Date(
270
- newDateFrom.getTime() + draggedAptSlotCount * slotIntervalMinutes * 60000
271
- );
272
-
273
- // Check whether the position actually changed
274
- const origFrom = new Date(draggedAppointment.dateFrom);
275
- const samePosition =
276
- moveTargetDoorId === draggedAppointment.segmentId &&
277
- newDateFrom.getTime() === origFrom.getTime();
278
-
279
- if (samePosition) {
280
- // Dropped in the same spot - treat as a click
281
- onappointmentclick?.(draggedAppointment);
282
- } else if (!hasOverlap(moveTargetDoorId, newDateFrom, newDateTo, draggedAppointment.id)) {
283
- const door = doors.find((d) => d.id === moveTargetDoorId);
284
- onappointmentmove?.({
285
- appointment: draggedAppointment,
286
- newDoorId: moveTargetDoorId,
287
- newDoorName: door?.name ?? '',
288
- newDateFrom,
289
- newDateTo,
290
- });
291
- }
292
-
293
- resetAppointmentDrag();
294
- return;
295
- }
296
-
297
- // ---- Handle appointment click (mousedown + mouseup without leaving the block) ----
298
- if (appointmentDragStarted && !isDraggingAppointment && draggedAppointment) {
299
- onappointmentclick?.(draggedAppointment);
300
- resetAppointmentDrag();
301
- return;
302
- }
303
-
304
- resetAppointmentDrag();
305
-
306
- // ---- Handle drag-create ----
307
- if (
308
- !isDragging ||
309
- dragDoorId == null ||
310
- dragStartSlotIndex == null ||
311
- dragEndSlotIndex == null
312
- ) {
313
- return;
314
- }
315
-
316
- const startIdx = Math.min(dragStartSlotIndex, dragEndSlotIndex);
317
- const endIdx = Math.max(dragStartSlotIndex, dragEndSlotIndex);
318
-
319
- const startSlot = timeSlots[startIdx];
320
- const endSlot = timeSlots[endIdx];
321
-
322
- // eslint-disable-next-line svelte/prefer-svelte-reactivity
323
- const dateFrom = new Date(selected);
324
- dateFrom.setHours(startSlot.hour, startSlot.minute, 0, 0);
325
-
326
- // eslint-disable-next-line svelte/prefer-svelte-reactivity
327
- const dateTo = new Date(selected);
328
- // End slot is the start of the last selected slot; add one interval for the end time
329
- dateTo.setHours(endSlot.hour, endSlot.minute + slotIntervalMinutes, 0, 0);
330
-
331
- const door = doors.find((d) => d.id === dragDoorId);
332
-
333
- const selection: DragSelection = {
334
- doorId: dragDoorId,
335
- doorName: door?.name ?? '',
336
- dateFrom,
337
- dateTo,
338
- };
339
-
340
- isDragging = false;
341
- dragDoorId = null;
342
- dragStartSlotIndex = null;
343
- dragEndSlotIndex = null;
344
-
345
- ondragcreate?.(selection);
346
- }
347
-
348
- function isSlotInDragRange(doorId: number, slotIndex: number): boolean {
349
- if (!isDragging || doorId !== dragDoorId) {
350
- return false;
351
- }
352
- if (dragStartSlotIndex == null || dragEndSlotIndex == null) {
353
- return false;
354
- }
355
- const min = Math.min(dragStartSlotIndex, dragEndSlotIndex);
356
- const max = Math.max(dragStartSlotIndex, dragEndSlotIndex);
357
- return slotIndex >= min && slotIndex <= max;
358
- }
359
-
360
- // ---- Row hover tracking ----
361
-
362
- let hoveredSlotIndex: number | null = $state(null);
363
-
364
- // ---- Appointment drag-move logic ----
365
-
366
- let appointmentDragStarted = $state(false);
367
- let isDraggingAppointment = $state(false);
368
- let draggedAppointment: CalendarAppointment | null = $state(null);
369
- let draggedAptSlotCount = $state(0);
370
- let moveTargetDoorId: number | null = $state(null);
371
- let moveTargetSlotIndex: number | null = $state(null);
372
-
373
- function onAppointmentMouseDown(apt: CalendarAppointment, e: MouseEvent): void {
374
- if (!onappointmentmove) {
375
- return;
376
- }
377
- e.preventDefault();
378
- appointmentDragStarted = true;
379
- draggedAppointment = apt;
380
-
381
- const from = new Date(apt.dateFrom);
382
- const to = new Date(apt.dateTo);
383
- const durationMin = (to.getTime() - from.getTime()) / 60000;
384
- draggedAptSlotCount = Math.max(1, Math.ceil(durationMin / slotIntervalMinutes));
385
- }
386
-
387
- function resetAppointmentDrag(): void {
388
- appointmentDragStarted = false;
389
- isDraggingAppointment = false;
390
- draggedAppointment = null;
391
- draggedAptSlotCount = 0;
392
- moveTargetDoorId = null;
393
- moveTargetSlotIndex = null;
394
- }
395
-
396
- function isSlotInMoveTarget(doorId: number, slotIndex: number): boolean {
397
- if (!isDraggingAppointment || moveTargetDoorId !== doorId) {
398
- return false;
399
- }
400
- if (moveTargetSlotIndex == null) {
401
- return false;
402
- }
403
- return (
404
- slotIndex >= moveTargetSlotIndex && slotIndex < moveTargetSlotIndex + draggedAptSlotCount
405
- );
406
- }
407
-
408
- function hasOverlap(doorId: number, dateFrom: Date, dateTo: Date, excludeAptId: number): boolean {
409
- return appointments.some((apt) => {
410
- if (apt.id === excludeAptId) {
411
- return false;
412
- }
413
- if (apt.segmentId !== doorId) {
414
- return false;
415
- }
416
- const aptFrom = new Date(apt.dateFrom);
417
- const aptTo = new Date(apt.dateTo);
418
- return dateFrom < aptTo && dateTo > aptFrom;
419
- });
420
- }
421
-
422
- // ---- Month view helpers ----
423
-
424
- function getMonthDays(date: Date): Array<{ date: Date; isCurrentMonth: boolean }> {
425
- const year = date.getFullYear();
426
- const month = date.getMonth();
427
-
428
- const firstDayOfMonth = new Date(year, month, 1);
429
-
430
- // Start from Monday of the week containing the first day
431
- // eslint-disable-next-line svelte/prefer-svelte-reactivity
432
- const startDate = new Date(firstDayOfMonth);
433
- const dayOfWeek = startDate.getDay();
434
- const daysFromMonday = dayOfWeek === 0 ? 6 : dayOfWeek - 1;
435
- startDate.setDate(startDate.getDate() - daysFromMonday);
436
-
437
- const days: Array<{ date: Date; isCurrentMonth: boolean }> = [];
438
- // eslint-disable-next-line svelte/prefer-svelte-reactivity
439
- const current = new Date(startDate);
440
-
441
- // Generate 6 weeks (42 days) to fill the grid
442
- for (let i = 0; i < 42; i++) {
443
- days.push({
444
- date: new Date(current),
445
- isCurrentMonth: current.getMonth() === month,
446
- });
447
- current.setDate(current.getDate() + 1);
448
- }
449
-
450
- return days;
451
- }
452
-
453
- /** Cached month grid; rebuilt only when `selected` changes. */
454
- const monthDays = $derived(getMonthDays(selected));
455
-
456
- // ---- Week view helpers ----
457
-
458
- function getWeekDays(date: Date): Array<Date> {
459
- // eslint-disable-next-line svelte/prefer-svelte-reactivity
460
- const d = new Date(date);
461
- const day = d.getDay();
462
- const mondayOffset = day === 0 ? -6 : 1 - day;
463
- d.setDate(d.getDate() + mondayOffset);
464
-
465
- const week: Array<Date> = [];
466
- for (let i = 0; i < 7; i++) {
467
- week.push(new Date(d));
468
- d.setDate(d.getDate() + 1);
469
- }
470
- return week;
471
- }
472
-
473
- const weekDays = $derived(getWeekDays(selected));
474
-
475
- // ---- View mode buttons ----
476
-
477
- const viewModes: ReadonlyArray<{ mode: CalendarViewMode; label: string }> = [
478
- { mode: CalendarViewMode.Day, label: 'Day' },
479
- { mode: CalendarViewMode.Week, label: 'Week' },
480
- { mode: CalendarViewMode.Month, label: 'Month' },
481
- ];
482
- </script>
483
-
484
- <!-- svelte-ignore a11y_no_static_element_interactions -->
485
- <!-- svelte-ignore a11y_no_noninteractive_element_interactions -->
486
- <div
487
- class="appointment-calendar"
488
- class:is-moving-appointment={isDraggingAppointment}
489
- onmouseup={onSlotMouseUp}
490
- role="application"
491
- >
492
- <!-- Header: navigation + view toggle -->
493
- <div class="calendar-header">
494
- <div class="header-left">
495
- <Button
496
- label="Today"
497
- size={Size.Small}
498
- onclick={goToToday}
499
- />
500
- <div class="nav-arrows">
501
- <button
502
- class="nav-btn"
503
- onclick={() => {
504
- navigateDate(-1);
505
- }}
506
- aria-label="Previous"
507
- >
508
- <Icon
509
- name="chevron-left"
510
- size={Size.Small}
511
- colour={Colour['$ui-blue-14']}
512
- />
513
- </button>
514
- <button
515
- class="nav-btn"
516
- onclick={() => {
517
- navigateDate(1);
518
- }}
519
- aria-label="Next"
520
- >
521
- <Icon
522
- name="chevron-right"
523
- size={Size.Small}
524
- colour={Colour['$ui-blue-14']}
525
- />
526
- </button>
527
- </div>
528
- <h2 class="current-date-label">{formatDate(selected)}</h2>
529
- </div>
530
- <div class="header-right">
531
- {#if headerExtra}
532
- {@render headerExtra()}
533
- {/if}
534
- <div class="view-toggle">
535
- {#each viewModes as { mode, label } (mode)}
536
- <button
537
- class="view-btn"
538
- class:active={viewMode === mode}
539
- onclick={() => {
540
- onviewmodechange(mode);
541
- }}
542
- >
543
- {label}
544
- </button>
545
- {/each}
546
- </div>
547
- </div>
548
- </div>
549
-
550
- <!-- Week day tabs rendered OUTSIDE the scrollable body so they stay frozen -->
551
- {#if viewMode === CalendarViewMode.Week}
552
- <div class="week-day-tabs">
553
- {#each weekDays as day (day.getTime())}
554
- <button
555
- class="week-day-tab"
556
- class:active={sameDay(day, selected)}
557
- class:today={sameDay(day, today)}
558
- onclick={() => {
559
- ondatechange(day);
560
- }}
561
- >
562
- <span class="day-name">{dayNames[day.getDay()].slice(0, 3)}</span>
563
- <span class="day-num">{day.getDate()}</span>
564
- </button>
565
- {/each}
566
- </div>
567
- {/if}
568
-
569
- <!-- Calendar body -->
570
- <div class="calendar-body">
571
- {#if isLoading}
572
- <LoadingOverlay />
573
- {/if}
574
-
575
- {#if viewMode === CalendarViewMode.Day}
576
- <!-- DAY VIEW -->
577
- <!-- svelte-ignore a11y_no_static_element_interactions -->
578
- <div
579
- class="day-view"
580
- onmouseleave={() => {
581
- hoveredSlotIndex = null;
582
- }}
583
- >
584
- <!-- eslint-disable-next-line @typescript-eslint/no-confusing-void-expression -->
585
- {@render doorGrid(selected)}
586
- </div>
587
- {:else if viewMode === CalendarViewMode.Week}
588
- <!-- WEEK VIEW: day grid only, tabs are above calendar-body -->
589
- <!-- svelte-ignore a11y_no_static_element_interactions -->
590
- <div
591
- class="day-view"
592
- onmouseleave={() => {
593
- hoveredSlotIndex = null;
594
- }}
595
- >
596
- <!-- eslint-disable-next-line @typescript-eslint/no-confusing-void-expression -->
597
- {@render doorGrid(selected)}
598
- </div>
599
- {:else}
600
- <!-- MONTH VIEW -->
601
- <div class="month-view">
602
- <div class="month-header-row">
603
- {#each ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] as dayLabel (dayLabel)}
604
- <div class="month-day-header">{dayLabel}</div>
605
- {/each}
606
- </div>
607
- <div class="month-grid">
608
- {#each monthDays as { date: dayDate, isCurrentMonth } (dayDate.getTime())}
609
- <button
610
- class="month-day-cell"
611
- class:other-month={!isCurrentMonth}
612
- class:today={sameDay(dayDate, today)}
613
- class:selected={sameDay(dayDate, selected)}
614
- onclick={() => {
615
- ondatechange(dayDate);
616
- onviewmodechange(CalendarViewMode.Day);
617
- }}
618
- >
619
- <span class="day-number">{dayDate.getDate()}</span>
620
- <div class="day-badges">
621
- {#each countsAt(dayDate) as { doorId, doorName, count } (doorId)}
622
- <span class="door-badge">
623
- {doorName}: {count}
624
- </span>
625
- {/each}
626
- </div>
627
- </button>
628
- {/each}
629
- </div>
630
- </div>
631
- {/if}
632
- </div>
633
- </div>
634
-
635
- {#snippet doorGrid(day: Date)}
636
- <div class="grid-header">
637
- <div class="time-header">Time</div>
638
- {#each doors as door (door.id)}
639
- <div class="door-header">{door.name}</div>
640
- {/each}
641
- </div>
642
- <div class="grid-body">
643
- <div class="time-column">
644
- {#each timeSlots as slot, slotIdx (slot.hour * 60 + slot.minute)}
645
- <div
646
- class="time-label"
647
- class:hour-start={slot.minute === 0}
648
- class:row-hover={hoveredSlotIndex === slotIdx}
649
- >
650
- {#if slot.minute === 0}
651
- <span>{slot.label}</span>
652
- {/if}
653
- </div>
654
- {/each}
655
- </div>
656
- {#each doors as door (door.id)}
657
- <div class="door-column">
658
- <!-- Slot cells for drag interaction (rendered first, sit below appointments) -->
659
- {#each timeSlots as slot, slotIdx (slot.hour * 60 + slot.minute)}
660
- <!-- svelte-ignore a11y_no_static_element_interactions -->
661
- <div
662
- class="slot-cell"
663
- class:hour-start={slot.minute === 0}
664
- class:drag-selected={isSlotInDragRange(door.id, slotIdx)}
665
- class:move-target={isSlotInMoveTarget(door.id, slotIdx)}
666
- class:row-hover={hoveredSlotIndex === slotIdx}
667
- onmousedown={() => {
668
- onSlotMouseDown(door.id, slotIdx);
669
- }}
670
- onmouseenter={() => {
671
- hoveredSlotIndex = slotIdx;
672
- onSlotMouseEnter(door.id, slotIdx);
673
- }}
674
- ></div>
675
- {/each}
676
- <!-- Appointment blocks positioned absolutely (rendered after, sit above slots) -->
677
- {#each appointmentsAt(door.id, day) as apt (apt.id)}
678
- <!-- svelte-ignore a11y_no_static_element_interactions -->
679
- <div
680
- class="appointment-block"
681
- class:inbound={apt.typeCode === 'INBOUND'}
682
- class:outbound={apt.typeCode === 'OUTBOUND'}
683
- class:dragging={isDraggingAppointment && draggedAppointment?.id === apt.id}
684
- class:movable={!!onappointmentmove}
685
- style="top: {apt.topPercent}%; height: {apt.heightPercent}%;"
686
- onmousedown={(e) => {
687
- onAppointmentMouseDown(apt, e);
688
- }}
689
- >
690
- <span class="apt-type">{apt.typeCode}</span>
691
- <span class="apt-label">{apt.label}</span>
692
- {#if apt.sublabel}
693
- <span class="apt-sublabel">{apt.sublabel}</span>
694
- {/if}
695
- </div>
696
- {/each}
697
- </div>
698
- {/each}
699
- </div>
700
- {/snippet}
701
-
1
+ <svelte:options runes />
2
+
3
+ <script lang="ts">
4
+ import { Colour } from '../../scss/colours.js';
5
+ import { Size } from '../../Types/Internal/Size.js';
6
+ import Button from '../Button.svelte';
7
+ import Icon from '../Icon.svelte';
8
+ import LoadingOverlay from '../LoadingOverlay.svelte';
9
+ import { CalendarViewMode } from './AppointmentCalendarProps.js';
10
+ import type {
11
+ AppointmentCalendarProps,
12
+ CalendarAppointment,
13
+ DragSelection,
14
+ } from './AppointmentCalendarProps.js';
15
+
16
+ let {
17
+ doors,
18
+ appointments,
19
+ selectedDate,
20
+ viewMode,
21
+ ondatechange,
22
+ onviewmodechange,
23
+ ondragcreate,
24
+ onappointmentclick,
25
+ onappointmentmove,
26
+ startHour = 0,
27
+ endHour = 24,
28
+ slotIntervalMinutes = 15,
29
+ isLoading = false,
30
+ headerExtra,
31
+ }: AppointmentCalendarProps = $props();
32
+
33
+ /**
34
+ * `selectedDate` is always read by the component, never written. The
35
+ * runtime type may be either a plain `Date` or a `SvelteDate`; both
36
+ * expose the same `Date` interface that we use here. Cast to `Date`
37
+ * for narrowing inside the script.
38
+ */
39
+ const selected = $derived(selectedDate as Date);
40
+
41
+ /**
42
+ * Today's reference Date hoisted out of the per-cell loops so that
43
+ * rendering the month grid does not allocate 42 fresh `Date`
44
+ * instances on every state change. `$derived` does not invalidate
45
+ * over time on its own; if you need real day-rollover semantics
46
+ * track it with a `SvelteDate` and a `setInterval`.
47
+ */
48
+ const today = $derived(new Date());
49
+
50
+ // ---- Date helpers ----
51
+
52
+ const dayNames = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
53
+ const monthNames = [
54
+ 'January',
55
+ 'February',
56
+ 'March',
57
+ 'April',
58
+ 'May',
59
+ 'June',
60
+ 'July',
61
+ 'August',
62
+ 'September',
63
+ 'October',
64
+ 'November',
65
+ 'December',
66
+ ];
67
+
68
+ function formatDate(d: Date): string {
69
+ if (viewMode === CalendarViewMode.Month) {
70
+ return `${monthNames[d.getMonth()]} ${d.getFullYear()}`;
71
+ }
72
+ return `${dayNames[d.getDay()]} ${d.getDate()} ${monthNames[d.getMonth()]} ${d.getFullYear()}`;
73
+ }
74
+
75
+ function sameDay(a: Date, b: Date): boolean {
76
+ return (
77
+ a.getFullYear() === b.getFullYear() &&
78
+ a.getMonth() === b.getMonth() &&
79
+ a.getDate() === b.getDate()
80
+ );
81
+ }
82
+
83
+ function addDays(d: Date, n: number): Date {
84
+ // eslint-disable-next-line svelte/prefer-svelte-reactivity
85
+ const result = new Date(d);
86
+ result.setDate(result.getDate() + n);
87
+ return result;
88
+ }
89
+
90
+ function navigateDate(direction: number): void {
91
+ if (viewMode === CalendarViewMode.Day) {
92
+ ondatechange(addDays(selected, direction));
93
+ } else if (viewMode === CalendarViewMode.Week) {
94
+ ondatechange(addDays(selected, direction * 7));
95
+ } else {
96
+ // eslint-disable-next-line svelte/prefer-svelte-reactivity
97
+ const d = new Date(selected);
98
+ d.setMonth(d.getMonth() + direction);
99
+ ondatechange(d);
100
+ }
101
+ }
102
+
103
+ function goToToday(): void {
104
+ ondatechange(new Date());
105
+ }
106
+
107
+ // ---- Time slot generation ----
108
+
109
+ const timeSlots: Array<{ hour: number; minute: number; label: string }> = $derived.by(() => {
110
+ const slots: Array<{ hour: number; minute: number; label: string }> = [];
111
+ for (let h = startHour; h < endHour; h++) {
112
+ for (let m = 0; m < 60; m += slotIntervalMinutes) {
113
+ const hh = String(h).padStart(2, '0');
114
+ const mm = String(m).padStart(2, '0');
115
+ slots.push({ hour: h, minute: m, label: `${hh}:${mm}` });
116
+ }
117
+ }
118
+ return slots;
119
+ });
120
+
121
+ // ---- Appointment positioning (day view) ----
122
+
123
+ type PositionedAppointment = CalendarAppointment & {
124
+ readonly topPercent: number;
125
+ readonly heightPercent: number;
126
+ };
127
+
128
+ /**
129
+ * Build a `YYYY-MM-DD` key for date bucketing. Avoids `toISOString`
130
+ * timezone conversions that would smear appointments across days.
131
+ */
132
+ function dayKey(d: Date): string {
133
+ const y = d.getFullYear();
134
+ const m = String(d.getMonth() + 1).padStart(2, '0');
135
+ const day = String(d.getDate()).padStart(2, '0');
136
+ return `${y}-${m}-${day}`;
137
+ }
138
+
139
+ /**
140
+ * Precomputed `Map<doorId, Map<dayKey, PositionedAppointment[]>>` for
141
+ * day and week views. Replaces the previous per-cell
142
+ * `appointments.filter(...)` calls which were `O(doors * appointments)`
143
+ * per render and allocated a fresh `Date` per appointment per pass.
144
+ */
145
+ const positionedByDoorAndDay = $derived.by(() => {
146
+ const totalMinutes = (endHour - startHour) * 60;
147
+ // Local indexes built inside a $derived; outer reactivity already covers reads.
148
+ // eslint-disable-next-line svelte/prefer-svelte-reactivity
149
+ const byDoor = new Map<number, Map<string, Array<PositionedAppointment>>>();
150
+ for (const apt of appointments) {
151
+ const from = new Date(apt.dateFrom);
152
+ const to = new Date(apt.dateTo);
153
+ const startMin = (from.getHours() - startHour) * 60 + from.getMinutes();
154
+ const endMin = (to.getHours() - startHour) * 60 + to.getMinutes();
155
+ const durationMin = Math.max(endMin - startMin, slotIntervalMinutes);
156
+ const positioned: PositionedAppointment = {
157
+ ...apt,
158
+ topPercent: (Math.max(0, startMin) / totalMinutes) * 100,
159
+ heightPercent: (Math.min(durationMin, totalMinutes - startMin) / totalMinutes) * 100,
160
+ };
161
+ const key = dayKey(from);
162
+ let perDay = byDoor.get(apt.segmentId);
163
+ if (!perDay) {
164
+ // eslint-disable-next-line svelte/prefer-svelte-reactivity
165
+ perDay = new Map();
166
+ byDoor.set(apt.segmentId, perDay);
167
+ }
168
+ const list = perDay.get(key);
169
+ if (list) {
170
+ list.push(positioned);
171
+ } else {
172
+ perDay.set(key, [positioned]);
173
+ }
174
+ }
175
+ return byDoor;
176
+ });
177
+
178
+ function appointmentsAt(doorId: number, day: Date): ReadonlyArray<PositionedAppointment> {
179
+ return positionedByDoorAndDay.get(doorId)?.get(dayKey(day)) ?? [];
180
+ }
181
+
182
+ /**
183
+ * Precomputed appointment-count badges per day for the month view.
184
+ * Replaces the previous `O(cells * doors * appointments)` recomputation
185
+ * which scaled to ~42 000 ops on a single render with 10 doors and
186
+ * 100 appointments.
187
+ */
188
+ const countsByDay = $derived.by(() => {
189
+ // Local indexes built inside a $derived; outer reactivity already covers reads.
190
+ // eslint-disable-next-line svelte/prefer-svelte-reactivity
191
+ const map = new Map<string, Array<{ doorId: number; doorName: string; count: number }>>();
192
+ // One scan over appointments builds a nested Map<dayKey, Map<doorId, count>>.
193
+ // eslint-disable-next-line svelte/prefer-svelte-reactivity
194
+ const intermediate = new Map<string, Map<number, number>>();
195
+ for (const apt of appointments) {
196
+ const key = dayKey(new Date(apt.dateFrom));
197
+ let perDay = intermediate.get(key);
198
+ if (!perDay) {
199
+ // eslint-disable-next-line svelte/prefer-svelte-reactivity
200
+ perDay = new Map();
201
+ intermediate.set(key, perDay);
202
+ }
203
+ perDay.set(apt.segmentId, (perDay.get(apt.segmentId) ?? 0) + 1);
204
+ }
205
+ // Flatten to the door-ordered list the markup expects.
206
+ for (const [key, perDay] of intermediate) {
207
+ const list: Array<{ doorId: number; doorName: string; count: number }> = [];
208
+ for (const door of doors) {
209
+ const count = perDay.get(door.id);
210
+ if (count) {
211
+ list.push({ doorId: door.id, doorName: door.name, count });
212
+ }
213
+ }
214
+ if (list.length > 0) {
215
+ map.set(key, list);
216
+ }
217
+ }
218
+ return map;
219
+ });
220
+
221
+ function countsAt(day: Date): ReadonlyArray<{ doorId: number; doorName: string; count: number }> {
222
+ return countsByDay.get(dayKey(day)) ?? [];
223
+ }
224
+
225
+ // ---- Click and drag logic ----
226
+
227
+ let isDragging = $state(false);
228
+ let dragDoorId: number | null = $state(null);
229
+ let dragStartSlotIndex: number | null = $state(null);
230
+ let dragEndSlotIndex: number | null = $state(null);
231
+
232
+ function onSlotMouseDown(doorId: number, slotIndex: number, e: MouseEvent): void {
233
+ // Only start a drag-create on the primary (left) button. Otherwise a
234
+ // middle-click (autoscroll) or right-click would open the create modal.
235
+ if (e.button !== 0) {
236
+ return;
237
+ }
238
+ if (!ondragcreate || appointmentDragStarted) {
239
+ return;
240
+ }
241
+ isDragging = true;
242
+ dragDoorId = doorId;
243
+ dragStartSlotIndex = slotIndex;
244
+ dragEndSlotIndex = slotIndex;
245
+ }
246
+
247
+ function onSlotMouseEnter(doorId: number, slotIndex: number): void {
248
+ // Appointment move drag
249
+ if (appointmentDragStarted) {
250
+ isDraggingAppointment = true;
251
+ moveTargetDoorId = doorId;
252
+ moveTargetSlotIndex = slotIndex;
253
+ return;
254
+ }
255
+ // Slot drag-create
256
+ if (!isDragging || doorId !== dragDoorId) {
257
+ return;
258
+ }
259
+ dragEndSlotIndex = slotIndex;
260
+ }
261
+
262
+ function onSlotMouseUp(): void {
263
+ // ---- Handle appointment drag-move ----
264
+ if (
265
+ isDraggingAppointment &&
266
+ draggedAppointment &&
267
+ moveTargetDoorId != null &&
268
+ moveTargetSlotIndex != null
269
+ ) {
270
+ const slot = timeSlots[moveTargetSlotIndex];
271
+ // eslint-disable-next-line svelte/prefer-svelte-reactivity
272
+ const newDateFrom = new Date(selected);
273
+ newDateFrom.setHours(slot.hour, slot.minute, 0, 0);
274
+ const newDateTo = new Date(
275
+ newDateFrom.getTime() + draggedAptSlotCount * slotIntervalMinutes * 60000
276
+ );
277
+
278
+ // Check whether the position actually changed
279
+ const origFrom = new Date(draggedAppointment.dateFrom);
280
+ const samePosition =
281
+ moveTargetDoorId === draggedAppointment.segmentId &&
282
+ newDateFrom.getTime() === origFrom.getTime();
283
+
284
+ if (samePosition) {
285
+ // Dropped in the same spot - treat as a click
286
+ onappointmentclick?.(draggedAppointment);
287
+ } else if (!hasOverlap(moveTargetDoorId, newDateFrom, newDateTo, draggedAppointment.id)) {
288
+ const door = doors.find((d) => d.id === moveTargetDoorId);
289
+ onappointmentmove?.({
290
+ appointment: draggedAppointment,
291
+ newDoorId: moveTargetDoorId,
292
+ newDoorName: door?.name ?? '',
293
+ newDateFrom,
294
+ newDateTo,
295
+ });
296
+ }
297
+
298
+ resetAppointmentDrag();
299
+ return;
300
+ }
301
+
302
+ // ---- Handle appointment click (mousedown + mouseup without leaving the block) ----
303
+ if (appointmentDragStarted && !isDraggingAppointment && draggedAppointment) {
304
+ onappointmentclick?.(draggedAppointment);
305
+ resetAppointmentDrag();
306
+ return;
307
+ }
308
+
309
+ resetAppointmentDrag();
310
+
311
+ // ---- Handle drag-create ----
312
+ if (
313
+ !isDragging ||
314
+ dragDoorId == null ||
315
+ dragStartSlotIndex == null ||
316
+ dragEndSlotIndex == null
317
+ ) {
318
+ return;
319
+ }
320
+
321
+ const startIdx = Math.min(dragStartSlotIndex, dragEndSlotIndex);
322
+ const endIdx = Math.max(dragStartSlotIndex, dragEndSlotIndex);
323
+
324
+ const startSlot = timeSlots[startIdx];
325
+ const endSlot = timeSlots[endIdx];
326
+
327
+ // eslint-disable-next-line svelte/prefer-svelte-reactivity
328
+ const dateFrom = new Date(selected);
329
+ dateFrom.setHours(startSlot.hour, startSlot.minute, 0, 0);
330
+
331
+ // eslint-disable-next-line svelte/prefer-svelte-reactivity
332
+ const dateTo = new Date(selected);
333
+ // End slot is the start of the last selected slot; add one interval for the end time
334
+ dateTo.setHours(endSlot.hour, endSlot.minute + slotIntervalMinutes, 0, 0);
335
+
336
+ const door = doors.find((d) => d.id === dragDoorId);
337
+
338
+ const selection: DragSelection = {
339
+ doorId: dragDoorId,
340
+ doorName: door?.name ?? '',
341
+ dateFrom,
342
+ dateTo,
343
+ };
344
+
345
+ isDragging = false;
346
+ dragDoorId = null;
347
+ dragStartSlotIndex = null;
348
+ dragEndSlotIndex = null;
349
+
350
+ ondragcreate?.(selection);
351
+ }
352
+
353
+ function isSlotInDragRange(doorId: number, slotIndex: number): boolean {
354
+ if (!isDragging || doorId !== dragDoorId) {
355
+ return false;
356
+ }
357
+ if (dragStartSlotIndex == null || dragEndSlotIndex == null) {
358
+ return false;
359
+ }
360
+ const min = Math.min(dragStartSlotIndex, dragEndSlotIndex);
361
+ const max = Math.max(dragStartSlotIndex, dragEndSlotIndex);
362
+ return slotIndex >= min && slotIndex <= max;
363
+ }
364
+
365
+ // ---- Row hover tracking ----
366
+
367
+ let hoveredSlotIndex: number | null = $state(null);
368
+
369
+ // ---- Appointment drag-move logic ----
370
+
371
+ let appointmentDragStarted = $state(false);
372
+ let isDraggingAppointment = $state(false);
373
+ let draggedAppointment: CalendarAppointment | null = $state(null);
374
+ let draggedAptSlotCount = $state(0);
375
+ let moveTargetDoorId: number | null = $state(null);
376
+ let moveTargetSlotIndex: number | null = $state(null);
377
+
378
+ function onAppointmentMouseDown(apt: CalendarAppointment, e: MouseEvent): void {
379
+ // Only react to the primary (left) button so middle/right clicks don't
380
+ // start a move or register as an appointment click.
381
+ if (e.button !== 0) {
382
+ return;
383
+ }
384
+ if (!onappointmentmove) {
385
+ return;
386
+ }
387
+ e.preventDefault();
388
+ appointmentDragStarted = true;
389
+ draggedAppointment = apt;
390
+
391
+ const from = new Date(apt.dateFrom);
392
+ const to = new Date(apt.dateTo);
393
+ const durationMin = (to.getTime() - from.getTime()) / 60000;
394
+ draggedAptSlotCount = Math.max(1, Math.ceil(durationMin / slotIntervalMinutes));
395
+ }
396
+
397
+ function resetAppointmentDrag(): void {
398
+ appointmentDragStarted = false;
399
+ isDraggingAppointment = false;
400
+ draggedAppointment = null;
401
+ draggedAptSlotCount = 0;
402
+ moveTargetDoorId = null;
403
+ moveTargetSlotIndex = null;
404
+ }
405
+
406
+ function isSlotInMoveTarget(doorId: number, slotIndex: number): boolean {
407
+ if (!isDraggingAppointment || moveTargetDoorId !== doorId) {
408
+ return false;
409
+ }
410
+ if (moveTargetSlotIndex == null) {
411
+ return false;
412
+ }
413
+ return (
414
+ slotIndex >= moveTargetSlotIndex && slotIndex < moveTargetSlotIndex + draggedAptSlotCount
415
+ );
416
+ }
417
+
418
+ function hasOverlap(doorId: number, dateFrom: Date, dateTo: Date, excludeAptId: number): boolean {
419
+ return appointments.some((apt) => {
420
+ if (apt.id === excludeAptId) {
421
+ return false;
422
+ }
423
+ if (apt.segmentId !== doorId) {
424
+ return false;
425
+ }
426
+ const aptFrom = new Date(apt.dateFrom);
427
+ const aptTo = new Date(apt.dateTo);
428
+ return dateFrom < aptTo && dateTo > aptFrom;
429
+ });
430
+ }
431
+
432
+ // ---- Month view helpers ----
433
+
434
+ function getMonthDays(date: Date): Array<{ date: Date; isCurrentMonth: boolean }> {
435
+ const year = date.getFullYear();
436
+ const month = date.getMonth();
437
+
438
+ const firstDayOfMonth = new Date(year, month, 1);
439
+
440
+ // Start from Monday of the week containing the first day
441
+ // eslint-disable-next-line svelte/prefer-svelte-reactivity
442
+ const startDate = new Date(firstDayOfMonth);
443
+ const dayOfWeek = startDate.getDay();
444
+ const daysFromMonday = dayOfWeek === 0 ? 6 : dayOfWeek - 1;
445
+ startDate.setDate(startDate.getDate() - daysFromMonday);
446
+
447
+ const days: Array<{ date: Date; isCurrentMonth: boolean }> = [];
448
+ // eslint-disable-next-line svelte/prefer-svelte-reactivity
449
+ const current = new Date(startDate);
450
+
451
+ // Generate 6 weeks (42 days) to fill the grid
452
+ for (let i = 0; i < 42; i++) {
453
+ days.push({
454
+ date: new Date(current),
455
+ isCurrentMonth: current.getMonth() === month,
456
+ });
457
+ current.setDate(current.getDate() + 1);
458
+ }
459
+
460
+ return days;
461
+ }
462
+
463
+ /** Cached month grid; rebuilt only when `selected` changes. */
464
+ const monthDays = $derived(getMonthDays(selected));
465
+
466
+ // ---- Week view helpers ----
467
+
468
+ function getWeekDays(date: Date): Array<Date> {
469
+ // eslint-disable-next-line svelte/prefer-svelte-reactivity
470
+ const d = new Date(date);
471
+ const day = d.getDay();
472
+ const mondayOffset = day === 0 ? -6 : 1 - day;
473
+ d.setDate(d.getDate() + mondayOffset);
474
+
475
+ const week: Array<Date> = [];
476
+ for (let i = 0; i < 7; i++) {
477
+ week.push(new Date(d));
478
+ d.setDate(d.getDate() + 1);
479
+ }
480
+ return week;
481
+ }
482
+
483
+ const weekDays = $derived(getWeekDays(selected));
484
+
485
+ // ---- View mode buttons ----
486
+
487
+ const viewModes: ReadonlyArray<{ mode: CalendarViewMode; label: string }> = [
488
+ { mode: CalendarViewMode.Day, label: 'Day' },
489
+ { mode: CalendarViewMode.Week, label: 'Week' },
490
+ { mode: CalendarViewMode.Month, label: 'Month' },
491
+ ];
492
+ </script>
493
+
494
+ <!-- svelte-ignore a11y_no_static_element_interactions -->
495
+ <!-- svelte-ignore a11y_no_noninteractive_element_interactions -->
496
+ <div
497
+ class="appointment-calendar"
498
+ class:is-moving-appointment={isDraggingAppointment}
499
+ onmouseup={onSlotMouseUp}
500
+ role="application"
501
+ >
502
+ <!-- Header: navigation + view toggle -->
503
+ <div class="calendar-header">
504
+ <div class="header-left">
505
+ <Button
506
+ label="Today"
507
+ size={Size.Small}
508
+ onclick={goToToday}
509
+ />
510
+ <div class="nav-arrows">
511
+ <button
512
+ class="nav-btn"
513
+ onclick={() => {
514
+ navigateDate(-1);
515
+ }}
516
+ aria-label="Previous"
517
+ >
518
+ <Icon
519
+ name="chevron-left"
520
+ size={Size.Small}
521
+ colour={Colour['$ui-blue-14']}
522
+ />
523
+ </button>
524
+ <button
525
+ class="nav-btn"
526
+ onclick={() => {
527
+ navigateDate(1);
528
+ }}
529
+ aria-label="Next"
530
+ >
531
+ <Icon
532
+ name="chevron-right"
533
+ size={Size.Small}
534
+ colour={Colour['$ui-blue-14']}
535
+ />
536
+ </button>
537
+ </div>
538
+ <h2 class="current-date-label">{formatDate(selected)}</h2>
539
+ </div>
540
+ <div class="header-right">
541
+ {#if headerExtra}
542
+ {@render headerExtra()}
543
+ {/if}
544
+ <div class="view-toggle">
545
+ {#each viewModes as { mode, label } (mode)}
546
+ <button
547
+ class="view-btn"
548
+ class:active={viewMode === mode}
549
+ onclick={() => {
550
+ onviewmodechange(mode);
551
+ }}
552
+ >
553
+ {label}
554
+ </button>
555
+ {/each}
556
+ </div>
557
+ </div>
558
+ </div>
559
+
560
+ <!-- Week day tabs rendered OUTSIDE the scrollable body so they stay frozen -->
561
+ {#if viewMode === CalendarViewMode.Week}
562
+ <div class="week-day-tabs">
563
+ {#each weekDays as day (day.getTime())}
564
+ <button
565
+ class="week-day-tab"
566
+ class:active={sameDay(day, selected)}
567
+ class:today={sameDay(day, today)}
568
+ onclick={() => {
569
+ ondatechange(day);
570
+ }}
571
+ >
572
+ <span class="day-name">{dayNames[day.getDay()].slice(0, 3)}</span>
573
+ <span class="day-num">{day.getDate()}</span>
574
+ </button>
575
+ {/each}
576
+ </div>
577
+ {/if}
578
+
579
+ <!-- Calendar body -->
580
+ <div class="calendar-body">
581
+ {#if isLoading}
582
+ <LoadingOverlay />
583
+ {/if}
584
+
585
+ {#if viewMode === CalendarViewMode.Day}
586
+ <!-- DAY VIEW -->
587
+ <!-- svelte-ignore a11y_no_static_element_interactions -->
588
+ <div
589
+ class="day-view"
590
+ onmouseleave={() => {
591
+ hoveredSlotIndex = null;
592
+ }}
593
+ >
594
+ <!-- eslint-disable-next-line @typescript-eslint/no-confusing-void-expression -->
595
+ {@render doorGrid(selected)}
596
+ </div>
597
+ {:else if viewMode === CalendarViewMode.Week}
598
+ <!-- WEEK VIEW: day grid only, tabs are above calendar-body -->
599
+ <!-- svelte-ignore a11y_no_static_element_interactions -->
600
+ <div
601
+ class="day-view"
602
+ onmouseleave={() => {
603
+ hoveredSlotIndex = null;
604
+ }}
605
+ >
606
+ <!-- eslint-disable-next-line @typescript-eslint/no-confusing-void-expression -->
607
+ {@render doorGrid(selected)}
608
+ </div>
609
+ {:else}
610
+ <!-- MONTH VIEW -->
611
+ <div class="month-view">
612
+ <div class="month-header-row">
613
+ {#each ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] as dayLabel (dayLabel)}
614
+ <div class="month-day-header">{dayLabel}</div>
615
+ {/each}
616
+ </div>
617
+ <div class="month-grid">
618
+ {#each monthDays as { date: dayDate, isCurrentMonth } (dayDate.getTime())}
619
+ <button
620
+ class="month-day-cell"
621
+ class:other-month={!isCurrentMonth}
622
+ class:today={sameDay(dayDate, today)}
623
+ class:selected={sameDay(dayDate, selected)}
624
+ onclick={() => {
625
+ ondatechange(dayDate);
626
+ onviewmodechange(CalendarViewMode.Day);
627
+ }}
628
+ >
629
+ <span class="day-number">{dayDate.getDate()}</span>
630
+ <div class="day-badges">
631
+ {#each countsAt(dayDate) as { doorId, doorName, count } (doorId)}
632
+ <span class="door-badge">
633
+ {doorName}: {count}
634
+ </span>
635
+ {/each}
636
+ </div>
637
+ </button>
638
+ {/each}
639
+ </div>
640
+ </div>
641
+ {/if}
642
+ </div>
643
+ </div>
644
+
645
+ {#snippet doorGrid(day: Date)}
646
+ <div class="grid-header">
647
+ <div class="time-header">Time</div>
648
+ {#each doors as door (door.id)}
649
+ <div class="door-header">{door.name}</div>
650
+ {/each}
651
+ </div>
652
+ <div class="grid-body">
653
+ <div class="time-column">
654
+ {#each timeSlots as slot, slotIdx (slot.hour * 60 + slot.minute)}
655
+ <div
656
+ class="time-label"
657
+ class:hour-start={slot.minute === 0}
658
+ class:row-hover={hoveredSlotIndex === slotIdx}
659
+ >
660
+ {#if slot.minute === 0}
661
+ <span>{slot.label}</span>
662
+ {/if}
663
+ </div>
664
+ {/each}
665
+ </div>
666
+ {#each doors as door (door.id)}
667
+ <div class="door-column">
668
+ <!-- Slot cells for drag interaction (rendered first, sit below appointments) -->
669
+ {#each timeSlots as slot, slotIdx (slot.hour * 60 + slot.minute)}
670
+ <!-- svelte-ignore a11y_no_static_element_interactions -->
671
+ <div
672
+ class="slot-cell"
673
+ class:hour-start={slot.minute === 0}
674
+ class:drag-selected={isSlotInDragRange(door.id, slotIdx)}
675
+ class:move-target={isSlotInMoveTarget(door.id, slotIdx)}
676
+ class:row-hover={hoveredSlotIndex === slotIdx}
677
+ onmousedown={(e) => {
678
+ onSlotMouseDown(door.id, slotIdx, e);
679
+ }}
680
+ onmouseenter={() => {
681
+ hoveredSlotIndex = slotIdx;
682
+ onSlotMouseEnter(door.id, slotIdx);
683
+ }}
684
+ ></div>
685
+ {/each}
686
+ <!-- Appointment blocks positioned absolutely (rendered after, sit above slots) -->
687
+ {#each appointmentsAt(door.id, day) as apt (apt.id)}
688
+ <!-- svelte-ignore a11y_no_static_element_interactions -->
689
+ <div
690
+ class="appointment-block"
691
+ class:inbound={apt.typeCode === 'INBOUND'}
692
+ class:outbound={apt.typeCode === 'OUTBOUND'}
693
+ class:dragging={isDraggingAppointment && draggedAppointment?.id === apt.id}
694
+ class:movable={!!onappointmentmove}
695
+ style="top: {apt.topPercent}%; height: {apt.heightPercent}%;"
696
+ onmousedown={(e) => {
697
+ onAppointmentMouseDown(apt, e);
698
+ }}
699
+ >
700
+ <span class="apt-type">{apt.typeCode}</span>
701
+ <span class="apt-label">{apt.label}</span>
702
+ {#if apt.sublabel}
703
+ <span class="apt-sublabel">{apt.sublabel}</span>
704
+ {/if}
705
+ </div>
706
+ {/each}
707
+ </div>
708
+ {/each}
709
+ </div>
710
+ {/snippet}
711
+
702
712
  <style>.appointment-calendar {
703
713
  display: flex;
704
714
  flex-flow: column nowrap;
@@ -1123,4 +1133,4 @@
1123
1133
  white-space: nowrap;
1124
1134
  overflow: hidden;
1125
1135
  text-overflow: ellipsis;
1126
- }</style>
1136
+ }</style>