@record-evolution/widget-linechart 1.4.9

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.
@@ -0,0 +1,371 @@
1
+ import { html, css, LitElement } from 'lit';
2
+ import { repeat } from 'lit/directives/repeat.js'
3
+ import { property, state } from 'lit/decorators.js';
4
+ import Chart, { ChartDataset } from 'chart.js/auto';
5
+ import tinycolor from "tinycolor2";
6
+ // This does not work. See comments at the end of the file.
7
+ // import 'chartjs-adapter-dayjs-4/dist/chartjs-adapter-dayjs-4.esm';
8
+ // import 'chartjs-adapter-moment';
9
+ // import 'chartjs-adapter-date-fns';
10
+ import { InputData, Data, Dataseries } from './types.js'
11
+
12
+ export class WidgetLinechart extends LitElement {
13
+
14
+ @property({type: Object})
15
+ inputData = {} as InputData
16
+
17
+ @state()
18
+ private canvasList: Map<string, {chart?: any, dataSets: Dataseries[]}> = new Map()
19
+
20
+ version: string = 'versionplaceholder'
21
+
22
+ update(changedProperties: Map<string, any>) {
23
+ if (changedProperties.has('inputData')) {
24
+ this.transformInputData()
25
+ this.applyInputData()
26
+ }
27
+ super.update(changedProperties)
28
+ }
29
+
30
+ protected firstUpdated(): void {
31
+ this.applyInputData()
32
+ }
33
+
34
+ transformInputData() {
35
+
36
+ if (!this?.inputData?.dataseries.length) return
37
+
38
+ // reset all existing chart dataseries
39
+ this.canvasList.forEach(chartM => chartM.dataSets = [])
40
+ this.inputData.dataseries.forEach(ds => {
41
+ ds.chartName = ds.chartName ?? ''
42
+ if (ds.borderDash && typeof ds.borderDash === 'string') {
43
+ ds.borderDash = JSON.parse(ds.borderDash)
44
+ } else {
45
+ ds.borderDash = undefined
46
+ }
47
+
48
+ // pivot data
49
+ const distincts = [...new Set(ds.data.map((d: Data) => d.pivot))]
50
+ const derivedBgColors = tinycolor(ds.backgroundColor).monochromatic(distincts.length).map((c: any) => c.toHexString())
51
+ const derivedBdColors = tinycolor(ds.borderColor).monochromatic(distincts.length).map((c: any) => c.toHexString())
52
+
53
+ if (distincts.length > 1) {
54
+ distincts.forEach((piv, i) => {
55
+ const pds: any = {
56
+ label: ds.label + ' ' + piv,
57
+ type: ds.type,
58
+ showLine: true,
59
+ radius: ds.radius,
60
+ pointStyle: ds.pointStyle,
61
+ backgroundColor: derivedBgColors[i],
62
+ borderColor: derivedBdColors[i],
63
+ borderWidth: ds.borderWidth,
64
+ borderDash: ds.borderDash,
65
+ fill: ds.fill,
66
+ data: ds.data.filter(d => d.pivot === piv)
67
+ }
68
+ // If the chartName ends with :pivot: then create a seperate chart for each pivoted dataseries
69
+ const chartName = ds.chartName.endsWith('#pivot#') ? ds.chartName + piv : ds.chartName
70
+ if (!this.canvasList.has(chartName)) {
71
+ // initialize new charts
72
+ this.canvasList.set(chartName, {chart: undefined, dataSets: [] as Dataseries[]})
73
+ }
74
+ this.canvasList.get(chartName)?.dataSets.push(pds)
75
+ })
76
+ } else {
77
+ if (!this.canvasList.has(ds.chartName)) {
78
+ // initialize new charts
79
+ this.canvasList.set(ds.chartName, {chart: undefined, dataSets: [] as Dataseries[]})
80
+ }
81
+ this.canvasList.get(ds.chartName)?.dataSets.push(ds)
82
+ }
83
+ })
84
+ // prevent duplicate transformation
85
+ this.inputData.dataseries = []
86
+ // console.log('new linechart datasets', this.canvasList)
87
+ }
88
+
89
+
90
+ applyInputData() {
91
+ this.setupCharts()
92
+
93
+ this.canvasList.forEach(({chart, dataSets}) => {
94
+ if (chart) {
95
+ chart.data.datasets = dataSets
96
+ chart.options.scales.x.type = this.xAxisType()
97
+ chart.options.scales.x.title.display = !!this.inputData?.settings?.xAxisLabel
98
+ chart.options.scales.x.title.text = this.inputData?.settings?.xAxisLabel
99
+ chart.options.scales.y.title.display = !!this.inputData?.settings?.yAxisLabel
100
+ chart.options.scales.y.title.text = this.inputData?.settings?.yAxisLabel
101
+ chart?.update('resize')
102
+ }
103
+ })
104
+ }
105
+
106
+ xAxisType() {
107
+ if (this.inputData?.settings?.timeseries) return 'time'
108
+ const onePoint = this.inputData.dataseries?.[0].data?.[0]
109
+ // @ts-ignore
110
+ if (onePoint && !isNaN(onePoint.x)) return 'linear'
111
+ return 'category'
112
+ }
113
+
114
+ setupCharts() {
115
+
116
+ this.canvasList.forEach((chartM, chartName) => {
117
+ if (!chartM.dataSets.length) this.canvasList.delete(chartName)
118
+ if (chartM.chart) return
119
+ const canvas = this.shadowRoot?.querySelector(`[name="${chartName}"]`) as HTMLCanvasElement
120
+ if (!canvas) return
121
+ // console.log('chartM', canvas, chartM.chart)
122
+ chartM.chart = new Chart(
123
+ canvas,
124
+ {
125
+ type: 'line',
126
+ data: {
127
+ // @ts-ignore
128
+ datasets: chartM.dataSets
129
+ },
130
+ options: {
131
+ responsive: true,
132
+ maintainAspectRatio: false,
133
+ animations: {
134
+ "colors": false,
135
+ "x": false,
136
+ },
137
+ transitions: {
138
+ "active": {
139
+ "animation": {
140
+ "duration": 100
141
+ }
142
+ }
143
+ },
144
+ scales: {
145
+ x: {
146
+ type: this.xAxisType(),
147
+ title: {
148
+ display: !!this.inputData?.settings?.xAxisLabel,
149
+ text: this.inputData?.settings?.xAxisLabel
150
+ }
151
+ },
152
+ y: {
153
+ title: {
154
+ display: !!this.inputData?.settings?.yAxisLabel,
155
+ text: this.inputData?.settings?.yAxisLabel
156
+ }
157
+ }
158
+ },
159
+ },
160
+ }
161
+ )
162
+ })
163
+ }
164
+
165
+ static styles = css`
166
+ :host {
167
+ display: block;
168
+ color: var(--re-text-color, #000);
169
+
170
+ font-family: sans-serif;
171
+ padding: 16px;
172
+ box-sizing: border-box;
173
+ margin: auto;
174
+ }
175
+
176
+ .paging:not([active]) { display: none !important; }
177
+
178
+ .columnLayout {
179
+ flex-direction: column;
180
+ }
181
+
182
+ .wrapper {
183
+ display: flex;
184
+ flex-direction: column;
185
+ height: 100%;
186
+ width: 100%;
187
+ }
188
+
189
+ .chart-container {
190
+ display: flex;
191
+ flex: 1;
192
+ overflow: hidden;
193
+ position: relative;
194
+ }
195
+
196
+ .sizer {
197
+ flex: 1;
198
+ overflow: hidden;
199
+ position: relative;
200
+ }
201
+
202
+ header {
203
+ display: flex;
204
+ flex-direction: column;
205
+ margin: 0 0 16px 0;
206
+ }
207
+ h3 {
208
+ margin: 0;
209
+ max-width: 300px;
210
+ overflow: hidden;
211
+ text-overflow: ellipsis;
212
+ white-space: nowrap;
213
+ }
214
+ p {
215
+ margin: 10px 0 0 0;
216
+ max-width: 300px;
217
+ font-size: 14px;
218
+ line-height: 17px;
219
+ }
220
+ `;
221
+
222
+ render() {
223
+ return html`
224
+ <div class="wrapper">
225
+ <header>
226
+ <h3 class="paging" ?active=${this.inputData?.settings?.title}>${this.inputData?.settings?.title}</h3>
227
+ <p class="paging" ?active=${this.inputData?.settings?.subTitle}>${this.inputData?.settings?.subTitle}</p>
228
+ </header>
229
+
230
+ <div class="chart-container ${this?.inputData?.settings?.columnLayout ? 'columnLayout': ''}">
231
+ ${repeat(this.canvasList, ([chartName, chartM]) => chartName, ([chartName]) => html`
232
+ <div class="sizer">
233
+ <canvas name="${chartName}"></canvas>
234
+ </div>
235
+ `)}
236
+ </div>
237
+ </div>
238
+ `;
239
+ }
240
+ }
241
+ window.customElements.define('widget-linechart-versionplaceholder', WidgetLinechart)
242
+
243
+ // ############################################### WORKAROUND #######################################################################
244
+ //
245
+ // For some reason the import of that adapter is messed up. I suspect that rollup does things in the wrong order.
246
+ // Because this is an import that has side effects. i.e. it overrides the adapters of the previously imported Chart.js
247
+ // So the current solution is to execute the source code here in-line. (moving this to a local file and importing that does not work!)
248
+ // This is the source code of https://github.com/chartjs/chartjs-adapter-date-fns/blob/master/src/index.js
249
+
250
+ import {_adapters} from 'chart.js';
251
+
252
+ import {
253
+ parse, parseISO, toDate, isValid, format,
254
+ startOfSecond, startOfMinute, startOfHour, startOfDay,
255
+ startOfWeek, startOfMonth, startOfQuarter, startOfYear,
256
+ addMilliseconds, addSeconds, addMinutes, addHours,
257
+ addDays, addWeeks, addMonths, addQuarters, addYears,
258
+ differenceInMilliseconds, differenceInSeconds, differenceInMinutes,
259
+ differenceInHours, differenceInDays, differenceInWeeks,
260
+ differenceInMonths, differenceInQuarters, differenceInYears,
261
+ endOfSecond, endOfMinute, endOfHour, endOfDay,
262
+ endOfWeek, endOfMonth, endOfQuarter, endOfYear
263
+ } from 'date-fns';
264
+
265
+ const FORMATS = {
266
+ datetime: 'MMM d, yyyy, h:mm:ss aaaa',
267
+ millisecond: 'h:mm:ss.SSS aaaa',
268
+ second: 'h:mm:ss aaaa',
269
+ minute: 'h:mm aaaa',
270
+ hour: 'ha',
271
+ day: 'MMM d',
272
+ week: 'PP',
273
+ month: 'MMM yyyy',
274
+ quarter: 'qqq - yyyy',
275
+ year: 'yyyy'
276
+ };
277
+
278
+ _adapters._date.override({
279
+ _id: 'date-fns', // DEBUG
280
+ formats: function() {
281
+ return FORMATS;
282
+ },
283
+
284
+ parse: function(value, fmt) {
285
+ if (value === null || typeof value === 'undefined') {
286
+ return null;
287
+ }
288
+ const type = typeof value;
289
+ if (type === 'number' || value instanceof Date) {
290
+ // @ts-ignore
291
+ value = toDate(value);
292
+ } else if (type === 'string') {
293
+ if (typeof fmt === 'string') {
294
+ // @ts-ignore
295
+ value = parse(value, fmt, new Date(), this.options);
296
+ } else {
297
+ // @ts-ignore
298
+ value = parseISO(value, this.options);
299
+ }
300
+ }
301
+ // @ts-ignore
302
+ return isValid(value) ? value.getTime() : null;
303
+ },
304
+
305
+ format: function(time, fmt) {
306
+ return format(time, fmt, this.options);
307
+ },
308
+
309
+ // @ts-ignore
310
+ add: function(time, amount, unit) {
311
+ switch (unit) {
312
+ case 'millisecond': return addMilliseconds(time, amount);
313
+ case 'second': return addSeconds(time, amount);
314
+ case 'minute': return addMinutes(time, amount);
315
+ case 'hour': return addHours(time, amount);
316
+ case 'day': return addDays(time, amount);
317
+ case 'week': return addWeeks(time, amount);
318
+ case 'month': return addMonths(time, amount);
319
+ case 'quarter': return addQuarters(time, amount);
320
+ case 'year': return addYears(time, amount);
321
+ default: return time;
322
+ }
323
+ },
324
+
325
+ diff: function(max, min, unit) {
326
+ switch (unit) {
327
+ case 'millisecond': return differenceInMilliseconds(max, min);
328
+ case 'second': return differenceInSeconds(max, min);
329
+ case 'minute': return differenceInMinutes(max, min);
330
+ case 'hour': return differenceInHours(max, min);
331
+ case 'day': return differenceInDays(max, min);
332
+ case 'week': return differenceInWeeks(max, min);
333
+ case 'month': return differenceInMonths(max, min);
334
+ case 'quarter': return differenceInQuarters(max, min);
335
+ case 'year': return differenceInYears(max, min);
336
+ default: return 0;
337
+ }
338
+ },
339
+
340
+ // @ts-ignore
341
+ startOf: function(time, unit, weekday) {
342
+ switch (unit) {
343
+ case 'second': return startOfSecond(time);
344
+ case 'minute': return startOfMinute(time);
345
+ case 'hour': return startOfHour(time);
346
+ case 'day': return startOfDay(time);
347
+ case 'week': return startOfWeek(time);
348
+ // @ts-ignore
349
+ case 'isoWeek': return startOfWeek(time, {weekStartsOn: +weekday});
350
+ case 'month': return startOfMonth(time);
351
+ case 'quarter': return startOfQuarter(time);
352
+ case 'year': return startOfYear(time);
353
+ default: return time;
354
+ }
355
+ },
356
+
357
+ // @ts-ignore
358
+ endOf: function(time, unit) {
359
+ switch (unit) {
360
+ case 'second': return endOfSecond(time);
361
+ case 'minute': return endOfMinute(time);
362
+ case 'hour': return endOfHour(time);
363
+ case 'day': return endOfDay(time);
364
+ case 'week': return endOfWeek(time);
365
+ case 'month': return endOfMonth(time);
366
+ case 'quarter': return endOfQuarter(time);
367
+ case 'year': return endOfYear(time);
368
+ default: return time;
369
+ }
370
+ }
371
+ });