@svgrid/grid 2.1.21 → 2.1.23

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 (219) hide show
  1. package/README.md +9 -2
  2. package/dist/DockNodeView.svelte +306 -0
  3. package/dist/DockNodeView.svelte.d.ts +7 -0
  4. package/dist/DockPopoutHost.svelte +17 -0
  5. package/dist/DockPopoutHost.svelte.d.ts +14 -0
  6. package/dist/GridMenus.svelte +83 -3
  7. package/dist/SvAutoComplete.svelte +5 -3
  8. package/dist/SvCarousel.svelte +20 -42
  9. package/dist/SvColorInput.svelte +4 -3
  10. package/dist/SvColorInput.svelte.d.ts +1 -1
  11. package/dist/SvComboBox.svelte +7 -3
  12. package/dist/SvCommand.svelte +28 -85
  13. package/dist/SvCountryInput.svelte +1 -1
  14. package/dist/SvDateRangeInput.svelte +1 -1
  15. package/dist/SvDateTimePicker.svelte +9 -3
  16. package/dist/SvDateTimePicker.svelte.d.ts +3 -0
  17. package/dist/SvDockLayout.svelte +244 -0
  18. package/dist/SvDockLayout.svelte.d.ts +77 -0
  19. package/dist/SvDockManager.svelte +922 -0
  20. package/dist/SvDockManager.svelte.d.ts +106 -0
  21. package/dist/SvDrawer.svelte +69 -47
  22. package/dist/SvDrawer.svelte.d.ts +4 -0
  23. package/dist/SvDropDownList.svelte +85 -13
  24. package/dist/SvDropDownList.svelte.d.ts +3 -0
  25. package/dist/SvField.svelte +21 -4
  26. package/dist/SvField.svelte.d.ts +1 -0
  27. package/dist/SvForm.svelte +201 -91
  28. package/dist/SvForm.svelte.d.ts +15 -22
  29. package/dist/SvGrid.controller.svelte.d.ts +32 -1
  30. package/dist/SvGrid.controller.svelte.js +156 -27
  31. package/dist/SvGrid.css +193 -5
  32. package/dist/SvGrid.svelte +357 -12
  33. package/dist/SvGrid.types.d.ts +452 -1
  34. package/dist/SvGridDropdown.svelte +8 -1
  35. package/dist/SvGridSelect.svelte +1 -0
  36. package/dist/SvListBox.svelte +36 -14
  37. package/dist/SvMaskedInput.svelte +4 -3
  38. package/dist/SvMaskedInput.svelte.d.ts +1 -1
  39. package/dist/SvMenu.svelte +1 -1
  40. package/dist/SvMenuList.svelte +23 -71
  41. package/dist/SvMenuList.svelte.d.ts +2 -13
  42. package/dist/SvModal.svelte +12 -29
  43. package/dist/SvMultiSelect.svelte +1 -0
  44. package/dist/SvNumberInput.svelte +4 -3
  45. package/dist/SvNumberInput.svelte.d.ts +1 -1
  46. package/dist/SvPagination.svelte +18 -18
  47. package/dist/SvPasswordInput.svelte +3 -2
  48. package/dist/SvPasswordInput.svelte.d.ts +1 -1
  49. package/dist/SvPhoneInput.svelte +3 -2
  50. package/dist/SvPhoneInput.svelte.d.ts +1 -1
  51. package/dist/SvPopover.svelte +1 -1
  52. package/dist/SvStepper.svelte +6 -9
  53. package/dist/SvTagsInput.svelte +3 -2
  54. package/dist/SvTagsInput.svelte.d.ts +1 -1
  55. package/dist/SvTooltip.svelte +12 -23
  56. package/dist/SvTour.svelte +32 -4
  57. package/dist/SvTreeSelect.svelte +1 -0
  58. package/dist/build-api.js +76 -54
  59. package/dist/cdn/svgrid.js +10907 -6444
  60. package/dist/cdn/svgrid.svelte-external.js +9622 -5475
  61. package/dist/columns.js +6 -0
  62. package/dist/conditional-formatting.d.ts +67 -3
  63. package/dist/conditional-formatting.js +124 -17
  64. package/dist/createCarousel.svelte.d.ts +72 -0
  65. package/dist/createCarousel.svelte.js +80 -0
  66. package/dist/createCommand.svelte.d.ts +62 -0
  67. package/dist/createCommand.svelte.js +109 -0
  68. package/dist/createForm.svelte.d.ts +62 -0
  69. package/dist/createForm.svelte.js +374 -0
  70. package/dist/createMenu.svelte.d.ts +88 -0
  71. package/dist/createMenu.svelte.js +153 -0
  72. package/dist/createOverlay.svelte.d.ts +38 -0
  73. package/dist/createOverlay.svelte.js +68 -0
  74. package/dist/createPagination.d.ts +74 -0
  75. package/dist/createPagination.js +71 -0
  76. package/dist/createPopoverSelect.svelte.js +6 -12
  77. package/dist/createStepper.d.ts +44 -0
  78. package/dist/createStepper.js +26 -0
  79. package/dist/createTooltip.svelte.d.ts +32 -0
  80. package/dist/createTooltip.svelte.js +61 -0
  81. package/dist/datetime/timezone.d.ts +36 -0
  82. package/dist/datetime/timezone.js +110 -0
  83. package/dist/dock-context.d.ts +52 -0
  84. package/dist/dock-context.js +1 -0
  85. package/dist/dock-manager-model.d.ts +136 -0
  86. package/dist/dock-manager-model.js +514 -0
  87. package/dist/dock-model.d.ts +105 -0
  88. package/dist/dock-model.js +288 -0
  89. package/dist/dock-popout.d.ts +30 -0
  90. package/dist/dock-popout.js +81 -0
  91. package/dist/editor-contract.d.ts +2 -0
  92. package/dist/filter-operators.d.ts +6 -0
  93. package/dist/filter-operators.js +35 -2
  94. package/dist/filtering/excel-filters.d.ts +18 -1
  95. package/dist/filtering/excel-filters.js +56 -0
  96. package/dist/form-field.d.ts +73 -0
  97. package/dist/form-field.js +15 -0
  98. package/dist/index.d.ts +25 -5
  99. package/dist/index.js +40 -4
  100. package/dist/list-nav.d.ts +18 -0
  101. package/dist/list-nav.js +30 -0
  102. package/dist/list-option.d.ts +2 -0
  103. package/dist/menu-item.d.ts +20 -0
  104. package/dist/menu-item.js +1 -0
  105. package/dist/menus.d.ts +5 -0
  106. package/dist/menus.js +68 -16
  107. package/dist/panel-resize.d.ts +25 -0
  108. package/dist/panel-resize.js +40 -0
  109. package/dist/popover.d.ts +29 -3
  110. package/dist/popover.js +22 -6
  111. package/dist/recurrence.d.ts +33 -7
  112. package/dist/recurrence.js +151 -13
  113. package/dist/row-drag.d.ts +8 -0
  114. package/dist/row-drag.js +11 -0
  115. package/dist/scheduler-ical.d.ts +30 -0
  116. package/dist/scheduler-ical.js +180 -0
  117. package/dist/scheduler-model.d.ts +269 -0
  118. package/dist/scheduler-model.js +602 -0
  119. package/dist/scheduler-view.svelte.d.ts +22 -0
  120. package/dist/scheduler-view.svelte.js +13 -0
  121. package/dist/spreadsheet.js +20 -12
  122. package/dist/ui-app.types.d.ts +3 -0
  123. package/package.json +5 -1
  124. package/src/DockNodeView.svelte +306 -0
  125. package/src/DockPopoutHost.svelte +17 -0
  126. package/src/GridMenus.svelte +83 -3
  127. package/src/SvAutoComplete.svelte +5 -3
  128. package/src/SvCarousel.svelte +20 -42
  129. package/src/SvCarousel.test.ts +68 -0
  130. package/src/SvColorInput.svelte +4 -3
  131. package/src/SvComboBox.svelte +7 -3
  132. package/src/SvCommand.svelte +28 -85
  133. package/src/SvCommand.test.ts +78 -0
  134. package/src/SvCountryInput.svelte +1 -1
  135. package/src/SvDateRangeInput.svelte +1 -1
  136. package/src/SvDateTimePicker.svelte +9 -3
  137. package/src/SvDockLayout.svelte +244 -0
  138. package/src/SvDockManager.svelte +922 -0
  139. package/src/SvDrawer.svelte +69 -47
  140. package/src/SvDropDownList.svelte +85 -13
  141. package/src/SvField.svelte +21 -4
  142. package/src/SvForm.svelte +201 -91
  143. package/src/SvForm.test.ts +299 -0
  144. package/src/SvGrid.controller.svelte.ts +152 -28
  145. package/src/SvGrid.css +193 -5
  146. package/src/SvGrid.svelte +357 -12
  147. package/src/SvGrid.types.ts +463 -1
  148. package/src/SvGridDropdown.svelte +8 -1
  149. package/src/SvGridSelect.svelte +1 -0
  150. package/src/SvListBox.svelte +36 -14
  151. package/src/SvMaskedInput.svelte +4 -3
  152. package/src/SvMenu.svelte +1 -1
  153. package/src/SvMenu.test.ts +24 -0
  154. package/src/SvMenuList.svelte +23 -71
  155. package/src/SvModal.svelte +12 -29
  156. package/src/SvModal.test.ts +82 -0
  157. package/src/SvMultiSelect.svelte +1 -0
  158. package/src/SvNumberInput.svelte +4 -3
  159. package/src/SvPagination.svelte +18 -18
  160. package/src/SvPasswordInput.svelte +3 -2
  161. package/src/SvPhoneInput.svelte +3 -2
  162. package/src/SvPopover.svelte +1 -1
  163. package/src/SvStepper.svelte +6 -9
  164. package/src/SvTagsInput.svelte +3 -2
  165. package/src/SvTooltip.svelte +12 -23
  166. package/src/SvTooltip.test.ts +73 -0
  167. package/src/SvTour.svelte +32 -4
  168. package/src/SvTreeSelect.svelte +1 -0
  169. package/src/build-api.ts +74 -51
  170. package/src/columns.ts +5 -0
  171. package/src/conditional-formatting.test.ts +104 -0
  172. package/src/conditional-formatting.ts +176 -19
  173. package/src/createCarousel.svelte.ts +104 -0
  174. package/src/createCommand.svelte.ts +125 -0
  175. package/src/createForm.svelte.ts +333 -0
  176. package/src/createMenu.svelte.ts +202 -0
  177. package/src/createOverlay.svelte.ts +101 -0
  178. package/src/createPagination.test.ts +65 -0
  179. package/src/createPagination.ts +84 -0
  180. package/src/createPopoverSelect.svelte.ts +5 -9
  181. package/src/createStepper.test.ts +62 -0
  182. package/src/createStepper.ts +61 -0
  183. package/src/createTooltip.svelte.ts +86 -0
  184. package/src/datetime/timezone.test.ts +69 -0
  185. package/src/datetime/timezone.ts +134 -0
  186. package/src/dock-context.ts +47 -0
  187. package/src/dock-manager-model.test.ts +275 -0
  188. package/src/dock-manager-model.ts +593 -0
  189. package/src/dock-model.test.ts +163 -0
  190. package/src/dock-model.ts +368 -0
  191. package/src/dock-popout.ts +94 -0
  192. package/src/editor-contract.ts +2 -0
  193. package/src/filter-operators.test.ts +59 -0
  194. package/src/filter-operators.ts +35 -2
  195. package/src/filtering/excel-filters.test.ts +86 -1
  196. package/src/filtering/excel-filters.ts +65 -0
  197. package/src/form-field.ts +87 -0
  198. package/src/index.ts +158 -4
  199. package/src/list-nav.test.ts +49 -0
  200. package/src/list-nav.ts +29 -0
  201. package/src/list-option.ts +2 -0
  202. package/src/menu-item.ts +21 -0
  203. package/src/menus.test.ts +48 -0
  204. package/src/menus.ts +73 -16
  205. package/src/panel-resize.ts +52 -0
  206. package/src/popover.bounds.test.ts +93 -0
  207. package/src/popover.ts +51 -7
  208. package/src/recurrence.test.ts +88 -1
  209. package/src/recurrence.ts +166 -15
  210. package/src/row-drag.ts +10 -0
  211. package/src/scheduler-ical.test.ts +68 -0
  212. package/src/scheduler-ical.ts +180 -0
  213. package/src/scheduler-model.test.ts +546 -0
  214. package/src/scheduler-model.ts +853 -0
  215. package/src/scheduler-view.svelte.ts +33 -0
  216. package/src/spreadsheet.ts +20 -12
  217. package/src/svgrid.effect-driven-filter.svelte.test.ts +116 -0
  218. package/src/ui-app.types.ts +3 -0
  219. package/src/virtual.test.ts +6 -4
@@ -0,0 +1,853 @@
1
+ /**
2
+ * scheduler-model - the pure, framework-free core behind SvGridScheduler (the
3
+ * calendar / scheduler *view of the grid*). No Svelte, no DOM: just date math
4
+ * over the native `Date`, so every rule here is unit-tested directly.
5
+ *
6
+ * It does three things the view leans on:
7
+ * 1. resolve rows into concrete event instances for a visible window, expanding
8
+ * recurring rows via the shared `recurrence` engine (see recurrence.ts);
9
+ * 2. pack overlapping timed events into side-by-side columns for the time-grid
10
+ * (week / day) views;
11
+ * 3. compute the visible date range + navigation for each view.
12
+ *
13
+ * Deliberately avoids the arg-less `new Date()` / `Date.now()` (they are
14
+ * non-deterministic and unavailable in some execution contexts) - the caller
15
+ * supplies "today"/the anchor date and passes it in.
16
+ */
17
+ import {
18
+ addDays,
19
+ addMonths,
20
+ startOfDay,
21
+ startOfMonth,
22
+ startOfWeek,
23
+ withTime,
24
+ toDate,
25
+ isSameDay,
26
+ type DateLike,
27
+ } from './datetime/date-core'
28
+ import { expandRecurrence, type RecurrenceRule } from './recurrence'
29
+ import type { SchedulerView, SchedulerResource, SchedulerCollisionMode } from './SvGrid.types'
30
+
31
+ export type { SchedulerView, SchedulerResource, SchedulerCollisionMode }
32
+
33
+ /** A concrete event instance placed on the calendar (one row may yield many when
34
+ * it recurs). `key` is unique per instance; `rowKey` ties it back to its row. */
35
+ export type ResolvedEvent<TData = unknown> = {
36
+ key: string
37
+ rowKey: string
38
+ row: TData
39
+ title: string
40
+ start: Date
41
+ end: Date
42
+ allDay: boolean
43
+ color?: string
44
+ /** Optional secondary accent (e.g. a category) shown as a left strip, distinct
45
+ * from the main `color`. */
46
+ color2?: string
47
+ /** Free/busy status (busy | free | tentative | oof) for a distinct visual. */
48
+ status?: string
49
+ resourceId?: string
50
+ /** True when this instance came from expanding a recurrence rule. */
51
+ recurring: boolean
52
+ /** For a recurring instance, its canonical (pre-override) occurrence start -
53
+ * the identity used to key {@link RecurrenceException} overrides. */
54
+ occurrenceStart?: Date
55
+ /** True when a recurring instance carries a per-occurrence override. */
56
+ isException?: boolean
57
+ }
58
+
59
+ /** A per-occurrence override of a recurring event (the model's shape; the
60
+ * component maps the consumer's `SchedulerException` onto this). */
61
+ export type RecurrenceException = {
62
+ occurrenceStart: DateLike
63
+ deleted?: boolean
64
+ start?: DateLike | null
65
+ end?: DateLike | null
66
+ title?: string
67
+ allDay?: boolean
68
+ }
69
+
70
+ /** Field accessors the model uses to read an event off a row. The component
71
+ * builds this from `SchedulerConfig`, applying its move/edit overlay first so
72
+ * a dragged event resolves at its new time without mutating the source row. */
73
+ export type EventSpec<TData> = {
74
+ getKey: (row: TData) => string
75
+ getStart: (row: TData) => DateLike | null | undefined
76
+ getEnd?: (row: TData) => DateLike | null | undefined
77
+ getAllDay?: (row: TData) => boolean
78
+ getTitle?: (row: TData) => string
79
+ getColor?: (row: TData) => string | undefined
80
+ /** Optional secondary accent color (rendered as a left strip). */
81
+ getSecondaryColor?: (row: TData) => string | undefined
82
+ /** Optional free/busy status. */
83
+ getStatus?: (row: TData) => string | undefined
84
+ getResource?: (row: TData) => string | undefined
85
+ getRecurrence?: (
86
+ row: TData,
87
+ ) => RecurrenceRule | ReadonlyArray<RecurrenceRule> | null | undefined
88
+ /** Per-occurrence overrides for a recurring row (deleted / moved / edited). */
89
+ getExceptions?: (row: TData) => ReadonlyArray<RecurrenceException> | null | undefined
90
+ /** Fallback event length (minutes) when a row has a start but no end. Default 60. */
91
+ defaultDurationMin?: number
92
+ }
93
+
94
+ const MS_MIN = 60_000
95
+
96
+ /** True when [aStart,aEnd] and [bStart,bEnd] overlap (touching counts as overlap
97
+ * only for zero-length events). */
98
+ function rangesOverlap(aStart: Date, aEnd: Date, bStart: Date, bEnd: Date): boolean {
99
+ return aStart.getTime() < bEnd.getTime() && aEnd.getTime() > bStart.getTime()
100
+ }
101
+
102
+ /** One working window: `[start, end)` hours, optionally limited to `days`
103
+ * (weekday 0 = Sun … 6 = Sat). Omitting `days` applies it to every day. */
104
+ export type WorkingWindow = {
105
+ days?: ReadonlyArray<number>
106
+ start: number
107
+ end: number
108
+ }
109
+
110
+ /**
111
+ * The working `[startMin, endMin]` intervals for `weekday`, from `windows`,
112
+ * clamped to `[bandStartMin, bandEndMin]` and merged. Empty = the whole day is
113
+ * off. Pure; used for per-resource availability shading + enforcement.
114
+ */
115
+ export function workingIntervals(
116
+ weekday: number,
117
+ windows: ReadonlyArray<WorkingWindow>,
118
+ bandStartMin: number,
119
+ bandEndMin: number,
120
+ ): Array<[number, number]> {
121
+ const raw: Array<[number, number]> = []
122
+ for (const w of windows) {
123
+ if (w.days && !w.days.includes(weekday)) continue
124
+ const s = Math.max(bandStartMin, w.start * 60)
125
+ const e = Math.min(bandEndMin, w.end * 60)
126
+ if (e > s) raw.push([s, e])
127
+ }
128
+ raw.sort((a, b) => a[0] - b[0])
129
+ const merged: Array<[number, number]> = []
130
+ for (const iv of raw) {
131
+ const last = merged[merged.length - 1]
132
+ if (last && iv[0] <= last[1]) last[1] = Math.max(last[1], iv[1])
133
+ else merged.push([iv[0], iv[1]])
134
+ }
135
+ return merged
136
+ }
137
+
138
+ /** True when `[startMin, endMin]` lies wholly inside one working interval. */
139
+ export function withinWorking(
140
+ startMin: number,
141
+ endMin: number,
142
+ intervals: ReadonlyArray<readonly [number, number]>,
143
+ ): boolean {
144
+ return intervals.some(([a, b]) => startMin >= a && endMin <= b)
145
+ }
146
+
147
+ /**
148
+ * True when placing `[start,end]` on `resourceId` would overlap another event on
149
+ * the SAME resource (ignoring the event identified by `excludeRowKey`). Used to
150
+ * enforce `disableConflicts` (no double-booking). All-day/timed both count.
151
+ */
152
+ export function hasConflict<TData>(
153
+ start: Date,
154
+ end: Date,
155
+ resourceId: string | undefined,
156
+ events: ReadonlyArray<ResolvedEvent<TData>>,
157
+ excludeRowKey?: string,
158
+ ): boolean {
159
+ for (const e of events) {
160
+ if (e.rowKey === excludeRowKey) continue
161
+ if ((e.resourceId ?? undefined) !== (resourceId ?? undefined)) continue
162
+ if (rangesOverlap(start, end, e.start, e.end)) return true
163
+ }
164
+ return false
165
+ }
166
+
167
+ /**
168
+ * How many events on the SAME resource overlap `[start,end]` (excluding
169
+ * `excludeRowKey`). Used to enforce `maxEventsPerSlot` (resource capacity): a
170
+ * move/create is blocked when this count would reach the cap.
171
+ */
172
+ export function overlapCount<TData>(
173
+ start: Date,
174
+ end: Date,
175
+ resourceId: string | undefined,
176
+ events: ReadonlyArray<ResolvedEvent<TData>>,
177
+ excludeRowKey?: string,
178
+ ): number {
179
+ let n = 0
180
+ for (const e of events) {
181
+ if (e.rowKey === excludeRowKey) continue
182
+ if ((e.resourceId ?? undefined) !== (resourceId ?? undefined)) continue
183
+ if (rangesOverlap(start, end, e.start, e.end)) n++
184
+ }
185
+ return n
186
+ }
187
+
188
+ /** True when the minute range `[sMin,eMin)` overlaps any of the given hour bands. */
189
+ export function overlapsBands(
190
+ sMin: number,
191
+ eMin: number,
192
+ bands: ReadonlyArray<{ start: number; end: number }>,
193
+ ): boolean {
194
+ for (const b of bands) {
195
+ if (sMin < b.end * 60 && eMin > b.start * 60) return true
196
+ }
197
+ return false
198
+ }
199
+
200
+ /**
201
+ * Resolve `rows` into the event instances visible in `[rangeStart, rangeEnd]`.
202
+ * Recurring rows are expanded to one instance per matching day (keeping the base
203
+ * event's time-of-day and duration); single rows are included when they overlap
204
+ * the window. Result is sorted by start (all-day first within a start).
205
+ */
206
+ export function resolveEvents<TData>(
207
+ rows: ReadonlyArray<TData>,
208
+ spec: EventSpec<TData>,
209
+ rangeStart: Date,
210
+ rangeEnd: Date,
211
+ ): ResolvedEvent<TData>[] {
212
+ const defDur = Math.max(1, spec.defaultDurationMin ?? 60)
213
+ const out: ResolvedEvent<TData>[] = []
214
+
215
+ for (const row of rows) {
216
+ const start = toDate(spec.getStart(row))
217
+ if (!start) continue
218
+ const rawEnd = spec.getEnd ? toDate(spec.getEnd(row)) : null
219
+ const end =
220
+ rawEnd && rawEnd.getTime() > start.getTime()
221
+ ? rawEnd
222
+ : new Date(start.getTime() + defDur * MS_MIN)
223
+ const durationMs = end.getTime() - start.getTime()
224
+
225
+ const rowKey = spec.getKey(row)
226
+ const title = spec.getTitle?.(row) ?? ''
227
+ const allDay = spec.getAllDay?.(row) ?? false
228
+ const color = spec.getColor?.(row)
229
+ const color2 = spec.getSecondaryColor?.(row)
230
+ const status = spec.getStatus?.(row)
231
+ const resourceId = spec.getResource?.(row)
232
+ const rule = spec.getRecurrence?.(row)
233
+
234
+ if (rule) {
235
+ // One instance per matching day, carrying the base time-of-day + duration.
236
+ // Recurrence begins at the event's OWN start - never emit an occurrence
237
+ // before it, so clip the expansion's lower bound to the start date (a rule
238
+ // like "weekly on Mon-Fri" must not back-fill days before the event began).
239
+ const from = start.getTime() > rangeStart.getTime() ? start : rangeStart
240
+ const days = expandRecurrence(rule, from, rangeEnd)
241
+ // Per-occurrence overrides keyed by the occurrence's canonical start time.
242
+ const exs = spec.getExceptions?.(row)
243
+ const exMap = exs?.length
244
+ ? new Map(exs.map((e) => [toDate(e.occurrenceStart)?.getTime() ?? NaN, e]))
245
+ : null
246
+ for (const day of days) {
247
+ const occStart = allDay ? startOfDay(day) : withTime(day, start)
248
+ const ex = exMap?.get(occStart.getTime())
249
+ if (ex?.deleted) continue // this occurrence was removed
250
+ let iStart = occStart
251
+ let iEnd = new Date(occStart.getTime() + durationMs)
252
+ let iTitle = title
253
+ let iAllDay = allDay
254
+ if (ex) {
255
+ const exS = toDate(ex.start)
256
+ const exE = toDate(ex.end)
257
+ if (exS) {
258
+ iStart = exS
259
+ iEnd = exE && exE.getTime() > exS.getTime() ? exE : new Date(exS.getTime() + durationMs)
260
+ } else if (exE) {
261
+ iEnd = exE
262
+ }
263
+ if (ex.title != null) iTitle = ex.title
264
+ if (ex.allDay != null) iAllDay = ex.allDay
265
+ }
266
+ if (!rangesOverlap(iStart, iEnd, rangeStart, rangeEnd)) continue
267
+ out.push({
268
+ // Key on the CANONICAL occurrence start so a moved occurrence keeps its identity.
269
+ key: `${rowKey}#${occStart.getFullYear()}-${occStart.getMonth() + 1}-${occStart.getDate()}T${occStart.getHours()}:${occStart.getMinutes()}`,
270
+ rowKey,
271
+ row,
272
+ title: iTitle,
273
+ start: iStart,
274
+ end: iEnd,
275
+ allDay: iAllDay,
276
+ color,
277
+ color2,
278
+ status,
279
+ resourceId,
280
+ recurring: true,
281
+ occurrenceStart: occStart,
282
+ isException: !!ex,
283
+ })
284
+ }
285
+ } else if (rangesOverlap(start, end, rangeStart, rangeEnd)) {
286
+ out.push({
287
+ key: rowKey,
288
+ rowKey,
289
+ row,
290
+ title,
291
+ start,
292
+ end,
293
+ allDay,
294
+ color,
295
+ color2,
296
+ status,
297
+ resourceId,
298
+ recurring: false,
299
+ })
300
+ }
301
+ }
302
+
303
+ out.sort((a, b) => {
304
+ const d = a.start.getTime() - b.start.getTime()
305
+ if (d !== 0) return d
306
+ if (a.allDay !== b.allDay) return a.allDay ? -1 : 1
307
+ return a.end.getTime() - b.end.getTime()
308
+ })
309
+ return out
310
+ }
311
+
312
+ /** Events that touch `day` (any calendar day the event spans), timed + all-day. */
313
+ export function eventsOnDay<TData>(
314
+ events: ReadonlyArray<ResolvedEvent<TData>>,
315
+ day: Date,
316
+ ): ResolvedEvent<TData>[] {
317
+ const dayStart = startOfDay(day)
318
+ const dayEnd = addDays(dayStart, 1)
319
+ return events.filter((e) => rangesOverlap(e.start, e.end, dayStart, dayEnd))
320
+ }
321
+
322
+ /**
323
+ * A continuous month-view bar for one event within one week row: the columns it
324
+ * spans (`startCol`..`endCol`, 0-6) and the `lane` (stack row) it sits in. Events
325
+ * that cross a week boundary are split into one segment per week (with
326
+ * `continuesLeft`/`continuesRight` flags so the view can flatten that edge).
327
+ */
328
+ export type MonthSegment<TData = unknown> = {
329
+ event: ResolvedEvent<TData>
330
+ startCol: number
331
+ endCol: number
332
+ lane: number
333
+ continuesLeft: boolean
334
+ continuesRight: boolean
335
+ }
336
+
337
+ const MS_DAY = 86_400_000
338
+
339
+ /**
340
+ * Lay out one week row of the month grid as continuous spanning bars. `weekStart`
341
+ * is the local-midnight first day of the 7-day row. Returns each overlapping
342
+ * event as a {@link MonthSegment} clipped to the week, with greedy lane packing
343
+ * so bars never overlap, plus the total `laneCount`.
344
+ */
345
+ export function monthWeekSegments<TData>(
346
+ events: ReadonlyArray<ResolvedEvent<TData>>,
347
+ weekStart: Date,
348
+ ): { segments: MonthSegment<TData>[]; laneCount: number } {
349
+ const ws = startOfDay(weekStart)
350
+ const we = addDays(ws, 7)
351
+ const colOf = (d: Date) => Math.floor((startOfDay(d).getTime() - ws.getTime()) / MS_DAY)
352
+
353
+ const out: MonthSegment<TData>[] = []
354
+ for (const e of events) {
355
+ const firstDay = startOfDay(e.start)
356
+ // Last covered day: the day of (end - 1ms), so an end at exact midnight does
357
+ // not spill onto the next day. Guard against zero/negative-length events.
358
+ const lastDay = startOfDay(new Date(Math.max(e.start.getTime(), e.end.getTime() - 1)))
359
+ if (lastDay.getTime() < ws.getTime() || firstDay.getTime() >= we.getTime()) continue
360
+ const startCol = Math.max(0, colOf(firstDay))
361
+ const endCol = Math.min(6, colOf(lastDay))
362
+ if (endCol < startCol) continue
363
+ out.push({
364
+ event: e,
365
+ startCol,
366
+ endCol,
367
+ lane: 0,
368
+ continuesLeft: firstDay.getTime() < ws.getTime(),
369
+ continuesRight: lastDay.getTime() >= we.getTime(),
370
+ })
371
+ }
372
+
373
+ // Order: earliest start, then longest, then all-day before timed, then start time.
374
+ out.sort(
375
+ (a, b) =>
376
+ a.startCol - b.startCol ||
377
+ b.endCol - b.startCol - (a.endCol - a.startCol) ||
378
+ (a.event.allDay === b.event.allDay
379
+ ? a.event.start.getTime() - b.event.start.getTime()
380
+ : a.event.allDay
381
+ ? -1
382
+ : 1),
383
+ )
384
+
385
+ // Greedy lane packing: a lane tracks the last column it is occupied through.
386
+ const laneEnd: number[] = []
387
+ for (const seg of out) {
388
+ let lane = 0
389
+ for (; lane < laneEnd.length; lane++) if (seg.startCol > (laneEnd[lane] ?? -1)) break
390
+ laneEnd[lane] = seg.endCol
391
+ seg.lane = lane
392
+ }
393
+ return { segments: out, laneCount: laneEnd.length }
394
+ }
395
+
396
+ /** A timed event positioned within a time-grid column. `topPct`/`heightPct` are
397
+ * 0-100 of the visible day; `leftPct`/`widthPct`/`zIndex` place it horizontally
398
+ * among overlapping peers (already resolved for the chosen collision mode). */
399
+ export type PositionedEvent<TData = unknown> = {
400
+ event: ResolvedEvent<TData>
401
+ topPct: number
402
+ heightPct: number
403
+ col: number
404
+ colCount: number
405
+ leftPct: number
406
+ widthPct: number
407
+ zIndex: number
408
+ }
409
+
410
+ /** A `+N more` tile emitted by `cap` mode for the events that didn't fit. */
411
+ export type OverflowMarker<TData = unknown> = {
412
+ topPct: number
413
+ heightPct: number
414
+ leftPct: number
415
+ widthPct: number
416
+ /** Number of hidden events this tile stands for. */
417
+ count: number
418
+ /** The hidden events (chronological), for the "+N more" popover. */
419
+ events: ResolvedEvent<TData>[]
420
+ }
421
+
422
+ /** The full time-grid layout for one day: positioned events + any overflow tiles. */
423
+ export type DayLayout<TData = unknown> = {
424
+ events: PositionedEvent<TData>[]
425
+ overflows: OverflowMarker<TData>[]
426
+ }
427
+
428
+ export type LayoutOptions = {
429
+ dayStartHour?: number
430
+ dayEndHour?: number
431
+ /** Collision layout mode. Default `split`. */
432
+ mode?: SchedulerCollisionMode
433
+ /** `cap` mode: max columns before overflow (min 2). Default 3. */
434
+ maxColumns?: number
435
+ /** `stack` mode: horizontal offset per overlapping event, in % of column. */
436
+ stackOffsetPct?: number
437
+ /** `stack` mode: the narrowest a stacked event may get, in % of column. */
438
+ stackMinWidthPct?: number
439
+ }
440
+
441
+ /**
442
+ * Lay out the timed events of a single day for the time-grid, resolving
443
+ * collisions per {@link SchedulerCollisionMode}. `dayStartHour`/`dayEndHour`
444
+ * bound the visible band (e.g. 8..18); events are clamped to it. All-day events
445
+ * are ignored here (the view renders them in a separate all-day row).
446
+ */
447
+ export function layoutDayEvents<TData>(
448
+ dayEvents: ReadonlyArray<ResolvedEvent<TData>>,
449
+ day: Date,
450
+ opts: LayoutOptions = {},
451
+ ): DayLayout<TData> {
452
+ const dayStartHour = opts.dayStartHour ?? 0
453
+ const dayEndHour = opts.dayEndHour ?? 24
454
+ const mode = opts.mode ?? 'split'
455
+ const maxColumns = Math.max(2, Math.floor(opts.maxColumns ?? 3))
456
+ const stackOffset = opts.stackOffsetPct ?? 14
457
+ const stackMinWidth = opts.stackMinWidthPct ?? 42
458
+
459
+ const base = startOfDay(day)
460
+ const bandStartMin = dayStartHour * 60
461
+ const bandEndMin = dayEndHour * 60
462
+ const bandLen = Math.max(1, bandEndMin - bandStartMin)
463
+
464
+ type Item = { event: ResolvedEvent<TData>; startMin: number; endMin: number; col: number }
465
+ const items: Item[] = []
466
+ for (const e of dayEvents) {
467
+ if (e.allDay) continue
468
+ const s = Math.max(bandStartMin, (e.start.getTime() - base.getTime()) / MS_MIN)
469
+ const en = Math.min(bandEndMin, (e.end.getTime() - base.getTime()) / MS_MIN)
470
+ if (en <= bandStartMin || s >= bandEndMin) continue
471
+ items.push({ event: e, startMin: s, endMin: Math.max(s + 1, en), col: 0 })
472
+ }
473
+ items.sort((a, b) => a.startMin - b.startMin || a.endMin - b.endMin)
474
+
475
+ const events: PositionedEvent<TData>[] = []
476
+ const overflows: OverflowMarker<TData>[] = []
477
+ const topOf = (min: number) => ((min - bandStartMin) / bandLen) * 100
478
+ const heightOf = (a: number, b: number) => ((b - a) / bandLen) * 100
479
+ const maxStackShift = Math.max(0, Math.floor((100 - stackMinWidth) / stackOffset))
480
+
481
+ // Walk clusters of transitively-overlapping events; within each cluster assign
482
+ // greedy columns, then resolve horizontal geometry for the chosen mode.
483
+ let cluster: Item[] = []
484
+ let clusterEnd = -Infinity
485
+ const flush = () => {
486
+ if (!cluster.length) return
487
+ const colEnds: number[] = []
488
+ for (const it of cluster) {
489
+ let c = 0
490
+ for (; c < colEnds.length; c++) if (it.startMin >= (colEnds[c] ?? Infinity)) break
491
+ colEnds[c] = it.endMin
492
+ it.col = c
493
+ }
494
+ const colCount = colEnds.length
495
+
496
+ if (mode === 'stack' && colCount > 1) {
497
+ for (const it of cluster) {
498
+ const shift = Math.min(it.col, maxStackShift) * stackOffset
499
+ events.push({
500
+ event: it.event,
501
+ topPct: topOf(it.startMin),
502
+ heightPct: heightOf(it.startMin, it.endMin),
503
+ col: it.col,
504
+ colCount,
505
+ leftPct: shift,
506
+ widthPct: 100 - shift,
507
+ zIndex: it.col + 1,
508
+ })
509
+ }
510
+ } else if (mode === 'cap' && colCount > maxColumns) {
511
+ const realCols = maxColumns - 1 // reserve the last visible slot for overflow
512
+ const hidden: Item[] = []
513
+ for (const it of cluster) {
514
+ if (it.col < realCols) {
515
+ events.push({
516
+ event: it.event,
517
+ topPct: topOf(it.startMin),
518
+ heightPct: heightOf(it.startMin, it.endMin),
519
+ col: it.col,
520
+ colCount: maxColumns,
521
+ leftPct: (it.col / maxColumns) * 100,
522
+ widthPct: 100 / maxColumns,
523
+ zIndex: 1,
524
+ })
525
+ } else {
526
+ hidden.push(it)
527
+ }
528
+ }
529
+ if (hidden.length) {
530
+ const start = Math.min(...hidden.map((h) => h.startMin))
531
+ const end = Math.max(...hidden.map((h) => h.endMin))
532
+ overflows.push({
533
+ topPct: topOf(start),
534
+ heightPct: heightOf(start, end),
535
+ leftPct: (realCols / maxColumns) * 100,
536
+ widthPct: 100 / maxColumns,
537
+ count: hidden.length,
538
+ events: hidden.map((h) => h.event),
539
+ })
540
+ }
541
+ } else {
542
+ // split (and cap when the cluster fits within maxColumns): each event
543
+ // starts in its greedy column, then EXPANDS rightward across any columns
544
+ // that hold no event overlapping it in time - so an event with free space
545
+ // beside it fills the gap instead of staying a narrow 1/colCount sliver.
546
+ for (const it of cluster) {
547
+ let span = 1
548
+ for (let c = it.col + 1; c < colCount; c++) {
549
+ const blocked = cluster.some(
550
+ (o) => o !== it && o.col === c && o.startMin < it.endMin && o.endMin > it.startMin,
551
+ )
552
+ if (blocked) break
553
+ span++
554
+ }
555
+ events.push({
556
+ event: it.event,
557
+ topPct: topOf(it.startMin),
558
+ heightPct: heightOf(it.startMin, it.endMin),
559
+ col: it.col,
560
+ colCount,
561
+ leftPct: (it.col / colCount) * 100,
562
+ widthPct: (span / colCount) * 100,
563
+ zIndex: 1,
564
+ })
565
+ }
566
+ }
567
+
568
+ cluster = []
569
+ clusterEnd = -Infinity
570
+ }
571
+ for (const it of items) {
572
+ if (cluster.length && it.startMin >= clusterEnd) flush()
573
+ cluster.push(it)
574
+ clusterEnd = Math.max(clusterEnd, it.endMin)
575
+ }
576
+ flush()
577
+ return { events, overflows }
578
+ }
579
+
580
+ /** One day's bucket of events for the agenda (list) view. */
581
+ export type AgendaGroup<TData = unknown> = {
582
+ day: Date
583
+ events: ResolvedEvent<TData>[]
584
+ }
585
+
586
+ /** Group resolved events by calendar day for the agenda view (days with no
587
+ * events are omitted; groups and their events are in chronological order). */
588
+ export function agendaGroups<TData>(
589
+ events: ReadonlyArray<ResolvedEvent<TData>>,
590
+ ): AgendaGroup<TData>[] {
591
+ const groups: AgendaGroup<TData>[] = []
592
+ for (const e of [...events].sort((a, b) => a.start.getTime() - b.start.getTime())) {
593
+ const last = groups[groups.length - 1]
594
+ if (last && isSameDay(last.day, e.start)) last.events.push(e)
595
+ else groups.push({ day: startOfDay(e.start), events: [e] })
596
+ }
597
+ return groups
598
+ }
599
+
600
+ /**
601
+ * The visible date window for a view anchored on `anchor`. Used both to size the
602
+ * grid and to bound event resolution (recurrence expansion clips to it).
603
+ * `agendaDays` controls the agenda span (default 30).
604
+ */
605
+ export function rangeForView(
606
+ view: SchedulerView,
607
+ anchor: Date,
608
+ weekStartsOn = 0,
609
+ agendaDays = 30,
610
+ ): { start: Date; end: Date } {
611
+ switch (view) {
612
+ case 'month': {
613
+ const start = startOfWeek(startOfMonth(anchor), weekStartsOn)
614
+ return { start, end: addDays(start, 42) } // fixed 6-week grid
615
+ }
616
+ case 'week': {
617
+ const start = startOfWeek(anchor, weekStartsOn)
618
+ return { start, end: addDays(start, 7) }
619
+ }
620
+ case 'day': {
621
+ const start = startOfDay(anchor)
622
+ return { start, end: addDays(start, 1) }
623
+ }
624
+ case 'agenda': {
625
+ const start = startOfDay(anchor)
626
+ return { start, end: addDays(start, Math.max(1, agendaDays)) }
627
+ }
628
+ case 'timelineDay':
629
+ return { start: startOfDay(anchor), end: addDays(startOfDay(anchor), 1) }
630
+ case 'timelineWeek': {
631
+ const start = startOfWeek(anchor, weekStartsOn)
632
+ return { start, end: addDays(start, 7) }
633
+ }
634
+ case 'timelineMonth': {
635
+ const start = startOfMonth(anchor)
636
+ return { start, end: startOfMonth(addMonths(anchor, 1)) }
637
+ }
638
+ case 'timelineYear': {
639
+ const start = new Date(anchor.getFullYear(), 0, 1)
640
+ return { start, end: new Date(anchor.getFullYear() + 1, 0, 1) }
641
+ }
642
+ }
643
+ }
644
+
645
+ /** The 7 (or fewer) day columns rendered for the week / day views. */
646
+ export function daysForView(view: SchedulerView, anchor: Date, weekStartsOn = 0): Date[] {
647
+ if (view === 'day') return [startOfDay(anchor)]
648
+ const start = startOfWeek(anchor, weekStartsOn)
649
+ return Array.from({ length: 7 }, (_, i) => addDays(start, i))
650
+ }
651
+
652
+ /** Move the anchor one view-unit in `dir` (-1 back, +1 forward). */
653
+ export function navigateAnchor(view: SchedulerView, anchor: Date, dir: number): Date {
654
+ switch (view) {
655
+ case 'month':
656
+ return addMonths(anchor, dir)
657
+ case 'week':
658
+ return addDays(anchor, 7 * dir)
659
+ case 'day':
660
+ return addDays(anchor, dir)
661
+ case 'agenda':
662
+ return addDays(anchor, 30 * dir)
663
+ case 'timelineDay':
664
+ return addDays(anchor, dir)
665
+ case 'timelineWeek':
666
+ return addDays(anchor, 7 * dir)
667
+ case 'timelineMonth':
668
+ return addMonths(anchor, dir)
669
+ case 'timelineYear':
670
+ return new Date(anchor.getFullYear() + dir, anchor.getMonth(), anchor.getDate())
671
+ }
672
+ }
673
+
674
+ // --- timeline views (horizontal: time left→right, resources as rows) ----------
675
+
676
+ const TL_WD = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
677
+ const TL_MO = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
678
+ const tlHourLabel = (h: number) =>
679
+ h === 0 ? '12 AM' : h < 12 ? `${h} AM` : h === 12 ? '12 PM' : `${h - 12} PM`
680
+
681
+ /** One column of the timeline's minor (tick) header row. */
682
+ export type TimelineTick = {
683
+ start: Date
684
+ end: Date
685
+ leftPct: number
686
+ widthPct: number
687
+ label: string
688
+ today: boolean
689
+ }
690
+ /** One cell of the timeline's major (grouping) header row, spanning several ticks. */
691
+ export type TimelineMajor = { label: string; leftPct: number; widthPct: number }
692
+ /** The horizontal axis: its window [start, end] (the day band for `timelineDay`),
693
+ * the minor `ticks`, and the coarser `majors` above them. */
694
+ export type TimelineAxis = {
695
+ start: Date
696
+ end: Date
697
+ totalMs: number
698
+ ticks: TimelineTick[]
699
+ majors: TimelineMajor[]
700
+ }
701
+
702
+ // Group consecutive ticks that share a key into a coarser major cell.
703
+ function groupMajors(
704
+ ticks: TimelineTick[],
705
+ keyOf: (t: TimelineTick) => string,
706
+ labelOf: (t: TimelineTick) => string,
707
+ ): TimelineMajor[] {
708
+ const out: (TimelineMajor & { _k?: string })[] = []
709
+ for (const t of ticks) {
710
+ const k = keyOf(t)
711
+ const last = out[out.length - 1]
712
+ if (last && last._k === k) last.widthPct += t.widthPct
713
+ else out.push({ _k: k, label: labelOf(t), leftPct: t.leftPct, widthPct: t.widthPct })
714
+ }
715
+ return out.map(({ _k, ...m }) => m)
716
+ }
717
+
718
+ /**
719
+ * Build the timeline header axis for `view` over `[rangeStart, rangeEnd]`. For
720
+ * `timelineDay` the axis is clamped to the `dayStartHour..dayEndHour` band (so
721
+ * events outside it clip, matching the vertical day view). Ticks are hours (day),
722
+ * days (week / month) or months (year); majors are the date, the month(s), or
723
+ * quarters. All geometry is percentage of the axis window.
724
+ */
725
+ export function timelineAxis(
726
+ view: SchedulerView,
727
+ rangeStart: Date,
728
+ rangeEnd: Date,
729
+ opts: { dayStartHour?: number; dayEndHour?: number; today?: Date | null } = {},
730
+ ): TimelineAxis {
731
+ const dayStartHour = opts.dayStartHour ?? 0
732
+ const dayEndHour = opts.dayEndHour ?? 24
733
+ const today = opts.today ? startOfDay(opts.today) : null
734
+ const isToday = (d: Date) => (today ? isSameDay(d, today) : false)
735
+
736
+ let start = rangeStart
737
+ let end = rangeEnd
738
+ if (view === 'timelineDay') {
739
+ start = new Date(rangeStart.getFullYear(), rangeStart.getMonth(), rangeStart.getDate(), dayStartHour)
740
+ end = new Date(rangeStart.getFullYear(), rangeStart.getMonth(), rangeStart.getDate(), 0, 0, 0, 0)
741
+ end = new Date(end.getTime() + dayEndHour * 3_600_000)
742
+ }
743
+ const total = Math.max(1, end.getTime() - start.getTime())
744
+ const base = start.getTime()
745
+ const mk = (s: Date, e: Date, label: string): TimelineTick => ({
746
+ start: s,
747
+ end: e,
748
+ leftPct: ((s.getTime() - base) / total) * 100,
749
+ widthPct: ((e.getTime() - s.getTime()) / total) * 100,
750
+ label,
751
+ today: isToday(s),
752
+ })
753
+
754
+ const ticks: TimelineTick[] = []
755
+ let majors: TimelineMajor[] = []
756
+
757
+ if (view === 'timelineDay') {
758
+ for (let h = dayStartHour; h < dayEndHour; h++) {
759
+ const s = new Date(rangeStart.getFullYear(), rangeStart.getMonth(), rangeStart.getDate(), h)
760
+ ticks.push(mk(s, new Date(s.getTime() + 3_600_000), tlHourLabel(h)))
761
+ }
762
+ majors = [
763
+ { label: `${TL_WD[rangeStart.getDay()]}, ${TL_MO[rangeStart.getMonth()]} ${rangeStart.getDate()}`, leftPct: 0, widthPct: 100 },
764
+ ]
765
+ } else if (view === 'timelineWeek' || view === 'timelineMonth') {
766
+ let cur = startOfDay(start)
767
+ while (cur.getTime() < end.getTime()) {
768
+ const nxt = addDays(cur, 1)
769
+ const label = view === 'timelineWeek' ? `${TL_WD[cur.getDay()]} ${cur.getDate()}` : `${cur.getDate()}`
770
+ ticks.push(mk(cur, nxt, label))
771
+ cur = nxt
772
+ }
773
+ majors = groupMajors(
774
+ ticks,
775
+ (t) => `${t.start.getFullYear()}-${t.start.getMonth()}`,
776
+ (t) => `${TL_MO[t.start.getMonth()]} ${t.start.getFullYear()}`,
777
+ )
778
+ } else if (view === 'timelineYear') {
779
+ const y = rangeStart.getFullYear()
780
+ for (let m = 0; m < 12; m++) {
781
+ ticks.push(mk(new Date(y, m, 1), new Date(y, m + 1, 1), TL_MO[m]))
782
+ }
783
+ majors = groupMajors(
784
+ ticks,
785
+ (t) => `${Math.floor(t.start.getMonth() / 3)}`,
786
+ (t) => `Q${Math.floor(t.start.getMonth() / 3) + 1} ${t.start.getFullYear()}`,
787
+ )
788
+ }
789
+
790
+ return { start, end, totalMs: total, ticks, majors }
791
+ }
792
+
793
+ /** An event's horizontal geometry within the axis window, or `null` when it
794
+ * falls entirely outside it. `continuesLeft/Right` flag a clipped edge. */
795
+ export function timelineGeom(
796
+ start: Date,
797
+ end: Date,
798
+ axisStart: Date,
799
+ axisMs: number,
800
+ ): { leftPct: number; widthPct: number; continuesLeft: boolean; continuesRight: boolean } | null {
801
+ const a = axisStart.getTime()
802
+ const b = a + axisMs
803
+ const s = Math.max(start.getTime(), a)
804
+ const e = Math.min(end.getTime(), b)
805
+ if (e <= a || s >= b || e <= s) return null
806
+ return {
807
+ leftPct: ((s - a) / axisMs) * 100,
808
+ widthPct: ((e - s) / axisMs) * 100,
809
+ continuesLeft: start.getTime() < a,
810
+ continuesRight: end.getTime() > b,
811
+ }
812
+ }
813
+
814
+ /** One resource's timeline row: its events lane-packed so overlaps stack. */
815
+ export type TimelineRow<TData = unknown> = {
816
+ resource: SchedulerResource | null
817
+ laneCount: number
818
+ items: { event: ResolvedEvent<TData>; lane: number }[]
819
+ }
820
+
821
+ /**
822
+ * Bucket `events` by resource into rows (a single `null` row when there are no
823
+ * resources), then greedily lane-pack each row so overlapping events stack. An
824
+ * event whose `resourceId` matches no resource is dropped.
825
+ */
826
+ export function timelineRows<TData>(
827
+ resources: ReadonlyArray<SchedulerResource> | null | undefined,
828
+ events: ReadonlyArray<ResolvedEvent<TData>>,
829
+ ): TimelineRow<TData>[] {
830
+ const hasRes = !!(resources && resources.length)
831
+ const rows = hasRes
832
+ ? resources!.map((r) => ({ resource: r as SchedulerResource | null, evs: [] as ResolvedEvent<TData>[] }))
833
+ : [{ resource: null as SchedulerResource | null, evs: [] as ResolvedEvent<TData>[] }]
834
+ const byId = new Map<string | null, (typeof rows)[number]>()
835
+ for (const r of rows) byId.set(r.resource?.id ?? null, r)
836
+
837
+ for (const ev of events) {
838
+ const row = hasRes ? byId.get(ev.resourceId ?? '') : rows[0]
839
+ if (row) row.evs.push(ev)
840
+ }
841
+
842
+ return rows.map((r) => {
843
+ const sorted = [...r.evs].sort((a, b) => a.start.getTime() - b.start.getTime() || a.end.getTime() - b.end.getTime())
844
+ const laneEnd: number[] = []
845
+ const items = sorted.map((event) => {
846
+ let lane = 0
847
+ for (; lane < laneEnd.length; lane++) if (event.start.getTime() >= (laneEnd[lane] ?? -Infinity)) break
848
+ laneEnd[lane] = event.end.getTime()
849
+ return { event, lane }
850
+ })
851
+ return { resource: r.resource, laneCount: Math.max(1, laneEnd.length), items }
852
+ })
853
+ }