@lavalogic/scoria 0.40.0 → 0.40.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (137) hide show
  1. package/README.md +58 -58
  2. package/dist/Components/AccordionGroup.svelte +46 -46
  3. package/dist/Components/AccordionGroupButton.svelte +76 -76
  4. package/dist/Components/Action.svelte +136 -136
  5. package/dist/Components/AlertModal.svelte +195 -195
  6. package/dist/Components/AppointmentCalendar/AppointmentCalendar.svelte +729 -729
  7. package/dist/Components/Base/BaseModal.svelte +125 -125
  8. package/dist/Components/Base/ContextWrapper.svelte +72 -72
  9. package/dist/Components/Base/Pagination.svelte +198 -198
  10. package/dist/Components/Base/Snippets.svelte +36 -36
  11. package/dist/Components/BigRadioSet.svelte +38 -38
  12. package/dist/Components/Bubble.svelte +101 -101
  13. package/dist/Components/Button.svelte +209 -209
  14. package/dist/Components/Checkbox.svelte +86 -86
  15. package/dist/Components/CollapsibleCard.svelte +78 -78
  16. package/dist/Components/Contexts/ContextMenu.svelte +164 -164
  17. package/dist/Components/Contexts/ContextMenuDivider.svelte +15 -15
  18. package/dist/Components/Contexts/ContextMenuOption.svelte +60 -60
  19. package/dist/Components/Contexts/Toast.svelte +86 -86
  20. package/dist/Components/Contexts/ToastContainer.svelte +65 -65
  21. package/dist/Components/Contexts/Tooltip.svelte +37 -37
  22. package/dist/Components/DataMatrixIcon.svelte +112 -112
  23. package/dist/Components/DateInput.svelte +148 -148
  24. package/dist/Components/DatePicker.svelte +300 -300
  25. package/dist/Components/DesktopModal.svelte +90 -90
  26. package/dist/Components/Dial.svelte +204 -204
  27. package/dist/Components/DimensionInput.svelte +170 -170
  28. package/dist/Components/DragMenu/DragMenuHolder.svelte +119 -119
  29. package/dist/Components/DragMenu/DraggableCard.svelte +77 -77
  30. package/dist/Components/FileCard.svelte +24 -24
  31. package/dist/Components/FileUpload.svelte +236 -236
  32. package/dist/Components/GridInput.svelte +196 -196
  33. package/dist/Components/GridInputSet.svelte +29 -29
  34. package/dist/Components/HorizontalTabGroup.svelte +82 -82
  35. package/dist/Components/HorizontalTabGroupButton.svelte +44 -44
  36. package/dist/Components/Icon.svelte +128 -128
  37. package/dist/Components/Icons.js +357 -357
  38. package/dist/Components/InfoAlert.svelte +35 -35
  39. package/dist/Components/LoadingAnimation.svelte +29 -29
  40. package/dist/Components/LoadingModal.svelte +45 -45
  41. package/dist/Components/LoadingOverlay.svelte +25 -25
  42. package/dist/Components/Modal.svelte +258 -258
  43. package/dist/Components/MultiSelect.svelte +220 -220
  44. package/dist/Components/Nav/Nav.svelte +110 -110
  45. package/dist/Components/Nav/NavServiceMenuList.svelte +43 -43
  46. package/dist/Components/Nav/NavTab.svelte +62 -62
  47. package/dist/Components/Nav/ServiceMenuItem.svelte +112 -112
  48. package/dist/Components/Nav/ServicesNav.svelte +80 -80
  49. package/dist/Components/NumberInput.svelte +157 -157
  50. package/dist/Components/PageHeading.svelte +25 -25
  51. package/dist/Components/PasswordInput.svelte +88 -88
  52. package/dist/Components/Portal.svelte +36 -36
  53. package/dist/Components/ProgressBubble.svelte +107 -107
  54. package/dist/Components/QuerySelect.svelte +366 -366
  55. package/dist/Components/SingleSelect.svelte +250 -250
  56. package/dist/Components/StepButton.svelte +70 -70
  57. package/dist/Components/StepForm.svelte +140 -140
  58. package/dist/Components/Switch.svelte +69 -69
  59. package/dist/Components/Table/ARCHITECTURE.md +298 -298
  60. package/dist/Components/Table/Body/QuickSearchCell.svelte +679 -679
  61. package/dist/Components/Table/Body/Rows/ColumnHighlight.svelte +51 -51
  62. package/dist/Components/Table/Body/Rows/ColumnList.svelte +59 -59
  63. package/dist/Components/Table/Body/Rows/ColumnListRow.svelte +454 -454
  64. package/dist/Components/Table/Body/Rows/Columns/AccessorComponent.svelte +79 -79
  65. package/dist/Components/Table/Body/Rows/Columns/ActionsCell.svelte +185 -185
  66. package/dist/Components/Table/Body/Rows/Columns/BubbleCell.svelte +124 -124
  67. package/dist/Components/Table/Body/Rows/Columns/ExpandCell.svelte +131 -120
  68. package/dist/Components/Table/Body/Rows/Columns/FocusableImmutableCell.svelte +234 -234
  69. package/dist/Components/Table/Body/Rows/Columns/ProgressCell.svelte +105 -105
  70. package/dist/Components/Table/Body/Rows/Columns/TableAction.svelte +87 -87
  71. package/dist/Components/Table/Body/Rows/Columns/TableCheckbox.svelte +126 -126
  72. package/dist/Components/Table/Body/Rows/Columns/TableColumn.svelte +159 -159
  73. package/dist/Components/Table/Body/Rows/Columns/TableDatePicker.svelte +246 -246
  74. package/dist/Components/Table/Body/Rows/Columns/TableNumberInput.svelte +216 -216
  75. package/dist/Components/Table/Body/Rows/Columns/TableQuerySelect.svelte +252 -252
  76. package/dist/Components/Table/Body/Rows/Columns/TableRowSelectionCheckbox.svelte +179 -179
  77. package/dist/Components/Table/Body/Rows/Columns/TableSelect.svelte +221 -221
  78. package/dist/Components/Table/Body/Rows/Columns/TableTextInput.svelte +197 -197
  79. package/dist/Components/Table/Body/Rows/Columns/ValidityCell.svelte +190 -190
  80. package/dist/Components/Table/Body/Rows/TableRow.svelte +290 -290
  81. package/dist/Components/Table/Body/TableBody.svelte +155 -155
  82. package/dist/Components/Table/ColumnFactory.svelte.js +1 -0
  83. package/dist/Components/Table/Headers/HighlightAllHeader.svelte +41 -41
  84. package/dist/Components/Table/Headers/SelectAllHeader.svelte +30 -30
  85. package/dist/Components/Table/Headers/TableHead.svelte +415 -415
  86. package/dist/Components/Table/Misc/ColumnPanel.svelte +39 -39
  87. package/dist/Components/Table/Misc/ColumnPanelModal.svelte +39 -39
  88. package/dist/Components/Table/Misc/FilterInput.svelte +641 -641
  89. package/dist/Components/Table/Misc/FilterPanel.svelte +190 -190
  90. package/dist/Components/Table/Misc/FilterPanelModal.svelte +31 -31
  91. package/dist/Components/Table/Misc/ShareViewModal.svelte +291 -291
  92. package/dist/Components/Table/Misc/SidePanel.svelte +35 -35
  93. package/dist/Components/Table/Misc/TableConfigurationModal.svelte +644 -644
  94. package/dist/Components/Table/Misc/TableFooter.svelte +340 -340
  95. package/dist/Components/Table/Misc/TableHorizontalBar.svelte +140 -140
  96. package/dist/Components/Table/Misc/TableSidebar.svelte +200 -200
  97. package/dist/Components/Table/Misc/TableViewDropdown.svelte +105 -105
  98. package/dist/Components/Table/Misc/ToolboxPanel.svelte +100 -100
  99. package/dist/Components/Table/Misc/ToolboxPanelModal.svelte +107 -107
  100. package/dist/Components/Table/Misc/UpdateViewOptionsModal.svelte +192 -192
  101. package/dist/Components/Table/NestedTable.svelte +130 -130
  102. package/dist/Components/Table/Table.svelte +692 -692
  103. package/dist/Components/Table/Types/Columns/Definitions/Expand/ExpandDef.svelte.d.ts +5 -0
  104. package/dist/Components/Table/Types/Columns/Definitions/Expand/ExpandDef.svelte.js +3 -0
  105. package/dist/Components/Table/Types/Public/ColumnOptions.d.ts +10 -0
  106. package/dist/Components/Test/TestContextConsumer.svelte +13 -13
  107. package/dist/Components/TextArea.svelte +130 -130
  108. package/dist/Components/TextInput.svelte +176 -176
  109. package/dist/Components/ThreeStateRadio.svelte +131 -131
  110. package/dist/Components/Touch/BoolCard.svelte +45 -45
  111. package/dist/Components/Touch/DateModal.svelte +209 -209
  112. package/dist/Components/Touch/EditCard.svelte +59 -59
  113. package/dist/Components/Touch/InfoCard.svelte +31 -31
  114. package/dist/Components/Touch/InfoTextCard.svelte +28 -28
  115. package/dist/Components/Touch/ModalExplanation.svelte +17 -17
  116. package/dist/Components/Touch/NumberKeyboard.svelte +225 -225
  117. package/dist/Components/Touch/NumberModal.svelte +79 -79
  118. package/dist/Components/Touch/PlusMinusCard.svelte +46 -46
  119. package/dist/Components/Touch/SelectModal.svelte +127 -127
  120. package/dist/Components/Touch/SummaryCard.svelte +93 -93
  121. package/dist/Components/Touch/TextAreaModal.svelte +95 -95
  122. package/dist/Components/Touch/TextModal.svelte +106 -106
  123. package/dist/Components/Touch/TouchCard.svelte +33 -33
  124. package/dist/Components/Touch/TouchModal.svelte +274 -274
  125. package/dist/Components/Touch/UtilityButton.svelte +109 -109
  126. package/dist/Components/VerticalTabGroup.svelte +79 -79
  127. package/dist/Components/VerticalTabGroupButton.svelte +58 -58
  128. package/dist/Helpers/Datamatrix.d.ts +19 -19
  129. package/dist/Helpers/Datamatrix.js +291 -291
  130. package/dist/Types/Examples/ExampleModal.svelte +35 -35
  131. package/dist/scss/_basics.scss +12 -12
  132. package/dist/scss/_colours.scss +134 -134
  133. package/dist/scss/_mixins.scss +3392 -3392
  134. package/dist/scss/_motion.scss +57 -57
  135. package/dist/scss/_sizing.scss +85 -85
  136. package/dist/scss/_transitions.scss +8 -8
  137. package/package.json +1 -1
@@ -1,731 +1,731 @@
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, e: MouseEvent): void {
248
- // If a drag is in progress but the primary button is no longer held, the
249
- // pointer-up happened somewhere we did not observe (e.g. outside the
250
- // calendar). Reset so we do not "drag" without the button being pressed.
251
- if ((isDragging || appointmentDragStarted) && (e.buttons & 1) === 0) {
252
- isDragging = false;
253
- dragDoorId = null;
254
- dragStartSlotIndex = null;
255
- dragEndSlotIndex = null;
256
- resetAppointmentDrag();
257
- return;
258
- }
259
- // Appointment move drag
260
- if (appointmentDragStarted) {
261
- isDraggingAppointment = true;
262
- moveTargetDoorId = doorId;
263
- moveTargetSlotIndex = slotIndex;
264
- return;
265
- }
266
- // Slot drag-create
267
- if (!isDragging || doorId !== dragDoorId) {
268
- return;
269
- }
270
- dragEndSlotIndex = slotIndex;
271
- }
272
-
273
- function onSlotMouseUp(): void {
274
- // ---- Handle appointment drag-move ----
275
- if (
276
- isDraggingAppointment &&
277
- draggedAppointment &&
278
- moveTargetDoorId != null &&
279
- moveTargetSlotIndex != null
280
- ) {
281
- const slot = timeSlots[moveTargetSlotIndex];
282
- // eslint-disable-next-line svelte/prefer-svelte-reactivity
283
- const newDateFrom = new Date(selected);
284
- newDateFrom.setHours(slot.hour, slot.minute, 0, 0);
285
- const newDateTo = new Date(
286
- newDateFrom.getTime() + draggedAptSlotCount * slotIntervalMinutes * 60000
287
- );
288
-
289
- // Check whether the position actually changed
290
- const origFrom = new Date(draggedAppointment.dateFrom);
291
- const samePosition =
292
- moveTargetDoorId === draggedAppointment.segmentId &&
293
- newDateFrom.getTime() === origFrom.getTime();
294
-
295
- if (samePosition) {
296
- // Dropped in the same spot - treat as a click
297
- onappointmentclick?.(draggedAppointment);
298
- } else if (!hasOverlap(moveTargetDoorId, newDateFrom, newDateTo, draggedAppointment.id)) {
299
- const door = doors.find((d) => d.id === moveTargetDoorId);
300
- onappointmentmove?.({
301
- appointment: draggedAppointment,
302
- newDoorId: moveTargetDoorId,
303
- newDoorName: door?.name ?? '',
304
- newDateFrom,
305
- newDateTo,
306
- });
307
- }
308
-
309
- resetAppointmentDrag();
310
- return;
311
- }
312
-
313
- // ---- Handle appointment click (mousedown + mouseup without leaving the block) ----
314
- if (appointmentDragStarted && !isDraggingAppointment && draggedAppointment) {
315
- onappointmentclick?.(draggedAppointment);
316
- resetAppointmentDrag();
317
- return;
318
- }
319
-
320
- resetAppointmentDrag();
321
-
322
- // ---- Handle drag-create ----
323
- if (
324
- !isDragging ||
325
- dragDoorId == null ||
326
- dragStartSlotIndex == null ||
327
- dragEndSlotIndex == null
328
- ) {
329
- return;
330
- }
331
-
332
- const startIdx = Math.min(dragStartSlotIndex, dragEndSlotIndex);
333
- const endIdx = Math.max(dragStartSlotIndex, dragEndSlotIndex);
334
-
335
- const startSlot = timeSlots[startIdx];
336
- const endSlot = timeSlots[endIdx];
337
-
338
- // eslint-disable-next-line svelte/prefer-svelte-reactivity
339
- const dateFrom = new Date(selected);
340
- dateFrom.setHours(startSlot.hour, startSlot.minute, 0, 0);
341
-
342
- // eslint-disable-next-line svelte/prefer-svelte-reactivity
343
- const dateTo = new Date(selected);
344
- // End slot is the start of the last selected slot; add one interval for the end time
345
- dateTo.setHours(endSlot.hour, endSlot.minute + slotIntervalMinutes, 0, 0);
346
-
347
- const door = doors.find((d) => d.id === dragDoorId);
348
-
349
- const selection: DragSelection = {
350
- doorId: dragDoorId,
351
- doorName: door?.name ?? '',
352
- dateFrom,
353
- dateTo,
354
- };
355
-
356
- isDragging = false;
357
- dragDoorId = null;
358
- dragStartSlotIndex = null;
359
- dragEndSlotIndex = null;
360
-
361
- ondragcreate?.(selection);
362
- }
363
-
364
- function isSlotInDragRange(doorId: number, slotIndex: number): boolean {
365
- if (!isDragging || doorId !== dragDoorId) {
366
- return false;
367
- }
368
- if (dragStartSlotIndex == null || dragEndSlotIndex == null) {
369
- return false;
370
- }
371
- const min = Math.min(dragStartSlotIndex, dragEndSlotIndex);
372
- const max = Math.max(dragStartSlotIndex, dragEndSlotIndex);
373
- return slotIndex >= min && slotIndex <= max;
374
- }
375
-
376
- // ---- Row hover tracking ----
377
-
378
- let hoveredSlotIndex: number | null = $state(null);
379
-
380
- // ---- Appointment drag-move logic ----
381
-
382
- let appointmentDragStarted = $state(false);
383
- let isDraggingAppointment = $state(false);
384
- let draggedAppointment: CalendarAppointment | null = $state(null);
385
- let draggedAptSlotCount = $state(0);
386
- let moveTargetDoorId: number | null = $state(null);
387
- let moveTargetSlotIndex: number | null = $state(null);
388
-
389
- function onAppointmentMouseDown(apt: CalendarAppointment, e: MouseEvent): void {
390
- // Only react to the primary (left) button so middle/right clicks don't
391
- // start a move or register as an appointment click.
392
- if (e.button !== 0) {
393
- return;
394
- }
395
- if (!onappointmentmove) {
396
- return;
397
- }
398
- e.preventDefault();
399
- appointmentDragStarted = true;
400
- draggedAppointment = apt;
401
-
402
- const from = new Date(apt.dateFrom);
403
- const to = new Date(apt.dateTo);
404
- const durationMin = (to.getTime() - from.getTime()) / 60000;
405
- draggedAptSlotCount = Math.max(1, Math.ceil(durationMin / slotIntervalMinutes));
406
- }
407
-
408
- function resetAppointmentDrag(): void {
409
- appointmentDragStarted = false;
410
- isDraggingAppointment = false;
411
- draggedAppointment = null;
412
- draggedAptSlotCount = 0;
413
- moveTargetDoorId = null;
414
- moveTargetSlotIndex = null;
415
- }
416
-
417
- function isSlotInMoveTarget(doorId: number, slotIndex: number): boolean {
418
- if (!isDraggingAppointment || moveTargetDoorId !== doorId) {
419
- return false;
420
- }
421
- if (moveTargetSlotIndex == null) {
422
- return false;
423
- }
424
- return (
425
- slotIndex >= moveTargetSlotIndex && slotIndex < moveTargetSlotIndex + draggedAptSlotCount
426
- );
427
- }
428
-
429
- function hasOverlap(doorId: number, dateFrom: Date, dateTo: Date, excludeAptId: number): boolean {
430
- return appointments.some((apt) => {
431
- if (apt.id === excludeAptId) {
432
- return false;
433
- }
434
- if (apt.segmentId !== doorId) {
435
- return false;
436
- }
437
- const aptFrom = new Date(apt.dateFrom);
438
- const aptTo = new Date(apt.dateTo);
439
- return dateFrom < aptTo && dateTo > aptFrom;
440
- });
441
- }
442
-
443
- // ---- Month view helpers ----
444
-
445
- function getMonthDays(date: Date): Array<{ date: Date; isCurrentMonth: boolean }> {
446
- const year = date.getFullYear();
447
- const month = date.getMonth();
448
-
449
- const firstDayOfMonth = new Date(year, month, 1);
450
-
451
- // Start from Monday of the week containing the first day
452
- // eslint-disable-next-line svelte/prefer-svelte-reactivity
453
- const startDate = new Date(firstDayOfMonth);
454
- const dayOfWeek = startDate.getDay();
455
- const daysFromMonday = dayOfWeek === 0 ? 6 : dayOfWeek - 1;
456
- startDate.setDate(startDate.getDate() - daysFromMonday);
457
-
458
- const days: Array<{ date: Date; isCurrentMonth: boolean }> = [];
459
- // eslint-disable-next-line svelte/prefer-svelte-reactivity
460
- const current = new Date(startDate);
461
-
462
- // Generate 6 weeks (42 days) to fill the grid
463
- for (let i = 0; i < 42; i++) {
464
- days.push({
465
- date: new Date(current),
466
- isCurrentMonth: current.getMonth() === month,
467
- });
468
- current.setDate(current.getDate() + 1);
469
- }
470
-
471
- return days;
472
- }
473
-
474
- /** Cached month grid; rebuilt only when `selected` changes. */
475
- const monthDays = $derived(getMonthDays(selected));
476
-
477
- // ---- Week view helpers ----
478
-
479
- function getWeekDays(date: Date): Array<Date> {
480
- // eslint-disable-next-line svelte/prefer-svelte-reactivity
481
- const d = new Date(date);
482
- const day = d.getDay();
483
- const mondayOffset = day === 0 ? -6 : 1 - day;
484
- d.setDate(d.getDate() + mondayOffset);
485
-
486
- const week: Array<Date> = [];
487
- for (let i = 0; i < 7; i++) {
488
- week.push(new Date(d));
489
- d.setDate(d.getDate() + 1);
490
- }
491
- return week;
492
- }
493
-
494
- const weekDays = $derived(getWeekDays(selected));
495
-
496
- // ---- View mode buttons ----
497
-
498
- const viewModes: ReadonlyArray<{ mode: CalendarViewMode; label: string }> = [
499
- { mode: CalendarViewMode.Day, label: 'Day' },
500
- { mode: CalendarViewMode.Week, label: 'Week' },
501
- { mode: CalendarViewMode.Month, label: 'Month' },
502
- ];
503
- </script>
504
-
505
- <!-- A drag can end anywhere on the page (the pointer is often released outside
506
- the calendar when sweeping across columns). Listen on the window so the
507
- drag state is always finalised and never left "stuck" for the next drag. -->
508
- <svelte:window onmouseup={onSlotMouseUp} />
509
-
510
- <!-- svelte-ignore a11y_no_static_element_interactions -->
511
- <!-- svelte-ignore a11y_no_noninteractive_element_interactions -->
512
- <div
513
- class="appointment-calendar"
514
- class:is-moving-appointment={isDraggingAppointment}
515
- role="application"
516
- >
517
- <!-- Header: navigation + view toggle -->
518
- <div class="calendar-header">
519
- <div class="header-left">
520
- <Button
521
- label="Today"
522
- size={Size.Small}
523
- onclick={goToToday}
524
- >
525
- Today
526
- </Button>
527
- <div class="nav-arrows">
528
- <button
529
- class="nav-btn"
530
- onclick={() => {
531
- navigateDate(-1);
532
- }}
533
- aria-label="Previous"
534
- >
535
- <Icon
536
- name="chevron-left"
537
- size={Size.Small}
538
- colour={Colour['$ui-blue-14']}
539
- />
540
- </button>
541
- <button
542
- class="nav-btn"
543
- onclick={() => {
544
- navigateDate(1);
545
- }}
546
- aria-label="Next"
547
- >
548
- <Icon
549
- name="chevron-right"
550
- size={Size.Small}
551
- colour={Colour['$ui-blue-14']}
552
- />
553
- </button>
554
- </div>
555
- <h2 class="current-date-label">{formatDate(selected)}</h2>
556
- </div>
557
- <div class="header-right">
558
- {#if headerExtra}
559
- {@render headerExtra()}
560
- {/if}
561
- <div class="view-toggle">
562
- {#each viewModes as { mode, label } (mode)}
563
- <button
564
- class="view-btn"
565
- class:active={viewMode === mode}
566
- onclick={() => {
567
- onviewmodechange(mode);
568
- }}
569
- >
570
- {label}
571
- </button>
572
- {/each}
573
- </div>
574
- </div>
575
- </div>
576
-
577
- <!-- Week day tabs rendered OUTSIDE the scrollable body so they stay frozen -->
578
- {#if viewMode === CalendarViewMode.Week}
579
- <div class="week-day-tabs">
580
- {#each weekDays as day (day.getTime())}
581
- <button
582
- class="week-day-tab"
583
- class:active={sameDay(day, selected)}
584
- class:today={sameDay(day, today)}
585
- onclick={() => {
586
- ondatechange(day);
587
- }}
588
- >
589
- <span class="day-name">{dayNames[day.getDay()].slice(0, 3)}</span>
590
- <span class="day-num">{day.getDate()}</span>
591
- </button>
592
- {/each}
593
- </div>
594
- {/if}
595
-
596
- <!-- Calendar body -->
597
- <div class="calendar-body">
598
- {#if isLoading}
599
- <LoadingOverlay />
600
- {/if}
601
-
602
- {#if viewMode === CalendarViewMode.Day}
603
- <!-- DAY VIEW -->
604
- <!-- svelte-ignore a11y_no_static_element_interactions -->
605
- <div
606
- class="day-view"
607
- onmouseleave={() => {
608
- hoveredSlotIndex = null;
609
- }}
610
- >
611
- <!-- eslint-disable-next-line @typescript-eslint/no-confusing-void-expression -->
612
- {@render doorGrid(selected)}
613
- </div>
614
- {:else if viewMode === CalendarViewMode.Week}
615
- <!-- WEEK VIEW: day grid only, tabs are above calendar-body -->
616
- <!-- svelte-ignore a11y_no_static_element_interactions -->
617
- <div
618
- class="day-view"
619
- onmouseleave={() => {
620
- hoveredSlotIndex = null;
621
- }}
622
- >
623
- <!-- eslint-disable-next-line @typescript-eslint/no-confusing-void-expression -->
624
- {@render doorGrid(selected)}
625
- </div>
626
- {:else}
627
- <!-- MONTH VIEW -->
628
- <div class="month-view">
629
- <div class="month-header-row">
630
- {#each ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] as dayLabel (dayLabel)}
631
- <div class="month-day-header">{dayLabel}</div>
632
- {/each}
633
- </div>
634
- <div class="month-grid">
635
- {#each monthDays as { date: dayDate, isCurrentMonth } (dayDate.getTime())}
636
- <button
637
- class="month-day-cell"
638
- class:other-month={!isCurrentMonth}
639
- class:today={sameDay(dayDate, today)}
640
- class:selected={sameDay(dayDate, selected)}
641
- onclick={() => {
642
- ondatechange(dayDate);
643
- onviewmodechange(CalendarViewMode.Day);
644
- }}
645
- >
646
- <span class="day-number">{dayDate.getDate()}</span>
647
- <div class="day-badges">
648
- {#each countsAt(dayDate) as { doorId, doorName, count } (doorId)}
649
- <span class="door-badge">
650
- {doorName}: {count}
651
- </span>
652
- {/each}
653
- </div>
654
- </button>
655
- {/each}
656
- </div>
657
- </div>
658
- {/if}
659
- </div>
660
- </div>
661
-
662
- {#snippet doorGrid(day: Date)}
663
- <div class="grid-header">
664
- <div class="time-header">Time</div>
665
- {#each doors as door (door.id)}
666
- <div class="door-header">{door.name}</div>
667
- {/each}
668
- </div>
669
- <div class="grid-body">
670
- <div class="time-column">
671
- {#each timeSlots as slot, slotIdx (slot.hour * 60 + slot.minute)}
672
- <div
673
- class="time-label"
674
- class:hour-start={slot.minute === 0}
675
- class:row-hover={hoveredSlotIndex === slotIdx}
676
- >
677
- {#if slot.minute === 0}
678
- <span>{slot.label}</span>
679
- {/if}
680
- </div>
681
- {/each}
682
- </div>
683
- {#each doors as door (door.id)}
684
- <div class="door-column">
685
- <!-- Slot cells for drag interaction (rendered first, sit below appointments) -->
686
- {#each timeSlots as slot, slotIdx (slot.hour * 60 + slot.minute)}
687
- <!-- svelte-ignore a11y_no_static_element_interactions -->
688
- <div
689
- class="slot-cell"
690
- class:hour-start={slot.minute === 0}
691
- class:drag-selected={isSlotInDragRange(door.id, slotIdx)}
692
- class:move-target={isSlotInMoveTarget(door.id, slotIdx)}
693
- class:row-hover={hoveredSlotIndex === slotIdx}
694
- onmousedown={(e) => {
695
- onSlotMouseDown(door.id, slotIdx, e);
696
- }}
697
- onmouseenter={(e) => {
698
- hoveredSlotIndex = slotIdx;
699
- onSlotMouseEnter(door.id, slotIdx, e);
700
- }}
701
- ></div>
702
- {/each}
703
- <!-- Appointment blocks positioned absolutely (rendered after, sit above slots) -->
704
- {#each appointmentsAt(door.id, day) as apt (apt.id)}
705
- <!-- svelte-ignore a11y_no_static_element_interactions -->
706
- <div
707
- class="appointment-block"
708
- class:inbound={apt.typeCode === 'INBOUND'}
709
- class:outbound={apt.typeCode === 'OUTBOUND'}
710
- class:dragging={isDraggingAppointment && draggedAppointment?.id === apt.id}
711
- class:movable={!!onappointmentmove}
712
- style="top: {apt.topPercent}%; height: {apt.heightPercent}%;"
713
- onmousedown={(e) => {
714
- onAppointmentMouseDown(apt, e);
715
- }}
716
- >
717
- <span class="apt-type">{apt.typeCode}</span>
718
- <span class="apt-label">{apt.label}</span>
719
- {#if apt.sublabel}
720
- <span class="apt-sublabel">{apt.sublabel}</span>
721
- {/if}
722
- </div>
723
- {/each}
724
- </div>
725
- {/each}
726
- </div>
727
- {/snippet}
728
-
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, e: MouseEvent): void {
248
+ // If a drag is in progress but the primary button is no longer held, the
249
+ // pointer-up happened somewhere we did not observe (e.g. outside the
250
+ // calendar). Reset so we do not "drag" without the button being pressed.
251
+ if ((isDragging || appointmentDragStarted) && (e.buttons & 1) === 0) {
252
+ isDragging = false;
253
+ dragDoorId = null;
254
+ dragStartSlotIndex = null;
255
+ dragEndSlotIndex = null;
256
+ resetAppointmentDrag();
257
+ return;
258
+ }
259
+ // Appointment move drag
260
+ if (appointmentDragStarted) {
261
+ isDraggingAppointment = true;
262
+ moveTargetDoorId = doorId;
263
+ moveTargetSlotIndex = slotIndex;
264
+ return;
265
+ }
266
+ // Slot drag-create
267
+ if (!isDragging || doorId !== dragDoorId) {
268
+ return;
269
+ }
270
+ dragEndSlotIndex = slotIndex;
271
+ }
272
+
273
+ function onSlotMouseUp(): void {
274
+ // ---- Handle appointment drag-move ----
275
+ if (
276
+ isDraggingAppointment &&
277
+ draggedAppointment &&
278
+ moveTargetDoorId != null &&
279
+ moveTargetSlotIndex != null
280
+ ) {
281
+ const slot = timeSlots[moveTargetSlotIndex];
282
+ // eslint-disable-next-line svelte/prefer-svelte-reactivity
283
+ const newDateFrom = new Date(selected);
284
+ newDateFrom.setHours(slot.hour, slot.minute, 0, 0);
285
+ const newDateTo = new Date(
286
+ newDateFrom.getTime() + draggedAptSlotCount * slotIntervalMinutes * 60000
287
+ );
288
+
289
+ // Check whether the position actually changed
290
+ const origFrom = new Date(draggedAppointment.dateFrom);
291
+ const samePosition =
292
+ moveTargetDoorId === draggedAppointment.segmentId &&
293
+ newDateFrom.getTime() === origFrom.getTime();
294
+
295
+ if (samePosition) {
296
+ // Dropped in the same spot - treat as a click
297
+ onappointmentclick?.(draggedAppointment);
298
+ } else if (!hasOverlap(moveTargetDoorId, newDateFrom, newDateTo, draggedAppointment.id)) {
299
+ const door = doors.find((d) => d.id === moveTargetDoorId);
300
+ onappointmentmove?.({
301
+ appointment: draggedAppointment,
302
+ newDoorId: moveTargetDoorId,
303
+ newDoorName: door?.name ?? '',
304
+ newDateFrom,
305
+ newDateTo,
306
+ });
307
+ }
308
+
309
+ resetAppointmentDrag();
310
+ return;
311
+ }
312
+
313
+ // ---- Handle appointment click (mousedown + mouseup without leaving the block) ----
314
+ if (appointmentDragStarted && !isDraggingAppointment && draggedAppointment) {
315
+ onappointmentclick?.(draggedAppointment);
316
+ resetAppointmentDrag();
317
+ return;
318
+ }
319
+
320
+ resetAppointmentDrag();
321
+
322
+ // ---- Handle drag-create ----
323
+ if (
324
+ !isDragging ||
325
+ dragDoorId == null ||
326
+ dragStartSlotIndex == null ||
327
+ dragEndSlotIndex == null
328
+ ) {
329
+ return;
330
+ }
331
+
332
+ const startIdx = Math.min(dragStartSlotIndex, dragEndSlotIndex);
333
+ const endIdx = Math.max(dragStartSlotIndex, dragEndSlotIndex);
334
+
335
+ const startSlot = timeSlots[startIdx];
336
+ const endSlot = timeSlots[endIdx];
337
+
338
+ // eslint-disable-next-line svelte/prefer-svelte-reactivity
339
+ const dateFrom = new Date(selected);
340
+ dateFrom.setHours(startSlot.hour, startSlot.minute, 0, 0);
341
+
342
+ // eslint-disable-next-line svelte/prefer-svelte-reactivity
343
+ const dateTo = new Date(selected);
344
+ // End slot is the start of the last selected slot; add one interval for the end time
345
+ dateTo.setHours(endSlot.hour, endSlot.minute + slotIntervalMinutes, 0, 0);
346
+
347
+ const door = doors.find((d) => d.id === dragDoorId);
348
+
349
+ const selection: DragSelection = {
350
+ doorId: dragDoorId,
351
+ doorName: door?.name ?? '',
352
+ dateFrom,
353
+ dateTo,
354
+ };
355
+
356
+ isDragging = false;
357
+ dragDoorId = null;
358
+ dragStartSlotIndex = null;
359
+ dragEndSlotIndex = null;
360
+
361
+ ondragcreate?.(selection);
362
+ }
363
+
364
+ function isSlotInDragRange(doorId: number, slotIndex: number): boolean {
365
+ if (!isDragging || doorId !== dragDoorId) {
366
+ return false;
367
+ }
368
+ if (dragStartSlotIndex == null || dragEndSlotIndex == null) {
369
+ return false;
370
+ }
371
+ const min = Math.min(dragStartSlotIndex, dragEndSlotIndex);
372
+ const max = Math.max(dragStartSlotIndex, dragEndSlotIndex);
373
+ return slotIndex >= min && slotIndex <= max;
374
+ }
375
+
376
+ // ---- Row hover tracking ----
377
+
378
+ let hoveredSlotIndex: number | null = $state(null);
379
+
380
+ // ---- Appointment drag-move logic ----
381
+
382
+ let appointmentDragStarted = $state(false);
383
+ let isDraggingAppointment = $state(false);
384
+ let draggedAppointment: CalendarAppointment | null = $state(null);
385
+ let draggedAptSlotCount = $state(0);
386
+ let moveTargetDoorId: number | null = $state(null);
387
+ let moveTargetSlotIndex: number | null = $state(null);
388
+
389
+ function onAppointmentMouseDown(apt: CalendarAppointment, e: MouseEvent): void {
390
+ // Only react to the primary (left) button so middle/right clicks don't
391
+ // start a move or register as an appointment click.
392
+ if (e.button !== 0) {
393
+ return;
394
+ }
395
+ if (!onappointmentmove) {
396
+ return;
397
+ }
398
+ e.preventDefault();
399
+ appointmentDragStarted = true;
400
+ draggedAppointment = apt;
401
+
402
+ const from = new Date(apt.dateFrom);
403
+ const to = new Date(apt.dateTo);
404
+ const durationMin = (to.getTime() - from.getTime()) / 60000;
405
+ draggedAptSlotCount = Math.max(1, Math.ceil(durationMin / slotIntervalMinutes));
406
+ }
407
+
408
+ function resetAppointmentDrag(): void {
409
+ appointmentDragStarted = false;
410
+ isDraggingAppointment = false;
411
+ draggedAppointment = null;
412
+ draggedAptSlotCount = 0;
413
+ moveTargetDoorId = null;
414
+ moveTargetSlotIndex = null;
415
+ }
416
+
417
+ function isSlotInMoveTarget(doorId: number, slotIndex: number): boolean {
418
+ if (!isDraggingAppointment || moveTargetDoorId !== doorId) {
419
+ return false;
420
+ }
421
+ if (moveTargetSlotIndex == null) {
422
+ return false;
423
+ }
424
+ return (
425
+ slotIndex >= moveTargetSlotIndex && slotIndex < moveTargetSlotIndex + draggedAptSlotCount
426
+ );
427
+ }
428
+
429
+ function hasOverlap(doorId: number, dateFrom: Date, dateTo: Date, excludeAptId: number): boolean {
430
+ return appointments.some((apt) => {
431
+ if (apt.id === excludeAptId) {
432
+ return false;
433
+ }
434
+ if (apt.segmentId !== doorId) {
435
+ return false;
436
+ }
437
+ const aptFrom = new Date(apt.dateFrom);
438
+ const aptTo = new Date(apt.dateTo);
439
+ return dateFrom < aptTo && dateTo > aptFrom;
440
+ });
441
+ }
442
+
443
+ // ---- Month view helpers ----
444
+
445
+ function getMonthDays(date: Date): Array<{ date: Date; isCurrentMonth: boolean }> {
446
+ const year = date.getFullYear();
447
+ const month = date.getMonth();
448
+
449
+ const firstDayOfMonth = new Date(year, month, 1);
450
+
451
+ // Start from Monday of the week containing the first day
452
+ // eslint-disable-next-line svelte/prefer-svelte-reactivity
453
+ const startDate = new Date(firstDayOfMonth);
454
+ const dayOfWeek = startDate.getDay();
455
+ const daysFromMonday = dayOfWeek === 0 ? 6 : dayOfWeek - 1;
456
+ startDate.setDate(startDate.getDate() - daysFromMonday);
457
+
458
+ const days: Array<{ date: Date; isCurrentMonth: boolean }> = [];
459
+ // eslint-disable-next-line svelte/prefer-svelte-reactivity
460
+ const current = new Date(startDate);
461
+
462
+ // Generate 6 weeks (42 days) to fill the grid
463
+ for (let i = 0; i < 42; i++) {
464
+ days.push({
465
+ date: new Date(current),
466
+ isCurrentMonth: current.getMonth() === month,
467
+ });
468
+ current.setDate(current.getDate() + 1);
469
+ }
470
+
471
+ return days;
472
+ }
473
+
474
+ /** Cached month grid; rebuilt only when `selected` changes. */
475
+ const monthDays = $derived(getMonthDays(selected));
476
+
477
+ // ---- Week view helpers ----
478
+
479
+ function getWeekDays(date: Date): Array<Date> {
480
+ // eslint-disable-next-line svelte/prefer-svelte-reactivity
481
+ const d = new Date(date);
482
+ const day = d.getDay();
483
+ const mondayOffset = day === 0 ? -6 : 1 - day;
484
+ d.setDate(d.getDate() + mondayOffset);
485
+
486
+ const week: Array<Date> = [];
487
+ for (let i = 0; i < 7; i++) {
488
+ week.push(new Date(d));
489
+ d.setDate(d.getDate() + 1);
490
+ }
491
+ return week;
492
+ }
493
+
494
+ const weekDays = $derived(getWeekDays(selected));
495
+
496
+ // ---- View mode buttons ----
497
+
498
+ const viewModes: ReadonlyArray<{ mode: CalendarViewMode; label: string }> = [
499
+ { mode: CalendarViewMode.Day, label: 'Day' },
500
+ { mode: CalendarViewMode.Week, label: 'Week' },
501
+ { mode: CalendarViewMode.Month, label: 'Month' },
502
+ ];
503
+ </script>
504
+
505
+ <!-- A drag can end anywhere on the page (the pointer is often released outside
506
+ the calendar when sweeping across columns). Listen on the window so the
507
+ drag state is always finalised and never left "stuck" for the next drag. -->
508
+ <svelte:window onmouseup={onSlotMouseUp} />
509
+
510
+ <!-- svelte-ignore a11y_no_static_element_interactions -->
511
+ <!-- svelte-ignore a11y_no_noninteractive_element_interactions -->
512
+ <div
513
+ class="appointment-calendar"
514
+ class:is-moving-appointment={isDraggingAppointment}
515
+ role="application"
516
+ >
517
+ <!-- Header: navigation + view toggle -->
518
+ <div class="calendar-header">
519
+ <div class="header-left">
520
+ <Button
521
+ label="Today"
522
+ size={Size.Small}
523
+ onclick={goToToday}
524
+ >
525
+ Today
526
+ </Button>
527
+ <div class="nav-arrows">
528
+ <button
529
+ class="nav-btn"
530
+ onclick={() => {
531
+ navigateDate(-1);
532
+ }}
533
+ aria-label="Previous"
534
+ >
535
+ <Icon
536
+ name="chevron-left"
537
+ size={Size.Small}
538
+ colour={Colour['$ui-blue-14']}
539
+ />
540
+ </button>
541
+ <button
542
+ class="nav-btn"
543
+ onclick={() => {
544
+ navigateDate(1);
545
+ }}
546
+ aria-label="Next"
547
+ >
548
+ <Icon
549
+ name="chevron-right"
550
+ size={Size.Small}
551
+ colour={Colour['$ui-blue-14']}
552
+ />
553
+ </button>
554
+ </div>
555
+ <h2 class="current-date-label">{formatDate(selected)}</h2>
556
+ </div>
557
+ <div class="header-right">
558
+ {#if headerExtra}
559
+ {@render headerExtra()}
560
+ {/if}
561
+ <div class="view-toggle">
562
+ {#each viewModes as { mode, label } (mode)}
563
+ <button
564
+ class="view-btn"
565
+ class:active={viewMode === mode}
566
+ onclick={() => {
567
+ onviewmodechange(mode);
568
+ }}
569
+ >
570
+ {label}
571
+ </button>
572
+ {/each}
573
+ </div>
574
+ </div>
575
+ </div>
576
+
577
+ <!-- Week day tabs rendered OUTSIDE the scrollable body so they stay frozen -->
578
+ {#if viewMode === CalendarViewMode.Week}
579
+ <div class="week-day-tabs">
580
+ {#each weekDays as day (day.getTime())}
581
+ <button
582
+ class="week-day-tab"
583
+ class:active={sameDay(day, selected)}
584
+ class:today={sameDay(day, today)}
585
+ onclick={() => {
586
+ ondatechange(day);
587
+ }}
588
+ >
589
+ <span class="day-name">{dayNames[day.getDay()].slice(0, 3)}</span>
590
+ <span class="day-num">{day.getDate()}</span>
591
+ </button>
592
+ {/each}
593
+ </div>
594
+ {/if}
595
+
596
+ <!-- Calendar body -->
597
+ <div class="calendar-body">
598
+ {#if isLoading}
599
+ <LoadingOverlay />
600
+ {/if}
601
+
602
+ {#if viewMode === CalendarViewMode.Day}
603
+ <!-- DAY VIEW -->
604
+ <!-- svelte-ignore a11y_no_static_element_interactions -->
605
+ <div
606
+ class="day-view"
607
+ onmouseleave={() => {
608
+ hoveredSlotIndex = null;
609
+ }}
610
+ >
611
+ <!-- eslint-disable-next-line @typescript-eslint/no-confusing-void-expression -->
612
+ {@render doorGrid(selected)}
613
+ </div>
614
+ {:else if viewMode === CalendarViewMode.Week}
615
+ <!-- WEEK VIEW: day grid only, tabs are above calendar-body -->
616
+ <!-- svelte-ignore a11y_no_static_element_interactions -->
617
+ <div
618
+ class="day-view"
619
+ onmouseleave={() => {
620
+ hoveredSlotIndex = null;
621
+ }}
622
+ >
623
+ <!-- eslint-disable-next-line @typescript-eslint/no-confusing-void-expression -->
624
+ {@render doorGrid(selected)}
625
+ </div>
626
+ {:else}
627
+ <!-- MONTH VIEW -->
628
+ <div class="month-view">
629
+ <div class="month-header-row">
630
+ {#each ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] as dayLabel (dayLabel)}
631
+ <div class="month-day-header">{dayLabel}</div>
632
+ {/each}
633
+ </div>
634
+ <div class="month-grid">
635
+ {#each monthDays as { date: dayDate, isCurrentMonth } (dayDate.getTime())}
636
+ <button
637
+ class="month-day-cell"
638
+ class:other-month={!isCurrentMonth}
639
+ class:today={sameDay(dayDate, today)}
640
+ class:selected={sameDay(dayDate, selected)}
641
+ onclick={() => {
642
+ ondatechange(dayDate);
643
+ onviewmodechange(CalendarViewMode.Day);
644
+ }}
645
+ >
646
+ <span class="day-number">{dayDate.getDate()}</span>
647
+ <div class="day-badges">
648
+ {#each countsAt(dayDate) as { doorId, doorName, count } (doorId)}
649
+ <span class="door-badge">
650
+ {doorName}: {count}
651
+ </span>
652
+ {/each}
653
+ </div>
654
+ </button>
655
+ {/each}
656
+ </div>
657
+ </div>
658
+ {/if}
659
+ </div>
660
+ </div>
661
+
662
+ {#snippet doorGrid(day: Date)}
663
+ <div class="grid-header">
664
+ <div class="time-header">Time</div>
665
+ {#each doors as door (door.id)}
666
+ <div class="door-header">{door.name}</div>
667
+ {/each}
668
+ </div>
669
+ <div class="grid-body">
670
+ <div class="time-column">
671
+ {#each timeSlots as slot, slotIdx (slot.hour * 60 + slot.minute)}
672
+ <div
673
+ class="time-label"
674
+ class:hour-start={slot.minute === 0}
675
+ class:row-hover={hoveredSlotIndex === slotIdx}
676
+ >
677
+ {#if slot.minute === 0}
678
+ <span>{slot.label}</span>
679
+ {/if}
680
+ </div>
681
+ {/each}
682
+ </div>
683
+ {#each doors as door (door.id)}
684
+ <div class="door-column">
685
+ <!-- Slot cells for drag interaction (rendered first, sit below appointments) -->
686
+ {#each timeSlots as slot, slotIdx (slot.hour * 60 + slot.minute)}
687
+ <!-- svelte-ignore a11y_no_static_element_interactions -->
688
+ <div
689
+ class="slot-cell"
690
+ class:hour-start={slot.minute === 0}
691
+ class:drag-selected={isSlotInDragRange(door.id, slotIdx)}
692
+ class:move-target={isSlotInMoveTarget(door.id, slotIdx)}
693
+ class:row-hover={hoveredSlotIndex === slotIdx}
694
+ onmousedown={(e) => {
695
+ onSlotMouseDown(door.id, slotIdx, e);
696
+ }}
697
+ onmouseenter={(e) => {
698
+ hoveredSlotIndex = slotIdx;
699
+ onSlotMouseEnter(door.id, slotIdx, e);
700
+ }}
701
+ ></div>
702
+ {/each}
703
+ <!-- Appointment blocks positioned absolutely (rendered after, sit above slots) -->
704
+ {#each appointmentsAt(door.id, day) as apt (apt.id)}
705
+ <!-- svelte-ignore a11y_no_static_element_interactions -->
706
+ <div
707
+ class="appointment-block"
708
+ class:inbound={apt.typeCode === 'INBOUND'}
709
+ class:outbound={apt.typeCode === 'OUTBOUND'}
710
+ class:dragging={isDraggingAppointment && draggedAppointment?.id === apt.id}
711
+ class:movable={!!onappointmentmove}
712
+ style="top: {apt.topPercent}%; height: {apt.heightPercent}%;"
713
+ onmousedown={(e) => {
714
+ onAppointmentMouseDown(apt, e);
715
+ }}
716
+ >
717
+ <span class="apt-type">{apt.typeCode}</span>
718
+ <span class="apt-label">{apt.label}</span>
719
+ {#if apt.sublabel}
720
+ <span class="apt-sublabel">{apt.sublabel}</span>
721
+ {/if}
722
+ </div>
723
+ {/each}
724
+ </div>
725
+ {/each}
726
+ </div>
727
+ {/snippet}
728
+
729
729
  <style>.appointment-calendar {
730
730
  display: flex;
731
731
  flex-flow: column nowrap;
@@ -1150,4 +1150,4 @@
1150
1150
  white-space: nowrap;
1151
1151
  overflow: hidden;
1152
1152
  text-overflow: ellipsis;
1153
- }</style>
1153
+ }</style>