@getcortexlabs/mavis-core 0.1.0-rc.12 → 0.1.0-rc.12.1

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 (82) hide show
  1. package/README.md +2 -2
  2. package/dist/advanced-collections.d.ts +74 -0
  3. package/dist/advanced-collections.d.ts.map +1 -0
  4. package/dist/advanced-collections.js +129 -0
  5. package/dist/advanced-collections.js.map +1 -0
  6. package/dist/capabilities.d.ts +7 -7
  7. package/dist/capabilities.d.ts.map +1 -1
  8. package/dist/capabilities.js +10 -4
  9. package/dist/capabilities.js.map +1 -1
  10. package/dist/image-crop.d.ts +49 -0
  11. package/dist/image-crop.d.ts.map +1 -0
  12. package/dist/image-crop.js +71 -0
  13. package/dist/image-crop.js.map +1 -0
  14. package/dist/index.d.ts +3 -0
  15. package/dist/index.d.ts.map +1 -1
  16. package/dist/index.js +3 -0
  17. package/dist/index.js.map +1 -1
  18. package/dist/scheduler.d.ts +45 -0
  19. package/dist/scheduler.d.ts.map +1 -0
  20. package/dist/scheduler.js +142 -0
  21. package/dist/scheduler.js.map +1 -0
  22. package/dist/vue/advanced-collections.d.ts +486 -0
  23. package/dist/vue/advanced-collections.d.ts.map +1 -0
  24. package/dist/vue/advanced-collections.js +476 -0
  25. package/dist/vue/advanced-collections.js.map +1 -0
  26. package/dist/vue/advanced-props.d.ts +398 -0
  27. package/dist/vue/advanced-props.d.ts.map +1 -0
  28. package/dist/vue/advanced-props.js +128 -0
  29. package/dist/vue/advanced-props.js.map +1 -0
  30. package/dist/vue/animated-text.d.ts +1 -1
  31. package/dist/vue/chart.d.ts +1 -1
  32. package/dist/vue/command-palette.d.ts +3 -3
  33. package/dist/vue/component-props.d.ts +359 -3
  34. package/dist/vue/component-props.d.ts.map +1 -1
  35. package/dist/vue/component-props.js +7 -0
  36. package/dist/vue/component-props.js.map +1 -1
  37. package/dist/vue/composer.d.ts +1 -1
  38. package/dist/vue/configurator.d.ts +4 -4
  39. package/dist/vue/creative-controls.d.ts +1 -1
  40. package/dist/vue/dashboard-charts.d.ts +1 -1
  41. package/dist/vue/dashboard-effects.d.ts +2 -2
  42. package/dist/vue/date-picker.d.ts +8 -8
  43. package/dist/vue/discovery-controls.d.ts +1 -1
  44. package/dist/vue/global-components.d.ts +46 -0
  45. package/dist/vue/global-components.d.ts.map +1 -1
  46. package/dist/vue/image-cropper.d.ts +187 -0
  47. package/dist/vue/image-cropper.d.ts.map +1 -0
  48. package/dist/vue/image-cropper.js +310 -0
  49. package/dist/vue/image-cropper.js.map +1 -0
  50. package/dist/vue/index.d.ts +4 -0
  51. package/dist/vue/index.d.ts.map +1 -1
  52. package/dist/vue/index.js +4 -0
  53. package/dist/vue/index.js.map +1 -1
  54. package/dist/vue/kanban.d.ts +2 -2
  55. package/dist/vue/menu.d.ts +2 -2
  56. package/dist/vue/navigation-controls.d.ts +1 -1
  57. package/dist/vue/props.d.ts +6 -6
  58. package/dist/vue/scheduler.d.ts +229 -0
  59. package/dist/vue/scheduler.d.ts.map +1 -0
  60. package/dist/vue/scheduler.js +363 -0
  61. package/dist/vue/scheduler.js.map +1 -0
  62. package/dist/vue/scroll-frame.d.ts +1 -1
  63. package/dist/vue/speed-dial.d.ts +2 -2
  64. package/dist/vue/swipe-actions.d.ts +1 -1
  65. package/dist/vue/swipe-deck.d.ts +1 -1
  66. package/dist/vue/time-picker.d.ts +4 -4
  67. package/dist/vue/tour.d.ts +1 -1
  68. package/dist/vue/wayfinding-controls.d.ts +2 -2
  69. package/dist/vue/workflows.d.ts +3 -3
  70. package/package.json +1 -1
  71. package/src/advanced-collections.ts +199 -0
  72. package/src/capabilities.ts +10 -4
  73. package/src/image-crop.ts +125 -0
  74. package/src/index.ts +6 -0
  75. package/src/scheduler.ts +194 -0
  76. package/src/vue/advanced-collections.ts +679 -0
  77. package/src/vue/advanced-props.ts +144 -0
  78. package/src/vue/component-props.ts +14 -0
  79. package/src/vue/global-components.ts +46 -0
  80. package/src/vue/image-cropper.ts +413 -0
  81. package/src/vue/index.ts +8 -0
  82. package/src/vue/scheduler.ts +505 -0
@@ -132,8 +132,8 @@ export declare function createWorkflows(ui: Primitives, platform: 'web' | 'nativ
132
132
  }>> & Readonly<{
133
133
  "onUpdate:modelValue"?: ((_value: ChoiceValue) => any) | undefined;
134
134
  }>, {
135
- loading: boolean;
136
135
  disabled: boolean;
136
+ loading: boolean;
137
137
  modelValue: ChoiceValue | null;
138
138
  errorLabel: string;
139
139
  currentLabel: string;
@@ -249,12 +249,12 @@ export declare function createWorkflows(ui: Primitives, platform: 'web' | 'nativ
249
249
  "onUpdate:modelValue"?: ((_page: number) => any) | undefined;
250
250
  }>, {
251
251
  label: string;
252
- loading: boolean;
253
252
  disabled: boolean;
253
+ loading: boolean;
254
254
  modelValue: number;
255
+ emptyLabel: string;
255
256
  previousLabel: string;
256
257
  nextLabel: string;
257
- emptyLabel: string;
258
258
  currentLabel: string;
259
259
  pageSize: number;
260
260
  siblingCount: number;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@getcortexlabs/mavis-core",
3
- "version": "0.1.0-rc.12",
3
+ "version": "0.1.0-rc.12.1",
4
4
  "type": "module",
5
5
  "sideEffects": false,
6
6
  "description": "Shared Mavis themes and component contracts.",
@@ -0,0 +1,199 @@
1
+ import { addCivilDays, civilDate, civilWeekday, type CivilDate } from './date.js'
2
+
3
+ export interface TreeSelectNode {
4
+ id: string
5
+ label: string
6
+ disabled?: boolean
7
+ selectable?: boolean
8
+ children?: readonly TreeSelectNode[]
9
+ }
10
+ export interface TreeSelectRow {
11
+ node: TreeSelectNode
12
+ depth: number
13
+ ancestors: readonly string[]
14
+ disabled: boolean
15
+ }
16
+ export function treeSelectRows(nodes: readonly TreeSelectNode[]): TreeSelectRow[] {
17
+ const ids = new Set<string>(),
18
+ rows: TreeSelectRow[] = []
19
+ function visit(items: readonly TreeSelectNode[], ancestors: string[], disabled = false) {
20
+ if (ancestors.length > 32) throw new RangeError('TreeSelect supports at most 32 levels.')
21
+ for (const node of items) {
22
+ if (!node.id || ids.has(node.id) || !node.label.trim())
23
+ throw new TypeError(
24
+ 'TreeSelect requires unique nonempty IDs and labels; cycles are invalid.',
25
+ )
26
+ ids.add(node.id)
27
+ if (ids.size > 2000) throw new RangeError('TreeSelect supports at most 2000 nodes.')
28
+ const unavailable = disabled || !!node.disabled
29
+ rows.push({ node, depth: ancestors.length, ancestors, disabled: unavailable })
30
+ visit(node.children ?? [], [...ancestors, node.id], unavailable)
31
+ }
32
+ }
33
+ visit(nodes, [])
34
+ return rows
35
+ }
36
+ export function visibleTreeSelection(
37
+ rows: readonly TreeSelectRow[],
38
+ expanded: readonly string[],
39
+ query: string,
40
+ ) {
41
+ const text = query.trim().toLocaleLowerCase()
42
+ if (!text) return rows.filter((row) => row.ancestors.every((id) => expanded.includes(id)))
43
+ const visible = new Set<string>()
44
+ for (const row of rows)
45
+ if (row.node.label.toLocaleLowerCase().includes(text)) {
46
+ visible.add(row.node.id)
47
+ row.ancestors.forEach((id) => visible.add(id))
48
+ }
49
+ return rows.filter((row) => visible.has(row.node.id))
50
+ }
51
+ export function toggleTreeSelection(
52
+ nodes: readonly TreeSelectNode[],
53
+ values: readonly string[],
54
+ id: string,
55
+ multiple: boolean,
56
+ ) {
57
+ const row = treeSelectRows(nodes).find((row) => row.node.id === id)
58
+ if (!row || row.disabled || row.node.selectable === false) return [...values]
59
+ if (!multiple) return [id]
60
+ return values.includes(id)
61
+ ? values.filter((value) => value !== id)
62
+ : [...new Set([...values, id])]
63
+ }
64
+ export interface MasonryItem {
65
+ id: string
66
+ estimatedHeight?: number
67
+ }
68
+ export interface MasonryPlacement {
69
+ id: string
70
+ x: number
71
+ y: number
72
+ width: number
73
+ height: number
74
+ column: number
75
+ }
76
+ export function masonryLayout(
77
+ items: readonly MasonryItem[],
78
+ width: number,
79
+ minWidth: number,
80
+ gap: number,
81
+ maxColumns: number,
82
+ heights: ReadonlyMap<string, number> = new Map(),
83
+ ) {
84
+ if (
85
+ ![width, minWidth, gap, maxColumns].every(Number.isFinite) ||
86
+ width < 0 ||
87
+ minWidth < 40 ||
88
+ gap < 0 ||
89
+ !Number.isInteger(maxColumns) ||
90
+ maxColumns < 1 ||
91
+ maxColumns > 12
92
+ )
93
+ throw new RangeError('Masonry needs a nonnegative width/gap, minWidth >= 40 and 1–12 columns.')
94
+ uniqueAdvanced(items, 'Masonry', 500)
95
+ const columns = Math.max(1, Math.min(maxColumns, Math.floor((width + gap) / (minWidth + gap))))
96
+ const itemWidth = Math.max(0, (width - gap * (columns - 1)) / columns),
97
+ bottoms = Array<number>(columns).fill(0)
98
+ const placements = items.map((item) => {
99
+ const height = heights.get(item.id) ?? item.estimatedHeight ?? 180
100
+ if (!Number.isFinite(height) || height < 0)
101
+ throw new RangeError('Masonry heights must be finite and nonnegative.')
102
+ const column = bottoms.indexOf(Math.min(...bottoms)),
103
+ y = bottoms[column]!
104
+ bottoms[column] = y + height + gap
105
+ return { id: item.id, x: column * (itemWidth + gap), y, width: itemWidth, height, column }
106
+ })
107
+ return { columns, placements, height: Math.max(0, ...bottoms) - (items.length ? gap : 0) }
108
+ }
109
+ export interface HeatmapValue {
110
+ date: CivilDate
111
+ value: number | null
112
+ label?: string
113
+ disabled?: boolean
114
+ }
115
+ export function heatmapCalendar(
116
+ start: CivilDate,
117
+ end: CivilDate,
118
+ values: readonly HeatmapValue[],
119
+ weekStartsOn: 0 | 1 = 1,
120
+ ) {
121
+ if (![0, 1].includes(weekStartsOn)) throw new RangeError('Heatmap weekStartsOn must be 0 or 1.')
122
+ civilDate(start)
123
+ civilDate(end)
124
+ if (end < start || end > addCivilDays(start, 365))
125
+ throw new RangeError('Heatmap range must contain 1–366 days.')
126
+ const map = new Map<CivilDate, HeatmapValue>()
127
+ for (const item of values) {
128
+ civilDate(item.date)
129
+ if (
130
+ map.has(item.date) ||
131
+ (item.value !== null && (!Number.isFinite(item.value) || item.value < 0))
132
+ )
133
+ throw new TypeError('Heatmap dates must be unique and values nonnegative, finite or null.')
134
+ map.set(item.date, item)
135
+ }
136
+ const leading = (civilWeekday(start) - weekStartsOn + 7) % 7
137
+ const cells: (HeatmapValue & { index: number; row: number; column: number; missing: boolean })[] =
138
+ []
139
+ for (let day = start, i = 0; ; i++, day = addCivilDays(day, 1)) {
140
+ const entry = map.get(day),
141
+ index = leading + i
142
+ cells.push({
143
+ date: day,
144
+ value: entry?.value ?? null,
145
+ label: entry?.label,
146
+ disabled: entry?.disabled,
147
+ index,
148
+ row: index % 7,
149
+ column: Math.floor(index / 7),
150
+ missing: entry?.value == null,
151
+ })
152
+ if (day === end) break
153
+ }
154
+ const max = Math.max(0, ...cells.map((c) => c.value ?? 0))
155
+ return { cells, columns: cells[cells.length - 1]!.column + 1, max }
156
+ }
157
+ export function heatmapColor(value: number | null, max: number, colors: readonly string[]) {
158
+ if (
159
+ colors.length < 2 ||
160
+ colors.length > 8 ||
161
+ colors.some((color) => !/^#[\da-f]{6}$/i.test(color))
162
+ )
163
+ throw new TypeError('Heatmap colors require 2–8 six-digit HEX values.')
164
+ if (value === null) return 'transparent'
165
+ return colors[
166
+ Math.min(colors.length - 1, Math.floor((max ? value / max : 0) * (colors.length - 1)))
167
+ ]!
168
+ }
169
+ export interface MavisNotification {
170
+ id: string
171
+ title: string
172
+ description?: string
173
+ group?: string
174
+ time?: string
175
+ read?: boolean
176
+ disabled?: boolean
177
+ dismissible?: boolean
178
+ actionLabel?: string
179
+ }
180
+ export function uniqueAdvanced(items: readonly { id: string }[], label: string, limit = 500) {
181
+ const ids = new Set<string>()
182
+ if (items.length > limit) throw new RangeError(`${label} supports at most ${limit} items.`)
183
+ for (const item of items) {
184
+ if (!item.id || ids.has(item.id)) throw new TypeError(`${label} requires unique nonempty IDs.`)
185
+ ids.add(item.id)
186
+ }
187
+ }
188
+ export function updateNotifications<T extends MavisNotification>(
189
+ items: readonly T[],
190
+ ids: readonly string[],
191
+ action: 'read' | 'unread' | 'dismiss',
192
+ ) {
193
+ uniqueAdvanced(items, 'NotificationCenter', 1000)
194
+ return items.flatMap((item) => {
195
+ if (!ids.includes(item.id) || item.disabled) return [item]
196
+ if (action === 'dismiss') return item.dismissible === false ? [item] : []
197
+ return [{ ...item, read: action === 'read' }]
198
+ })
199
+ }
@@ -1,5 +1,11 @@
1
1
  /** Source capabilities, not a promise that every feature is in the last npm release. */
2
2
  export const componentNames = [
3
+ 'MTreeSelect',
4
+ 'MMasonry',
5
+ 'MHeatmap',
6
+ 'MImageCropper',
7
+ 'MScheduler',
8
+ 'MNotificationCenter',
3
9
  'MKanban',
4
10
  'MDonutChart',
5
11
  'MSparkline',
@@ -99,11 +105,11 @@ export type CapabilityStatus = 'experimental' | 'planned' | 'unsupported' | 'unv
99
105
  export const targetCapabilities = {
100
106
  version: 1,
101
107
  source: 'repository',
102
- publishedBaseline: '0.1.0-rc.12',
108
+ publishedBaseline: '0.1.0-rc.12.1',
103
109
  developmentMotion: {
104
110
  availability: 'published',
105
111
  joltCommit: null,
106
- publishedJoltRelease: '0.1.0-rc.11.1',
112
+ publishedJoltRelease: '0.1.0-rc.12.1',
107
113
  features: {
108
114
  gradient: ['web', 'ios', 'android'],
109
115
  loadingEffects: ['web', 'ios'],
@@ -129,7 +135,7 @@ export const targetCapabilities = {
129
135
  streaming: 'unverified',
130
136
  rsc: 'unsupported',
131
137
  },
132
- motion: { engine: 'jolt', minimum: '0.1.0-rc.11.1', start: 'client-mount' },
138
+ motion: { engine: 'jolt', minimum: '0.1.0-rc.12.1', start: 'client-mount' },
133
139
  ssr: {
134
140
  availability: '0.1.0-alpha.5',
135
141
  host: 'nuxt',
@@ -172,7 +178,7 @@ export const targetCapabilities = {
172
178
  streaming: 'unsupported',
173
179
  rsc: 'unsupported',
174
180
  },
175
- motion: { engine: 'jolt', minimum: '0.1.0-rc.11.1', start: 'native-loaded' },
181
+ motion: { engine: 'jolt', minimum: '0.1.0-rc.12.1', start: 'native-loaded' },
176
182
  },
177
183
  ],
178
184
  planned: [
@@ -0,0 +1,125 @@
1
+ export type CropRotation = 0 | 90 | 180 | 270
2
+ /** Coordinates in the decoded image after applying the clockwise quarter rotation. */
3
+ export interface ImageCrop {
4
+ x: number
5
+ y: number
6
+ width: number
7
+ height: number
8
+ rotation: CropRotation
9
+ }
10
+ export interface CropImage {
11
+ width: number
12
+ height: number
13
+ }
14
+ export interface CropExportOptions {
15
+ mimeType: 'image/png' | 'image/jpeg'
16
+ quality: number
17
+ width?: number
18
+ }
19
+ /** Web returns a data URI; NativeScript returns a temporary file owned by the caller. */
20
+ export interface CropExport {
21
+ uri: string
22
+ width: number
23
+ height: number
24
+ mimeType: 'image/png' | 'image/jpeg'
25
+ dispose(): Promise<void>
26
+ }
27
+ export interface CropSource extends CropImage {
28
+ readonly preview: unknown
29
+ export(crop: ImageCrop, options: CropExportOptions): Promise<CropExport>
30
+ dispose(): void
31
+ }
32
+ export function rotatedImage(image: CropImage, rotation: CropRotation) {
33
+ if (
34
+ ![0, 90, 180, 270].includes(rotation) ||
35
+ !Number.isFinite(image.width) ||
36
+ !Number.isFinite(image.height) ||
37
+ image.width <= 0 ||
38
+ image.height <= 0
39
+ )
40
+ throw new RangeError('Crop source dimensions and quarter rotation must be valid.')
41
+ return rotation === 90 || rotation === 270 ? { width: image.height, height: image.width } : image
42
+ }
43
+ export function fitImageCrop(
44
+ image: CropImage,
45
+ aspectRatio: number,
46
+ rotation: CropRotation = 0,
47
+ ): ImageCrop {
48
+ const size = rotatedImage(image, rotation)
49
+ if (!Number.isFinite(aspectRatio) || aspectRatio < 0.1 || aspectRatio > 10)
50
+ throw new RangeError('Crop aspectRatio must be between 0.1 and 10.')
51
+ const width = Math.min(size.width, size.height * aspectRatio),
52
+ height = width / aspectRatio
53
+ return { x: (size.width - width) / 2, y: (size.height - height) / 2, width, height, rotation }
54
+ }
55
+ export function validateImageCrop(image: CropImage, crop: ImageCrop, aspectRatio?: number) {
56
+ const size = rotatedImage(image, crop.rotation)
57
+ if (
58
+ ![crop.x, crop.y, crop.width, crop.height].every(Number.isFinite) ||
59
+ crop.x < 0 ||
60
+ crop.y < 0 ||
61
+ crop.width < 1 ||
62
+ crop.height < 1 ||
63
+ crop.x + crop.width > size.width + 0.001 ||
64
+ crop.y + crop.height > size.height + 0.001 ||
65
+ (aspectRatio !== undefined && Math.abs(crop.width / crop.height - aspectRatio) > 0.001)
66
+ )
67
+ throw new RangeError('Crop must stay inside the rotated source and respect the aspect ratio.')
68
+ return crop
69
+ }
70
+ export function moveImageCrop(
71
+ image: CropImage,
72
+ crop: ImageCrop,
73
+ dx: number,
74
+ dy: number,
75
+ ): ImageCrop {
76
+ validateImageCrop(image, crop)
77
+ if (![dx, dy].every(Number.isFinite)) throw new RangeError('Crop offsets must be finite.')
78
+ const size = rotatedImage(image, crop.rotation)
79
+ return {
80
+ ...crop,
81
+ x: Math.max(0, Math.min(size.width - crop.width, crop.x + dx)),
82
+ y: Math.max(0, Math.min(size.height - crop.height, crop.y + dy)),
83
+ }
84
+ }
85
+ export function zoomImageCrop(image: CropImage, crop: ImageCrop, zoom: number): ImageCrop {
86
+ validateImageCrop(image, crop)
87
+ if (!Number.isFinite(zoom) || zoom < 1 || zoom > 8)
88
+ throw new RangeError('Crop zoom must be between 1 and 8.')
89
+ const fit = fitImageCrop(image, crop.width / crop.height, crop.rotation),
90
+ width = fit.width / Math.min(zoom, fit.width, fit.height),
91
+ height = fit.height / Math.min(zoom, fit.width, fit.height)
92
+ return moveImageCrop(
93
+ image,
94
+ { ...crop, x: 0, y: 0, width, height },
95
+ crop.x + crop.width / 2 - width / 2,
96
+ crop.y + crop.height / 2 - height / 2,
97
+ )
98
+ }
99
+ export function cropOutputSize(crop: ImageCrop, options: CropExportOptions) {
100
+ if (
101
+ !['image/png', 'image/jpeg'].includes(options.mimeType) ||
102
+ !Number.isFinite(options.quality) ||
103
+ options.quality < 0 ||
104
+ options.quality > 1
105
+ )
106
+ throw new RangeError('Invalid crop output format or quality.')
107
+ const width = options.width ?? Math.round(crop.width),
108
+ height = Math.round((width * crop.height) / crop.width)
109
+ if (!Number.isInteger(width) || width < 1 || width > 4096 || height < 1 || height > 4096)
110
+ throw new RangeError('Crop output dimensions must be between 1 and 4096 pixels.')
111
+ return { width, height }
112
+ }
113
+ /** Original-image center and scale within the crop viewport; rotation is about the center. */
114
+ export function cropPresentation(image: CropImage, crop: ImageCrop, viewportWidth: number) {
115
+ validateImageCrop(image, crop)
116
+ const size = rotatedImage(image, crop.rotation),
117
+ scale = viewportWidth / crop.width
118
+ return {
119
+ width: image.width * scale,
120
+ height: image.height * scale,
121
+ x: (size.width / 2 - crop.x - image.width / 2) * scale,
122
+ y: (size.height / 2 - crop.y - image.height / 2) * scale,
123
+ rotation: crop.rotation,
124
+ }
125
+ }
package/src/index.ts CHANGED
@@ -118,3 +118,9 @@ export * from './screen-components.js'
118
118
  export * from './creative-controls.js'
119
119
 
120
120
  export * from './dashboard.js'
121
+
122
+ export * from './advanced-collections.js'
123
+
124
+ export * from './image-crop.js'
125
+
126
+ export * from './scheduler.js'
@@ -0,0 +1,194 @@
1
+ import { addCivilDays, civilDate, parseCivilDate, formatCivilDate, type CivilDate } from './date.js'
2
+ import { uniqueAdvanced } from './advanced-collections.js'
3
+ export interface SchedulerEvent {
4
+ id: string
5
+ title: string
6
+ start: number
7
+ end: number
8
+ color?: string
9
+ disabled?: boolean
10
+ }
11
+ export interface SchedulerCivilTime {
12
+ date: CivilDate
13
+ minute: number
14
+ }
15
+ export interface SchedulerClock {
16
+ parts(instant: number, timeZone: string): SchedulerCivilTime
17
+ }
18
+ export type SchedulerDisambiguation = 'reject' | 'earlier' | 'later'
19
+ export interface SchedulerChange {
20
+ id: string
21
+ start: number
22
+ end: number
23
+ kind: 'move' | 'resize'
24
+ }
25
+ function civilMilliseconds(value: SchedulerCivilTime) {
26
+ const parts = parseCivilDate(value.date)
27
+ if (!parts || !Number.isInteger(value.minute) || value.minute < 0 || value.minute >= 1440)
28
+ throw new RangeError('Invalid scheduler civil time.')
29
+ const date = new Date(0)
30
+ date.setUTCFullYear(parts.year, parts.month - 1, parts.day)
31
+ date.setUTCHours(0, value.minute, 0, 0)
32
+ return date.getTime()
33
+ }
34
+ export function schedulerCivilFromUTC(value: number): SchedulerCivilTime {
35
+ const date = new Date(value)
36
+ return {
37
+ date: formatCivilDate({
38
+ year: date.getUTCFullYear(),
39
+ month: date.getUTCMonth() + 1,
40
+ day: date.getUTCDate(),
41
+ }),
42
+ minute: date.getUTCHours() * 60 + date.getUTCMinutes(),
43
+ }
44
+ }
45
+ /** Resolve wall time by testing actual zone offsets around the date; never guess a DST gap. */
46
+ export function schedulerInstant(
47
+ value: SchedulerCivilTime,
48
+ timeZone: string,
49
+ clock: SchedulerClock,
50
+ disambiguation: SchedulerDisambiguation = 'reject',
51
+ ) {
52
+ if (!['reject', 'earlier', 'later'].includes(disambiguation))
53
+ throw new RangeError('Invalid scheduler disambiguation.')
54
+ if (!timeZone.trim()) throw new RangeError('Scheduler requires an explicit timeZone.')
55
+ const nominal = civilMilliseconds(value),
56
+ offsets = new Set<number>()
57
+ for (let hours = -36; hours <= 36; hours += 6) {
58
+ const instant = nominal + hours * 3600000
59
+ offsets.add(civilMilliseconds(clock.parts(instant, timeZone)) - instant)
60
+ }
61
+ const matches = [...offsets]
62
+ .map((offset) => nominal - offset)
63
+ .filter((instant) => {
64
+ const parts = clock.parts(instant, timeZone)
65
+ return parts.date === value.date && parts.minute === value.minute
66
+ })
67
+ .sort((a, b) => a - b)
68
+ if (!matches.length)
69
+ throw new RangeError('This local time does not exist in the selected time zone.')
70
+ if (matches.length > 1 && disambiguation === 'reject')
71
+ throw new RangeError('This local time occurs twice. Choose earlier or later explicitly.')
72
+ return matches[disambiguation === 'later' ? matches.length - 1 : 0]!
73
+ }
74
+ export function validateSchedulerEvents(events: readonly SchedulerEvent[]) {
75
+ uniqueAdvanced(events, 'Scheduler', 500)
76
+ for (const event of events)
77
+ if (
78
+ !event.title.trim() ||
79
+ !Number.isFinite(event.start) ||
80
+ !Number.isFinite(event.end) ||
81
+ event.end <= event.start ||
82
+ event.end - event.start > 31 * 86400000 ||
83
+ Math.abs(event.start) > 8640000000000000 ||
84
+ Math.abs(event.end) > 8640000000000000 ||
85
+ (event.color && !/^#[\da-f]{6}$/i.test(event.color))
86
+ )
87
+ throw new RangeError(
88
+ 'Scheduler events require a title, ordered epoch milliseconds (duration <=31 days) and optional HEX color.',
89
+ )
90
+ }
91
+ export function changeSchedulerEvent<T extends SchedulerEvent>(
92
+ events: readonly T[],
93
+ change: SchedulerChange,
94
+ ) {
95
+ validateSchedulerEvents(events)
96
+ const event = events.find((event) => event.id === change.id)
97
+ if (!event || event.disabled) return [...events]
98
+ const next = events.map((event) =>
99
+ event.id === change.id ? { ...event, start: change.start, end: change.end } : event,
100
+ )
101
+ validateSchedulerEvents(next)
102
+ return next
103
+ }
104
+ export function schedulerLayout(
105
+ events: readonly SchedulerEvent[],
106
+ date: CivilDate,
107
+ days: number,
108
+ timeZone: string,
109
+ clock: SchedulerClock,
110
+ startHour = 0,
111
+ endHour = 24,
112
+ ) {
113
+ civilDate(date)
114
+ clock.parts(new Date(`${date}T12:00:00.000Z`).getTime(), timeZone)
115
+ validateSchedulerEvents(events)
116
+ if (
117
+ ![1, 7].includes(days) ||
118
+ !Number.isInteger(startHour) ||
119
+ !Number.isInteger(endHour) ||
120
+ startHour < 0 ||
121
+ endHour > 24 ||
122
+ startHour >= endHour
123
+ )
124
+ throw new RangeError('Scheduler needs a day/week and ordered whole-hour bounds.')
125
+ return Array.from({ length: days }, (_, day) => {
126
+ const civil = addCivilDays(date, day)
127
+ const segments = events
128
+ .flatMap((event) => {
129
+ const start = clock.parts(event.start, timeZone),
130
+ end = clock.parts(event.end, timeZone)
131
+ if (start.date > civil || end.date < civil || (end.date === civil && end.minute === 0))
132
+ return []
133
+ const top = Math.max(startHour * 60, start.date < civil ? 0 : start.minute),
134
+ bottom = Math.min(endHour * 60, end.date > civil ? 1440 : end.minute)
135
+ // A repeated-hour event may finish at an earlier wall time; retain its elapsed duration.
136
+ const finish =
137
+ end.minute <= start.minute &&
138
+ start.minute >= startHour * 60 &&
139
+ start.minute < endHour * 60 &&
140
+ event.end > event.start &&
141
+ start.date === civil &&
142
+ end.date === civil
143
+ ? Math.min(endHour * 60, top + (event.end - event.start) / 60000)
144
+ : bottom
145
+ return finish > top
146
+ ? [
147
+ {
148
+ event,
149
+ day,
150
+ date: civil,
151
+ top,
152
+ bottom: finish,
153
+ lane: 0,
154
+ lanes: 1,
155
+ startsHere: start.date === civil,
156
+ endsHere: end.date === civil,
157
+ },
158
+ ]
159
+ : []
160
+ })
161
+ .sort(
162
+ (a, b) =>
163
+ a.top - b.top || a.event.start - b.event.start || a.event.id.localeCompare(b.event.id),
164
+ )
165
+ let group: typeof segments = [],
166
+ ends: number[] = [],
167
+ groupEnd = 0
168
+ function finish() {
169
+ for (const segment of group) segment.lanes = ends.length
170
+ group = []
171
+ ends = []
172
+ }
173
+ for (const segment of segments) {
174
+ if (group.length && segment.top >= groupEnd) finish()
175
+ let lane = ends.findIndex((end) => end <= segment.top)
176
+ if (lane < 0) lane = ends.length
177
+ ends[lane] = segment.bottom
178
+ segment.lane = lane
179
+ group.push(segment)
180
+ groupEnd = Math.max(...ends)
181
+ }
182
+ finish()
183
+ return { date: civil, segments }
184
+ })
185
+ }
186
+
187
+ /** Offset distinguishes the two occurrences of a repeated local time. */
188
+ export function schedulerOffset(instant: number, timeZone: string, clock: SchedulerClock) {
189
+ const minutes = Math.round(
190
+ (civilMilliseconds(clock.parts(instant, timeZone)) - Math.floor(instant / 60000) * 60000) /
191
+ 60000,
192
+ )
193
+ return `UTC${minutes >= 0 ? '+' : '−'}${String(Math.floor(Math.abs(minutes) / 60)).padStart(2, '0')}:${String(Math.abs(minutes) % 60).padStart(2, '0')}`
194
+ }