@eox/chart 2.0.0-alpha1 → 2.0.0-alpha11

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.
@@ -1,10 +1,12 @@
1
1
  import Chart, {
2
- ChartDataset /*, LinearScale, CategoryScale */,
2
+ ChartDataset,
3
+ LinearScale,
4
+ CategoryScale,
3
5
  ChartOptions,
4
6
  } from "chart.js/auto";
5
7
  import pRetry, { AbortError } from "p-retry";
6
8
  import { DateTime } from "luxon";
7
- /*
9
+
8
10
  import {
9
11
  LineWithErrorBarsController,
10
12
  LineWithErrorBarsChart,
@@ -21,7 +23,7 @@ Chart.register(
21
23
  ScatterWithErrorBarsController,
22
24
  LinearScale,
23
25
  CategoryScale
24
- );*/
26
+ );
25
27
 
26
28
  type status = "ready" | "loading" | "error";
27
29
  interface DSDict {
@@ -39,6 +41,11 @@ interface DSDict {
39
41
  };
40
42
  }
41
43
 
44
+ interface yAxisObject {
45
+ id: "string";
46
+ containedSignals: string[];
47
+ }
48
+
42
49
  export interface SDMOptions {
43
50
  source: string;
44
51
  endpoint: string;
@@ -47,17 +54,25 @@ export interface SDMOptions {
47
54
  timeInterval: object;
48
55
  startTime?: string;
49
56
  endTime?: string;
57
+ timeAggregation?: object;
58
+ retries?: number;
59
+ normalize?: boolean;
60
+ showMinMax?: boolean;
61
+ colors?: string[];
62
+ additionalYAxis?: yAxisObject[];
50
63
  }
51
64
 
52
65
  class SignalsDataManager {
53
66
  chart: Chart;
54
67
  startTime: DateTime;
55
68
  endTime: DateTime;
69
+ timeAggregation: object;
56
70
  options: SDMOptions;
57
71
  chartOptions: ChartOptions;
58
72
  dataStorage: DSDict;
59
73
  status: status;
60
74
  activeFields: string[];
75
+ additionalYAxis: yAxisObject[] | null;
61
76
 
62
77
  constructor(chart: Chart, options: SDMOptions) {
63
78
  this.chart = chart;
@@ -69,6 +84,19 @@ class SignalsDataManager {
69
84
  this.startTime = DateTime.fromISO(options.startTime).setZone("UTC");
70
85
  this.endTime = DateTime.fromISO(options.endTime).setZone("UTC");
71
86
  }
87
+ if (this.options.timeAggregation) {
88
+ this.timeAggregation = this.options.timeAggregation;
89
+ }
90
+ this.options.retries = this.options.retries ? this.options.retries : 5;
91
+ this.options.normalize = this.options.normalize
92
+ ? this.options.normalize
93
+ : false;
94
+ this.options.showMinMax = this.options.showMinMax
95
+ ? this.options.showMinMax
96
+ : false;
97
+ this.additionalYAxis = this.options.additionalYAxis
98
+ ? this.options.additionalYAxis
99
+ : null;
72
100
  this.dataStorage = {};
73
101
  // Initialize data storage
74
102
  this.options.features.forEach((_, idx) => (this.dataStorage[idx] = {}));
@@ -84,13 +112,20 @@ class SignalsDataManager {
84
112
  maxRotation: 0,
85
113
  },
86
114
  },
87
- /*y: {
88
- min: 0,
89
- max: 0.5,
90
- },*/
115
+ },
116
+ interaction: {
117
+ axis: "x",
118
+ mode: "nearest",
119
+ intersect: false,
91
120
  },
92
121
  plugins: {
93
122
  legend: {
123
+ labels: {
124
+ usePointStyle: true,
125
+ pointStyle: "rect",
126
+ padding: 5,
127
+ sort: (a, b) => a.text.localeCompare(b.text),
128
+ },
94
129
  position: "right",
95
130
  onClick: (_, legendItem) => {
96
131
  if (!legendItem.hidden) {
@@ -103,8 +138,44 @@ class SignalsDataManager {
103
138
  }
104
139
  },
105
140
  },
141
+ tooltip: {
142
+ callbacks: {
143
+ title: (tooltipItem) => {
144
+ const raw: any = tooltipItem[0]?.raw;
145
+ return raw.x.toISODate();
146
+ },
147
+ label: (tooltipItem) => {
148
+ const raw: any = tooltipItem.raw;
149
+ return `${tooltipItem.dataset.label}: ↔ ${raw.y.toPrecision(
150
+ 3
151
+ )}; ↓ ${raw.yMin.toPrecision(3)}, ↑ ${raw.yMax.toPrecision(3)}`;
152
+ },
153
+ },
154
+ },
106
155
  },
107
156
  };
157
+ // Adding possible additional y axis scales
158
+ for (let index = 0; index < this.additionalYAxis.length; index++) {
159
+ const scale = this.additionalYAxis[index];
160
+ this.chartOptions.scales[scale.id] = {
161
+ type: "linear",
162
+ position: "right",
163
+ };
164
+ }
165
+ }
166
+
167
+ private checkLoadingStatus() {
168
+ const spinner = document.getElementById("loadingIndicator");
169
+ let loading = false;
170
+ // TODO: Showing when error state happened
171
+ Object.keys(this.dataStorage).forEach((_, groupIdx) => {
172
+ Object.keys(this.dataStorage[groupIdx]).forEach((timeKey) => {
173
+ if (this.dataStorage[groupIdx][timeKey].status === "fetching") {
174
+ loading = true;
175
+ }
176
+ });
177
+ });
178
+ spinner.className = loading ? "loader" : "loader hidden";
108
179
  }
109
180
 
110
181
  private fetchSignals(groupIndex: number, start?: DateTime, end?: DateTime) {
@@ -141,16 +212,18 @@ class SignalsDataManager {
141
212
  `Attempt ${error.attemptNumber} failed. There are ${error.retriesLeft} retries left.`
142
213
  );
143
214
  },
144
- retries: 5,
215
+ retries: this.options.retries,
145
216
  }).then(function (res) {
146
217
  return res.json();
147
218
  });
219
+ this.checkLoadingStatus();
148
220
  }
149
221
 
150
222
  private updateChart() {
223
+ this.checkLoadingStatus();
151
224
  this.chart.options = this.chartOptions;
152
225
  const datasets: ChartDataset[] = [];
153
- this.options.features.flat().forEach((key) => {
226
+ this.options.features.flat().forEach((key, dsIndex) => {
154
227
  // Find group
155
228
  let groupIndex: number = -1;
156
229
  this.options.features.forEach((group, idx) => {
@@ -176,25 +249,149 @@ class SignalsDataManager {
176
249
  data.push({ date: "missing" });
177
250
  }
178
251
  });
179
- datasets.push({
180
- // type: "lineWithErrorBars",
252
+
253
+ let actualDataAdded = false;
254
+ let max = Number.MIN_VALUE;
255
+ let min = Number.MAX_VALUE;
256
+ let signalData = <any>data.map((datapoint) => {
257
+ let ds = {};
258
+ if (datapoint && datapoint.date !== "missing") {
259
+ const stats = datapoint.basicStats;
260
+ if (this.options.showMinMax) {
261
+ min = stats.min < min ? stats.min : min;
262
+ max = stats.max > max ? stats.max : max;
263
+ } else {
264
+ min = stats.mean < min ? stats.mean : min;
265
+ max = stats.mean > max ? stats.mean : max;
266
+ }
267
+ ds = {
268
+ x: DateTime.fromISO(datapoint.date).setZone("UTC"),
269
+ y: datapoint.basicStats.mean,
270
+ yMin: datapoint.basicStats.min,
271
+ yMax: datapoint.basicStats.max,
272
+ };
273
+ actualDataAdded = true;
274
+ }
275
+ return ds;
276
+ });
277
+ if (actualDataAdded && this.timeAggregation) {
278
+ // If we aggregate data we recalculate min max so we reset it
279
+ max = Number.MIN_VALUE;
280
+ min = Number.MAX_VALUE;
281
+ const aggrData = [];
282
+ let currDataIdx = 0;
283
+ let currDate = DateTime.fromObject({
284
+ year: this.startTime.year,
285
+ month: this.startTime.month,
286
+ day: this.startTime.day,
287
+ });
288
+ while (currDate < this.endTime) {
289
+ let dataSum = 0;
290
+ let minSum = 0;
291
+ let maxSum = 0;
292
+ while (
293
+ currDataIdx < signalData.length &&
294
+ (Object.keys(signalData[currDataIdx]).length === 0 ||
295
+ signalData[currDataIdx].x < currDate)
296
+ ) {
297
+ currDataIdx++;
298
+ }
299
+ const x1 = currDataIdx;
300
+ while (
301
+ currDataIdx < signalData.length &&
302
+ (Object.keys(signalData[currDataIdx]).length === 0 ||
303
+ signalData[currDataIdx].x < currDate.plus(this.timeAggregation))
304
+ ) {
305
+ const sd = signalData[currDataIdx];
306
+ dataSum += sd.y;
307
+ minSum += sd.yMin;
308
+ maxSum += sd.yMax;
309
+ currDataIdx++;
310
+ }
311
+ const x2 = currDataIdx;
312
+ const count = x2 - x1;
313
+ // If datapoints are within the interval we push the aggregation to the aggregated data
314
+ if (count > 0) {
315
+ const yMean = dataSum / count;
316
+ const yMinMean = minSum / count;
317
+ const yMaxMean = maxSum / count;
318
+ if (this.options.showMinMax) {
319
+ min = yMinMean < min ? yMinMean : min;
320
+ max = yMaxMean > max ? yMaxMean : max;
321
+ } else {
322
+ min = yMean < min ? yMean : min;
323
+ max = yMean > max ? yMean : max;
324
+ }
325
+ // TODO: can we save a time interval here?
326
+ aggrData.push({
327
+ x: currDate,
328
+ y: yMean,
329
+ yMin: yMinMean,
330
+ yMax: yMaxMean,
331
+ });
332
+ }
333
+ currDate = currDate.plus(this.timeAggregation);
334
+ }
335
+ signalData = aggrData;
336
+ }
337
+
338
+ if (actualDataAdded && this.options.normalize) {
339
+ signalData = signalData.map(
340
+ (dp: { x: DateTime; y: number; yMin: number; yMax: number }) => {
341
+ dp.y = (dp.y - min) / (max - min);
342
+ dp.yMin = (dp.yMin - min) / (max - min);
343
+ dp.yMax = (dp.yMax - min) / (max - min);
344
+ return dp;
345
+ }
346
+ );
347
+ }
348
+
349
+ let ds: ChartDataset = {
181
350
  type: "line",
182
351
  label: key,
183
- // casting to any because an array of object should also be possible
184
- data: <any>data.map((datapoint) => {
185
- let ds = {};
186
- if (datapoint && datapoint.date !== "missing") {
187
- ds = {
188
- x: DateTime.fromISO(datapoint.date).setZone("UTC"),
189
- y: datapoint.basicStats.mean,
190
- yMin: [datapoint.basicStats.min],
191
- yMax: [datapoint.basicStats.max],
192
- };
193
- }
194
- return ds;
195
- }),
352
+ data: signalData,
196
353
  hidden: !this.activeFields.includes(key),
197
- });
354
+ };
355
+ if (this.options.showMinMax) {
356
+ ds = {
357
+ type: "lineWithErrorBars",
358
+ label: key,
359
+ data: signalData,
360
+ hidden: !this.activeFields.includes(key),
361
+ errorBarWhiskerLineWidth: 2,
362
+ errorBarColor: "#00000000",
363
+ };
364
+ }
365
+ if (this.options.colors && this.options.colors.length >= dsIndex) {
366
+ const color = this.options.colors[dsIndex];
367
+ ds.backgroundColor = color;
368
+ ds.borderColor = color;
369
+
370
+ if (this.options.showMinMax) {
371
+ ds = {
372
+ type: "lineWithErrorBars",
373
+ label: key,
374
+ data: signalData,
375
+ hidden: !this.activeFields.includes(key),
376
+ errorBarWhiskerLineWidth: 2,
377
+ errorBarColor: "#00000000",
378
+ errorBarWhiskerColor: color,
379
+ errorBarWhiskerSize: 10,
380
+ backgroundColor: color,
381
+ borderColor: color,
382
+ };
383
+ }
384
+ }
385
+ // Check if additional y axis should be used
386
+ if (this.additionalYAxis !== null) {
387
+ for (let index = 0; index < this.additionalYAxis.length; index++) {
388
+ const axis = this.additionalYAxis[index];
389
+ if (axis.containedSignals.includes(key)) {
390
+ ds.yAxisID = axis.id;
391
+ }
392
+ }
393
+ }
394
+ datasets.push(ds);
198
395
  }
199
396
  });
200
397
 
@@ -245,11 +442,16 @@ class SignalsDataManager {
245
442
  })
246
443
  .plus({ month: 1 })
247
444
  .minus({ second: 1 })
248
- ).then((data) => {
249
- this.dataStorage[index][timeslot].data = data;
250
- this.dataStorage[index][timeslot].status = "finished";
251
- this.updateChart();
252
- });
445
+ )
446
+ .then((data) => {
447
+ this.dataStorage[index][timeslot].data = data;
448
+ this.dataStorage[index][timeslot].status = "finished";
449
+ this.updateChart();
450
+ })
451
+ .catch(() => {
452
+ this.dataStorage[index][timeslot].status = "failed";
453
+ this.updateChart();
454
+ });
253
455
  this.dataStorage[index][timeslot] = {
254
456
  request,
255
457
  status: "fetching",
@@ -260,6 +462,101 @@ class SignalsDataManager {
260
462
  }
261
463
  }
262
464
 
465
+ triggerCSVDownload() {
466
+ const completeData: {
467
+ date: string;
468
+ basicStats?: { mean: number; min: number; max: number };
469
+ }[][] = [];
470
+ const headers: string[] = [];
471
+ const allSignals = this.activeFields;
472
+ allSignals.forEach((key, signalIdx) => {
473
+ // Find group
474
+ let groupIndex: number = -1;
475
+ this.options.features.forEach((group, idx) => {
476
+ if (group.includes(key)) {
477
+ groupIndex = idx;
478
+ }
479
+ });
480
+ if (groupIndex !== -1) {
481
+ let data: {
482
+ date: string;
483
+ basicStats?: { mean: number; min: number; max: number };
484
+ }[] = [];
485
+ Object.keys(this.dataStorage[groupIndex]).forEach((timekey) => {
486
+ const dsEntry = this.dataStorage[groupIndex][timekey];
487
+ if (dsEntry.status === "finished") {
488
+ if (
489
+ Object.keys(dsEntry.data).length !== 0 &&
490
+ Object.keys(dsEntry.data).includes(key)
491
+ ) {
492
+ data.push(...dsEntry.data[key]);
493
+ }
494
+ }
495
+ });
496
+ if (data.length > 0) {
497
+ headers.push(allSignals[signalIdx]);
498
+ completeData.push(data);
499
+ }
500
+ }
501
+ });
502
+ // We need to try and bring the different timed datasets into "same timegrid" lets do some binning
503
+ const binnedData: {
504
+ [key: string]: {
505
+ [key: string]: {
506
+ mean: number;
507
+ max: number;
508
+ min: number;
509
+ };
510
+ };
511
+ } = {};
512
+ headers.forEach((datakey, idx) => {
513
+ completeData[idx].forEach((dp) => {
514
+ if (binnedData[dp.date]) {
515
+ binnedData[dp.date][datakey] = dp.basicStats;
516
+ } else {
517
+ binnedData[dp.date] = {};
518
+ binnedData[dp.date][datakey] = dp.basicStats;
519
+ }
520
+ });
521
+ });
522
+
523
+ // Now we try to construct the csv adding empty values when timestamp not available for a dataset
524
+ let csv = "time,";
525
+ const allHeaders = headers.map((val) => [val, `${val}_max`, `${val}_min`]);
526
+ csv += allHeaders.flat().join(",");
527
+ csv += "\n";
528
+ Object.keys(binnedData).forEach((dateKey) => {
529
+ const row: (string | number)[] = [dateKey];
530
+ headers.forEach((signalKey) => {
531
+ const stats = binnedData[dateKey][signalKey]
532
+ ? binnedData[dateKey][signalKey]
533
+ : null;
534
+ if (stats != null) {
535
+ row.push(...[stats.mean, stats.max, stats.min]);
536
+ } else {
537
+ row.push(...["", "", ""]);
538
+ }
539
+ });
540
+ csv += row.join(",");
541
+ csv += "\n";
542
+ });
543
+ var hiddenElement = document.createElement("a");
544
+ hiddenElement.href = "data:text/csv;charset=utf-8," + encodeURI(csv);
545
+ hiddenElement.target = "_blank";
546
+ hiddenElement.download = "chart_data.csv";
547
+ hiddenElement.click();
548
+ }
549
+
550
+ setGeometry(geometry: object) {
551
+ // Clear all currently saved data
552
+ this.dataStorage = {};
553
+ // Initialize data storage
554
+ this.options.features.forEach((_, idx) => (this.dataStorage[idx] = {}));
555
+ this.options.geometry = geometry;
556
+ this.retrieveMissingData();
557
+ this.updateChart();
558
+ }
559
+
263
560
  setActiveFields(activeFields: string[]) {
264
561
  this.activeFields = activeFields;
265
562
  this.retrieveMissingData();
@@ -274,6 +571,28 @@ class SignalsDataManager {
274
571
  this.retrieveMissingData();
275
572
  this.updateChart();
276
573
  }
574
+
575
+ setNormalize(normalize: boolean) {
576
+ this.options.normalize = normalize;
577
+ this.updateChart();
578
+ }
579
+
580
+ setShowMinMax(showMinMax: boolean) {
581
+ this.options.showMinMax = showMinMax;
582
+ this.updateChart();
583
+ }
584
+
585
+ setTimeAggregation(
586
+ aggregation: {
587
+ day?: number;
588
+ week?: number;
589
+ month?: number;
590
+ year?: number;
591
+ } | null
592
+ ) {
593
+ this.timeAggregation = aggregation;
594
+ this.updateChart();
595
+ }
277
596
  /*
278
597
  setAggregation(aggregation: string) {}
279
598
  */
package/.eslintignore DELETED
@@ -1,2 +0,0 @@
1
- dist
2
- public
package/.eslintrc.js DELETED
@@ -1,9 +0,0 @@
1
- module.exports = {
2
- env: {
3
- "cypress/globals": true,
4
- },
5
- extends: ["@eox", "plugin:@typescript-eslint/recommended"],
6
- parser: "@typescript-eslint/parser",
7
- plugins: ["cypress", "@typescript-eslint"],
8
- root: true,
9
- };
package/.prettierignore DELETED
@@ -1,2 +0,0 @@
1
- dist
2
- public
@@ -1,34 +0,0 @@
1
- import { createChart } from "../../src/interface";
2
-
3
- describe("general", () => {
4
- beforeEach(() => {
5
- cy.visit("../../public/test.html");
6
- });
7
- it("loads the chart", () => {
8
- cy.document().then((doc) => {
9
- const init = async () => {
10
- const chart = await createChart(doc.querySelector("#chart"));
11
- const data = {
12
- datasets: [
13
- {
14
- type: "bar",
15
- label: "Bar Dataset",
16
- data: [1, 2, 3, 4],
17
- },
18
- {
19
- type: "line",
20
- label: "Line Dataset",
21
- data: [6, 6, 6, 6],
22
- },
23
- ],
24
- labels: ["January", "February", "March", "April"],
25
- };
26
- chart?.setData(data);
27
- const test = await chart?.getFoo();
28
- console.log(test);
29
- };
30
- init();
31
- });
32
- cy.get('[data-cy="chart"] > iframe').should("exist");
33
- });
34
- });