@eox/chart 2.0.0-alpha1

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,282 @@
1
+ import Chart, {
2
+ ChartDataset /*, LinearScale, CategoryScale */,
3
+ ChartOptions,
4
+ } from "chart.js/auto";
5
+ import pRetry, { AbortError } from "p-retry";
6
+ import { DateTime } from "luxon";
7
+ /*
8
+ import {
9
+ LineWithErrorBarsController,
10
+ LineWithErrorBarsChart,
11
+ ScatterWithErrorBarsChart,
12
+ ScatterWithErrorBarsController,
13
+ PointWithErrorBar,
14
+ } from "chartjs-chart-error-bars";
15
+
16
+ Chart.register(
17
+ LineWithErrorBarsController,
18
+ LineWithErrorBarsChart,
19
+ PointWithErrorBar,
20
+ ScatterWithErrorBarsChart,
21
+ ScatterWithErrorBarsController,
22
+ LinearScale,
23
+ CategoryScale
24
+ );*/
25
+
26
+ type status = "ready" | "loading" | "error";
27
+ interface DSDict {
28
+ [key: number]: {
29
+ [key: string]: {
30
+ status: string;
31
+ data?: {
32
+ [key: string]: {
33
+ date: string;
34
+ basicStats: { mean: number; min: number; max: number };
35
+ }[];
36
+ };
37
+ request: Promise<void>;
38
+ };
39
+ };
40
+ }
41
+
42
+ export interface SDMOptions {
43
+ source: string;
44
+ endpoint: string;
45
+ features: string[][];
46
+ geometry: object;
47
+ timeInterval: object;
48
+ startTime?: string;
49
+ endTime?: string;
50
+ }
51
+
52
+ class SignalsDataManager {
53
+ chart: Chart;
54
+ startTime: DateTime;
55
+ endTime: DateTime;
56
+ options: SDMOptions;
57
+ chartOptions: ChartOptions;
58
+ dataStorage: DSDict;
59
+ status: status;
60
+ activeFields: string[];
61
+
62
+ constructor(chart: Chart, options: SDMOptions) {
63
+ this.chart = chart;
64
+ this.options = options;
65
+ this.startTime = DateTime.now().minus(options.timeInterval);
66
+ this.endTime = DateTime.now();
67
+ if (options.startTime && options.endTime) {
68
+ // Overwrite values if provided
69
+ this.startTime = DateTime.fromISO(options.startTime).setZone("UTC");
70
+ this.endTime = DateTime.fromISO(options.endTime).setZone("UTC");
71
+ }
72
+ this.dataStorage = {};
73
+ // Initialize data storage
74
+ this.options.features.forEach((_, idx) => (this.dataStorage[idx] = {}));
75
+ this.status = "ready";
76
+ this.chartOptions = {
77
+ scales: {
78
+ x: {
79
+ type: "time",
80
+ min: this.startTime.toISODate(),
81
+ max: this.endTime.toISODate(),
82
+ ticks: {
83
+ minRotation: 0,
84
+ maxRotation: 0,
85
+ },
86
+ },
87
+ /*y: {
88
+ min: 0,
89
+ max: 0.5,
90
+ },*/
91
+ },
92
+ plugins: {
93
+ legend: {
94
+ position: "right",
95
+ onClick: (_, legendItem) => {
96
+ if (!legendItem.hidden) {
97
+ const idx = this.activeFields.indexOf(legendItem.text);
98
+ const keys = this.activeFields;
99
+ keys.splice(idx, 1);
100
+ this.setActiveFields(keys);
101
+ } else {
102
+ this.setActiveFields([...this.activeFields, legendItem.text]);
103
+ }
104
+ },
105
+ },
106
+ },
107
+ };
108
+ }
109
+
110
+ private fetchSignals(groupIndex: number, start?: DateTime, end?: DateTime) {
111
+ const features = this.options.features[groupIndex]
112
+ .map((f) => `feature=${f}`)
113
+ .join("&");
114
+ const times = `${start ? "&start_date=" + start.toISODate() : ""}${
115
+ end ? "&end_date=" + end.toISODate() : ""
116
+ }`;
117
+ const request = `${this.options.endpoint}?source=${this.options.source}&${features}${times}`;
118
+ const geom = this.options.geometry;
119
+
120
+ async function fetchSignals() {
121
+ const response = await fetch(request, {
122
+ headers: { "Content-Type": "application/json; charset=utf-8" },
123
+ method: "POST",
124
+ mode: "cors",
125
+ body: JSON.stringify({
126
+ geometry: geom,
127
+ }),
128
+ });
129
+ // Abort retrying if the resource doesn't exist
130
+ if (response.status === 404) {
131
+ throw new AbortError(response.statusText);
132
+ }
133
+ if (response.status !== 200) {
134
+ throw Error(response.statusText);
135
+ }
136
+ return response;
137
+ }
138
+ return pRetry(fetchSignals, {
139
+ onFailedAttempt: (error) => {
140
+ console.log(
141
+ `Attempt ${error.attemptNumber} failed. There are ${error.retriesLeft} retries left.`
142
+ );
143
+ },
144
+ retries: 5,
145
+ }).then(function (res) {
146
+ return res.json();
147
+ });
148
+ }
149
+
150
+ private updateChart() {
151
+ this.chart.options = this.chartOptions;
152
+ const datasets: ChartDataset[] = [];
153
+ this.options.features.flat().forEach((key) => {
154
+ // Find group
155
+ let groupIndex: number = -1;
156
+ this.options.features.forEach((group, idx) => {
157
+ if (group.includes(key)) {
158
+ groupIndex = idx;
159
+ }
160
+ });
161
+ if (groupIndex !== -1) {
162
+ let data: {
163
+ date: string;
164
+ basicStats?: { mean: number; min: number; max: number };
165
+ }[] = [];
166
+ Object.keys(this.dataStorage[groupIndex]).forEach((timekey) => {
167
+ const dsEntry = this.dataStorage[groupIndex][timekey];
168
+ if (dsEntry.status === "finished") {
169
+ if (
170
+ Object.keys(dsEntry.data).length !== 0 &&
171
+ Object.keys(dsEntry.data).includes(key)
172
+ ) {
173
+ data.push(...dsEntry.data[key]);
174
+ }
175
+ } else {
176
+ data.push({ date: "missing" });
177
+ }
178
+ });
179
+ datasets.push({
180
+ // type: "lineWithErrorBars",
181
+ type: "line",
182
+ 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
+ }),
196
+ hidden: !this.activeFields.includes(key),
197
+ });
198
+ }
199
+ });
200
+
201
+ this.chart.data = {
202
+ datasets,
203
+ };
204
+ this.chart.update("none");
205
+ }
206
+
207
+ private retrieveMissingData() {
208
+ // Review current time span and see if data needs to be fetched
209
+
210
+ // First identify signal groups
211
+ const signalGroupIndices: number[] = [];
212
+ this.activeFields.forEach((af) => {
213
+ this.options.features.forEach((group, index) => {
214
+ if (group.includes(af) && !signalGroupIndices.includes(index)) {
215
+ signalGroupIndices.push(index);
216
+ }
217
+ });
218
+ });
219
+
220
+ // Check if dataStorage has relevant data
221
+ // We use monthly steps for data retrieval
222
+ let currDate = DateTime.fromObject({
223
+ year: this.endTime.year,
224
+ month: this.endTime.month,
225
+ })
226
+ .plus({ month: 1 })
227
+ .minus({ second: 1 });
228
+ const start = DateTime.fromObject({
229
+ year: this.startTime.year,
230
+ month: this.startTime.month,
231
+ })
232
+ .plus({ month: 1 })
233
+ .minus({ second: 1 });
234
+ while (currDate > start) {
235
+ const timeslot = currDate.toFormat("yyyyMM");
236
+ signalGroupIndices.forEach((index) => {
237
+ if (!(timeslot in this.dataStorage[index])) {
238
+ // request data
239
+ const request = this.fetchSignals(
240
+ index,
241
+ DateTime.fromObject({ year: currDate.year, month: currDate.month }),
242
+ DateTime.fromObject({
243
+ year: currDate.year,
244
+ month: currDate.month,
245
+ })
246
+ .plus({ month: 1 })
247
+ .minus({ second: 1 })
248
+ ).then((data) => {
249
+ this.dataStorage[index][timeslot].data = data;
250
+ this.dataStorage[index][timeslot].status = "finished";
251
+ this.updateChart();
252
+ });
253
+ this.dataStorage[index][timeslot] = {
254
+ request,
255
+ status: "fetching",
256
+ };
257
+ }
258
+ });
259
+ currDate = currDate.minus({ months: 1 });
260
+ }
261
+ }
262
+
263
+ setActiveFields(activeFields: string[]) {
264
+ this.activeFields = activeFields;
265
+ this.retrieveMissingData();
266
+ this.updateChart();
267
+ }
268
+
269
+ setTimeInterval(start: DateTime, end: DateTime) {
270
+ this.startTime = start;
271
+ this.endTime = end;
272
+ this.chartOptions.scales.x.min = start.toISODate();
273
+ this.chartOptions.scales.x.max = end.toISODate();
274
+ this.retrieveMissingData();
275
+ this.updateChart();
276
+ }
277
+ /*
278
+ setAggregation(aggregation: string) {}
279
+ */
280
+ }
281
+
282
+ export default SignalsDataManager;
@@ -0,0 +1 @@
1
+ /// <reference types="vite/client" />
package/test.html ADDED
@@ -0,0 +1,23 @@
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8" />
5
+ <title>Simple Chart</title>
6
+ <style>
7
+ html,
8
+ body {
9
+ margin: 0;
10
+ padding: 0;
11
+ }
12
+ html,
13
+ body,
14
+ .chart {
15
+ width: 100%;
16
+ height: 100%;
17
+ }
18
+ </style>
19
+ </head>
20
+ <body>
21
+ <canvas id="chart" class="chart" data-cy="chart"></canvas>
22
+ </body>
23
+ </html>
package/tsconfig.json ADDED
@@ -0,0 +1,21 @@
1
+ {
2
+ "compilerOptions": {
3
+ "strictNullChecks": false,
4
+ "target": "ESNext",
5
+ "useDefineForClassFields": true,
6
+ "module": "ESNext",
7
+ "lib": ["ESNext", "DOM"],
8
+ "moduleResolution": "Node",
9
+ "strict": true,
10
+ "resolveJsonModule": true,
11
+ "esModuleInterop": true,
12
+ "noEmit": true,
13
+ "noUnusedLocals": true,
14
+ "noUnusedParameters": true,
15
+ "noImplicitReturns": true,
16
+ "skipLibCheck": true,
17
+ "typeRoots": ["./typings"],
18
+ "types": ["cypress"]
19
+ },
20
+ "include": ["**/*.ts"]
21
+ }
@@ -0,0 +1,9 @@
1
+ import Chart from "chart.js/auto";
2
+
3
+ declare global {
4
+ interface Window {
5
+ chart: Chart;
6
+ }
7
+ }
8
+
9
+ export {};
@@ -0,0 +1,19 @@
1
+ import { defineConfig } from "vite";
2
+ import { resolve } from "path";
3
+
4
+ // https://vitejs.dev/config/
5
+ export default defineConfig({
6
+ build: {
7
+ emptyOutDir: false,
8
+ lib: {
9
+ entry: resolve(__dirname, "src/interface.ts"),
10
+ name: "Interface",
11
+ fileName: "interface",
12
+ },
13
+ rollupOptions: {
14
+ output: {
15
+ dir: "public",
16
+ },
17
+ },
18
+ },
19
+ });
@@ -0,0 +1,15 @@
1
+ import { defineConfig } from "vite";
2
+ import { resolve } from "path";
3
+
4
+ // https://vitejs.dev/config/
5
+ export default defineConfig({
6
+ base: "./",
7
+ build: {
8
+ // emptyOutDir: false,
9
+ rollupOptions: {
10
+ input: {
11
+ main: resolve(__dirname, "index.html"),
12
+ },
13
+ },
14
+ },
15
+ });