Repository navigation
Expand file tree
/
Copy pathMMM-CalendarExt3Timeline.js
More file actions
304 lines (264 loc) · 9.72 KB
/
Copy pathMMM-CalendarExt3Timeline.js
File metadata and controls
304 lines (264 loc) · 9.72 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
Module.register('MMM-CalendarExt3Timeline', {
defaults: {
instanceId: null,
title: null,
titleWidth: '120px',
locale: null,
staticMode: true,
refreshInterval: 1000 * 60,
waitFetch: 1000 * 5,
animationSpeed: 1000,
beginHour: 0,
hourLength: 24,
hourIndexOptions: {
hour: 'numeric',
},
dateIndexOptions: {
dayStyle: 'short'
},
calendarSet: [],
groupBy: 'calendarName',
eventFilter: null,
eventTransformer: null,
preProcessor: null,
useSymbol: true,
notification: 'CALENDAR_EVENTS', /* reserved */
maxSlots: null,
displayLegend: false,
},
getStyles: function () {
return ['MMM-CalendarExt3Timeline.css']
},
groupEvents: function(events, groupBy) {
const groups = new Map()
for (let event of events) {
let groupName = 'Other'
if (typeof groupBy === 'function') {
try {
groupName = groupBy(event) ?? 'Other'
} catch (error) {
Log.warn('[CX3T] groupBy callback failed:', error)
}
} else if (typeof groupBy === 'string' && groupBy) {
groupName = event[groupBy] ?? 'Other'
}
groupName = String(groupName)
if (!groups.has(groupName)) groups.set(groupName, [])
groups.get(groupName).push(event)
}
return groups
},
stackEvents: function(events) {
const stacks = []
for (let event of events) {
const availableStack = stacks.find((stack) => {
return stack.every((existingEvent) => {
return ((existingEvent.startDate <= event.startDate)
? (existingEvent.endDate <= event.startDate)
: (event.endDate <= existingEvent.startDate)
)
})
})
if (availableStack) {
availableStack.push(event)
} else {
stacks.push([event])
}
}
return stacks
},
limitStacks: function(stacks, maxSlots) {
if (maxSlots === null || maxSlots === undefined) return stacks
if (!Number.isInteger(maxSlots) || maxSlots < 1) return stacks
return stacks.slice(0, maxSlots)
},
normalizeHourLength: function(hourLength) {
return Math.ceil((hourLength <= 1) ? 6 : hourLength)
},
normalizeTitleWidth: function(titleWidth) {
return typeof titleWidth === 'string' ? titleWidth : '120px'
},
start: function() {
this.instanceId = this.config.instanceId ?? this.identifier
this.hourLength = this.normalizeHourLength(this.config.hourLength)
this.eventPool = new Map()
this.storedEvents = []
this.refreshTimer = null
this.locale = Intl.getCanonicalLocales(this.config.locale ?? config.language)?.[0] ?? ''
this._ready = false
const _firstData = new Promise((resolve) => {
this._receiveFirstData = resolve
})
const _domCreated = new Promise((resolve) => {
this._domReady = resolve
})
void this.initialize({ _domCreated, _firstData })
},
async initialize({ _domCreated, _firstData }) {
try {
this.library = await import(new URL(this.file('CX3_Shared/CX3_shared.js'), document.baseURI).href)
const [, { payload, sender }] = await Promise.all([_domCreated, _firstData])
this.library.prepareMagic()
this._ready = true
this.fetch(payload, sender)
setTimeout(() => this.updateDom(this.config.animationSpeed), this.config.waitFetch)
}
catch (error) {
Log.error('[CX3T] Module initialization failed:', error)
}
},
notificationReceived: function(notification, payload, sender) {
if (notification === this.config.notification) {
if (this?.storedEvents?.length == 0 && payload.length > 0) {
this._receiveFirstData({payload, sender})
}
if (this?.library?.loaded) {
this.fetch(payload, sender)
} else {
Log.warn('[CX3T] Module is not prepared yet, wait a while.')
}
}
if (notification === 'DOM_OBJECTS_CREATED') {
this._domReady()
}
},
fetch: function(payload, sender) {
this.eventPool.set(sender.identifier, structuredClone(payload))
this.storedEvents = this.library.regularizeEvents({
eventPool: this.eventPool,
config: this.config
})
},
getDom: function() {
let dom = document.createElement('div')
dom.classList.add('bodice', 'CX3T_' + this.instanceId, 'CX3T')
dom = this.draw(dom, this.config)
if (this.library?.loaded) {
if (this.refreshTimer) {
clearTimeout(this.refreshTimer)
this.refreshTimer = null
}
this.refreshTimer = setTimeout(() => {
clearTimeout(this.refreshTimer)
this.refreshTimer = null
this.updateDom(this.config.animationSpeed)
}, this.config.refreshInterval)
} else {
Log.warn('[CX3T] Module is not prepared yet, wait a while.')
}
return dom
},
draw: function (dom, config) {
if (!this.library?.loaded) return dom
let thisMoment = new Date()
let startFrame = (config.staticMode)
? (new Date(thisMoment.getFullYear(), thisMoment.getMonth(), thisMoment.getDate(), config.beginHour))
: (new Date(thisMoment.getFullYear(), thisMoment.getMonth(), thisMoment.getDate(), thisMoment.getHours() + config.beginHour))
let endFrame = new Date(new Date(startFrame).setHours(startFrame.getHours() + this.hourLength))
let sv = startFrame.valueOf()
let ev = endFrame.valueOf()
let ni = Math.round((thisMoment.valueOf() - sv) / (ev - sv) * 10000) / 100
if (ni >= 100) ni = 100
dom.style.setProperty('--nowIndex', ni + '%')
let events = this.library.prepareEvents({
targetEvents: this.storedEvents,
range: [sv, ev],
config: config
})
dom.dataset.events = events.length
const groups = this.groupEvents(events, config.groupBy)
dom.innerHTML = ''
let content = document.createElement('div')
content.classList.add('timelineContent')
const title = typeof config.title === 'string' ? config.title.trim() : ''
if (title) {
const titleWidth = CSS.supports('width', this.normalizeTitleWidth(config.titleWidth))
? this.normalizeTitleWidth(config.titleWidth)
: '120px'
dom.style.setProperty('--timelineTitleWidth', titleWidth)
let titleRow = document.createElement('div')
titleRow.classList.add('titleRow')
let titleElement = document.createElement('div')
titleElement.classList.add('timelineTitle')
titleElement.textContent = title
titleElement.title = title
titleRow.appendChild(titleElement)
titleRow.appendChild(content)
dom.appendChild(titleRow)
} else {
dom.appendChild(content)
}
let lines = document.createElement('div')
lines.classList.add('timelines')
let frameLength = ev - sv
// dateIndices
let di = document.createElement('div')
di.classList.add('indexContainer', 'dateIndices')
// hourIndices
let hi = document.createElement('div')
hi.classList.add('indexContainer', 'hourIndices')
let dxPool = new Map()
for (let hx = 0; hx < this.hourLength; hx++) {
let d = new Date(startFrame.getFullYear(), startFrame.getMonth(), startFrame.getDate(), startFrame.getHours() + hx)
let hxd = document.createElement('div')
hxd.classList.add('hourIndex', 'index')
hxd.dataset.hour = d.getHours()
hxd.innerHTML = new Intl.DateTimeFormat(this.locale, config.hourIndexOptions).formatToParts(d).reduce((prev, cur, curIndex) => {
prev = prev + `<span class="cellTimeIndexParts ${cur.type} seq_${curIndex}">${cur.value}</span>`
return prev
}, '')
hi.appendChild(hxd)
let id = new Date(d.getFullYear(), d.getMonth(), d.getDate()).valueOf()
let dx = (dxPool.has(id)) ? dxPool.get(id) : 0
dxPool.set(id, dx + 1)
}
[...dxPool.entries()].sort((a, b) => {
return a[0] - b[0]
}).forEach((dd) => {
let dxd = document.createElement('div')
dxd.classList.add('dateIndex', 'index')
dxd.dataset.datetime = dd[0]
dxd.dataset.length = dd[1]
dxd.style.gridColumn = 'span ' + dd[1]
dxd.innerHTML = new Intl.DateTimeFormat(this.locale, config.dateIndexOptions).formatToParts(new Date(dd[0])).reduce((prev, cur, curIndex) => {
prev = prev + `<span class="cellDateIndexParts ${cur.type} seq_${curIndex}">${cur.value}</span>`
return prev
}, '')
di.appendChild(dxd)
})
content.appendChild(di)
content.appendChild(hi)
let groupIndex = 0
for (let [groupName, groupEvents] of groups) {
if (config.groupBy) {
let groupTitle = document.createElement('div')
groupTitle.classList.add('timelineGroupTitle')
groupTitle.textContent = groupName
lines.appendChild(groupTitle)
}
const stacks = this.stackEvents(groupEvents)
const visibleStacks = this.limitStacks(stacks, config.maxSlots)
let i = 0
for (let stack of visibleStacks) {
let tl = document.createElement('div')
tl.classList.add('timeline', 'timeline_' + i++)
tl.classList.add('timelineGroup_' + groupIndex)
for (let event of stack) {
let e = this.library.renderEvent(event, {
useSymbol: config.useSymbol
})
if (event.startDate < sv) e.classList.add('fromPast')
if (event.endDate > ev) e.classList.add('toFuture')
e.style.setProperty('--startPosition', (event.startDate <= sv) ? '0%' : Math.round((event.startDate - sv) / frameLength * 10000) / 100 + '%')
e.style.setProperty('--endPosition', (event.endDate >= ev) ? '0%' : Math.round((ev - event.endDate) / frameLength * 10000) / 100 + '%')
if (e) tl.appendChild(e)
}
lines.appendChild(tl)
}
groupIndex++
}
content.appendChild(lines)
if (config.displayLegend) this.library.displayLegend(content, events, {useSymbol: config.useSymbol})
return dom
},
})