@eox/chart 2.0.0-alpha1 → 2.0.0-alpha10

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