-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.html
1030 lines (934 loc) · 40.3 KB
/
index.html
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
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>JSONGrapher</title>
<script src="https://cdn.plot.ly/plotly-2.14.0.min.js"></script>
<!-- We use AJV for json validation. We use the 6.12.6 version because the later version had a compilation error. To reduce the external dependency, we have the source code on our github in he AJV folder, it is an under an MIT LICENSE, as noted in the LICENSE file of JSON Grapher.
<script src="https://cdnjs.cloudflare.com/ajax/libs/ajv/6.12.6/ajv.bundle.min.js" integrity="sha512-Xl0g/DHU98OkfXTsDfAAuTswzkniYQWPwLyGXzcpgDxCeH52eePfaHj/ictLAv2GvlPX2qZ6YV+3oDsw17L9qw==" crossorigin="anonymous" referrerpolicy="no-referrer"></script> -->
<script src="./AJV//6.12.6/ajv.bundle.min.js"></script>
<link rel="stylesheet" href="styles.css" />
<script src="./UUC/app/convert.js"></script>
<script src="./UUC/app/convert_parse.js"></script>
<script src="./UUC/app/convert_macro.js"></script>
<script src="./UUC/app/data.js"></script>
<style>
.file-actions {
display: flex;
gap: 8px;
}
.file-actions #downloadButtonsContainer {
display: flex;
gap: 4px;
}
</style>
</head>
<body>
<header>
<div class="container">
<a href="index.html">
<div class="button active">
<p>JSONGrapher</p>
</div>
</a>
<a href="Manual.pdf" target="_blank">
<div class="button">
<p>Manual</p>
</div>
</a>
<a href="https://github.com/AdityaSavara/JSONGrapher" target="_blank">
<div class="button">
<p>Source</p>
</div>
</a>
<a href="license.html">
<div class="button">
<p>License</p>
</div>
</a>
<a href="credits.html">
<div class="button">
<p>Credits</p>
</div>
</a>
</div>
</header>
<div class="page">
<h1>JSONGrapher</h1>
<p>
Upload data below for plotting -- use the browse button or the
drag-and-drop box. <br />
Then, upload even more data! It will be plotted on the same graph!
</p>
<p>
<a
href="https://www.dropbox.com/s/1s8ib1rsv3xmj1c/3_edited.mp4?dl=0"
target="_blank"
>Demonstration Video</a
>
|
<a
href=" https://github.com/AdityaSavara/JSONGrapherExamples/raw/main/DemonstrationFiles.zip"
target="_blank"
>Demonstration Files</a
>
(First unzip, then plot with JSON Grapher) |
<a
href="https://github.com/AdityaSavara/JSONGrapherExamples/raw/main/ExampleDataRecords.zip"
target="_blank"
>Additional Examples</a
>
</p>
<div class="file-actions">
<input type="file" id="file-selector" />
<button id="reset" onclick="clearData()">Clear Data</button>
<button id="download" style="display: none">
Download Last Data Set as a JSON File
</button>
<div id="downloadButtonsContainer"></div>
</div>
<p></p>
<div id="file-drop-area">
Drop a file here:
<pre></pre>
</div>
<div id="plotlyDiv">
<!-- Plotly chart will be drawn inside this DIV -->
</div>
<div id="errorDiv"></div>
<div id="downloadLink"></div>
<div id="conceptDiv">
<!-- The concept image will be shown in this div. -->
<pre></pre>
<center><img src="ConceptImage.png" width="600" /></center>
</div>
</div>
<script>
//JSONGrapher has the following steps, which will be commented in the MAIN BLOCK OF CODE of JSONGrapher:
// STEP 0: Prepare the 'universal' schemas
// STEP 1: User selects a file from computer or drops a file on the browser
// STEP 2: If the file is a .csv or .tsv file it is converted to a .json file
// STEP 3: Check if the jsonified object is a valid JSON file against the schema
// STEP 4: Check if the object has a dataSet that has a simulate key in it, and runs the simulate function
// STEP 5: Check if the units in the dataset are the same as the units in the previous object and convert them
// STEP 6: Provide file with converted units for download as JSON and CSV by buttons
// STEP 7: The plotly template is rendered on the browser
// Global Variables
let globalData = null;
let plotlyTemplate = null;
let schema = null;
let recentFileName = null;
let schemaURL = "";
let schemaTemplateURL = "";
// Initializing the AJV validator
const ajv = new Ajv();
const errorDiv = document.getElementById("errorDiv");
// Initiating the UUC converter
const convert = new Convert();
// A function that clears the data from global variables and removes the error text and plotly chart
function clearData() {
globalData = null;
document.getElementById("errorDiv").innerHTML = "";
document.getElementById("downloadButtonsContainer").innerHTML = "";
document.getElementById("file-selector").value = "";
document.getElementById("download").style.display = "none";
Plotly.purge("plotlyDiv");
}
// A function that checks if the uploaded file extension
function findFileType(fileName) {
let arrayName = fileName.split(".");
if (arrayName.includes("csv")) {
return "csv";
}
if (arrayName.includes("tsv")) {
return "tsv";
}
return "json";
}
// A function the jsonifies a tsv file
function jsonifyTSV(fileContent) {
//separate rows
let arr = fileContent.split("\n");
//if last row is empty remove it
if (arr[arr.length - 1].length < 2) {
arr = arr.slice(0, arr.length - 1);
}
//count number of columns
let number_of_columns = arr[0].split("\t").length;
//extract the config information
let comments = arr[0].split("\t")[0].split(":")[1].trim();
let data_type = arr[1].split("\t")[0].split(":")[1].trim();
let chart_label = arr[2].split("\t")[0].split(":")[1].trim();
let x_label = arr[3].split("\t")[0].split(":")[1].trim();
let y_label = arr[4].split("\t")[0].split(":")[1].trim();
custom = arr[5]; //This field is for custom json objects and is currently ignored.
//extract the series names
let series_names_array = arr[6]
.split(":")[1]
.split('"')[0]
.split("\t")
.splice(0, number_of_columns - 1)
.map((n) => n.trim());
//ignore arr[7] which is custom_variables:
//extract the data
let data = arr
.slice(8)
.map((r) => r.split("\t").map((str) => Number(str)));
let resultJSON = JSON.parse(JSON.stringify(plotlyTemplate, null, 2)); // clone of the template. The ", null, 2" is optional to make the json more human readable.
resultJSON.comments = comments;
resultJSON.title = data_type;
resultJSON.layout.title = chart_label;
resultJSON.layout.xaxis.title = x_label;
resultJSON.layout.yaxis.title = y_label;
let newData = [];
series_names_array.forEach((series_name, index) => {
let dataClone = JSON.parse(
JSON.stringify(plotlyTemplate.data[0], null, 2)
); // the ", null, 2" is optional to make the json more human readable.
dataClone.name = series_name;
dataClone.x = data.map((r) => r[0]);
dataClone.y = data.map((r) => r[index + 1]);
dataClone.uid = dataClone.uid + String(index);
newData.push(dataClone);
});
resultJSON.data = newData;
return resultJSON;
}
// A function the jsonifies a csv file
function jsonifyCSV(fileContent) {
//separate rows
let arr = fileContent.split("\n");
//if last row is empty remove it
if (arr[arr.length - 1].length < 2) {
arr = arr.slice(0, arr.length - 1);
}
//count number of columns
let number_of_columns = arr[5].split(",").length;
//extract the config information
let comments = arr[0].split(",")[0].split(":")[1].trim();
let data_type = arr[1].split(",")[0].split(":")[1].trim();
let chart_label = arr[2].split(",")[0].split(":")[1].trim();
let x_label = arr[3].split(",")[0].split(":")[1].trim();
let y_label = arr[4].split(",")[0].split(":")[1].trim();
//extract the series names
let series_names_array = arr[5]
.split(":")[1]
.split('"')[0]
.split(",")
.map((n) => n.trim());
//extract the data
let data = arr
.slice(7)
.map((r) => r.split(",").map((str) => Number(str)));
let resultJSON = JSON.parse(JSON.stringify(plotlyTemplate, null, 2)); // clone of the template. The "null, 2" are optional arguments that increase human readability.
resultJSON.comments = comments;
resultJSON.title = data_type;
resultJSON.layout.title = chart_label;
resultJSON.layout.xaxis.title = x_label;
resultJSON.layout.yaxis.title = y_label;
//Remove any series where the series name is blank.
function isNotBlank(value) {
return value != "";
}
series_names_array = series_names_array.filter(isNotBlank);
//We make a data set for each series_name, this way the blank series_name that have been removed will not be included.
let newData = [];
series_names_array.forEach((series_name, index) => {
let dataClone = JSON.parse(
JSON.stringify(plotlyTemplate.data[0]),
null,
2
); // the ", null, 2" are optional arguments to increase human readability.
dataClone.name = series_name;
dataClone.x = data.map((r) => r[0]);
dataClone.y = data.map((r) => r[index + 1]);
dataClone.uid = dataClone.uid + String(index);
newData.push(dataClone);
});
resultJSON.data = newData;
return resultJSON;
}
// Gets the name of the uploaded file
function getFileName(fileName) {
let arrayName = fileName.split(".");
return arrayName[0];
}
// A function checks the extension of the file and calls the appropriate function to jsonfiy the file
function jsonifyData(filetype, dataLoaded) {
switch (filetype) {
case "csv": {
return jsonifyCSV(dataLoaded);
}
case "tsv": {
return jsonifyTSV(dataLoaded);
}
default: {
return JSON.parse(dataLoaded);
}
}
}
function isValidUrl(urlString) {
var urlPattern = new RegExp(
"^(https?:\\/\\/)?" + // validate protocol
"((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|" + // validate domain name
"((\\d{1,3}\\.){3}\\d{1,3}))" + // validate OR ip (v4) address
"(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*" + // validate port and path
"(\\?[;&a-z\\d%_.~+=-]*)?" + // validate query string
"(\\#[-a-z\\d_]*)?$",
"i"
); // validate fragment locator
return !!urlPattern.test(urlString);
}
// function to extract from the title the location of the schema
function getSchemaLocation(jsonified, template = false) {
if (isValidUrl(jsonified.title)) {
const template_suffix = jsonified.title.replace(
".schema.json",
".schema.template.json"
);
return !template ? jsonified.title : template_suffix;
} else if (jsonified.title.endsWith("schema.json")) {
if (template) {
const template_suffix = jsonified.title.replace(
".schema.json",
".schema.template.json"
);
return "./schema/" + template_suffix;
} else {
return "./schema/" + jsonified.title;
}
} else {
if (template) {
return "./schema/" + jsonified.title + ".schema.template.json";
} else {
return "./schema/" + jsonified.title + ".schema.json";
}
}
}
// function to extract from the title the json schema
async function getSchemaType(jsonified) {
let schema2body;
schema_location = getSchemaLocation(jsonified);
const schema_template_location = getSchemaLocation(jsonified, true);
try {
const schema1 = await fetch(schema_location);
const schema2 = await fetch(schema_template_location);
const schema1body = await schema1.text();
if (schema2.status == 404) {
schema2body = "{}";
} else {
schema2body = await schema2.text();
}
const schema1json = JSON.parse(schema1body);
const schema2json = JSON.parse(schema2body);
return [schema1json, schema2json];
} catch (err) {
// TODO: !! error catching to be made informative.
//console.log("in getSchemaType error:");
//errorDiv.innerText += "undocumented error in getSchemaType\n";
try {
const schema1 = await fetch("./schema/0_PlotlyTemplate.json");
const schema1body = await schema1.text();
const schema1json = JSON.parse(schema1body);
return [schema1json, {}];
} catch (err2) {
return [{}, {}];
}
return [{}, {}];
}
}
// A function that prepares the plotly schema and the template for the jsonification
async function prepareUniversalSchemas() {
const schema1 = await fetch("./schema/plot-schema.json");
const schema1body = await schema1.text();
const schema1json = JSON.parse(schema1body);
const schema2 = await fetch("./schema/0_PlotlyTemplate.json");
const schema2body = await schema2.text();
const schema2json = await JSON.parse(schema2body);
return [schema1json, schema2json];
}
// A function that gets the unit from the label with regex
function getUnitFromLabel(label) {
let unit = label.match(/\((.*)\)/);
if (unit) {
return unit[1];
}
return "";
}
// A function that removes the unit from the label
function removeUnitFromLabel(label) {
const unit = getUnitFromLabel(label);
return label.replace(unit, "").replace("()", "");
}
// Checking if the dataSet has simulation
function checkSimulate(dataSet) {
if (dataSet.simulate) {
return true;
}
return false;
}
// Get raw content of github file from url
async function getRawContent(url) {
return new Promise(async (resolve, reject) => {
try {
const res = await fetch(url);
const data = await res.text();
resolve(data);
} catch (err) {
reject(err);
}
});
}
// Changes the Github link to a CDN link to avoid CORB issues
// TODO: currently we only support javascript from github. In the future, cross-domain / cross-origin simulate functions will be supported by SRI hash. https://www.w3schools.com/Tags/att_script_crossorigin.asp https://www.w3schools.com/Tags/att_script_integrity.asp with the SRI hash provided within the simulate object by a field in the JSON record named "SRI" or 'integrity"
function parseUrl(url) {
const urlArr = url.split("/");
if (urlArr[2] === "github.com") {
return url
.replace("github.com", "raw.githubusercontent.com")
.replace("/blob/", "/")
.replace("/tree/", "/")
.replace("www.", "");
} else {
return url;
}
}
// a function that gets the simulate script from an external file by url
function getAndRunSimulateScript(dataSet, jsonified, index) {
return new Promise(async (resolve, reject) => {
try {
loadScript = document.createElement("script");
const data = await getRawContent(parseUrl(dataSet.simulate.model));
loadScript.append(data);
document.getElementsByTagName("head")[0].appendChild(loadScript);
// Once the script is loaded in the <script> tag, we can run it
const simulatedData = Simulate(dataSet);
resolve(simulatedData);
} catch (err) {
reject({ status: "error", error: "Error: " + err });
}
});
}
// Check the units of the simulated data compared to the json record layout field and convert them if needed
function maybeConvertSimulatedDataUnits(jsonified, simulatedData, index) {
return new Promise((resolve, reject) => {
try {
// Javascript doesn't have deep clones so we use the JSON solution
// source: https://stackoverflow.com/questions/597588/how-do-you-clone-an-array-of-objects-in-javascript
let _simulatedData = JSON.parse(JSON.stringify(simulatedData));
const desiredXUnit = getUnitFromLabel(jsonified.layout.xaxis.title);
const desiredYUnit = getUnitFromLabel(jsonified.layout.yaxis.title);
const simulatedXUnit = getUnitFromLabel(simulatedData.data.x_label);
const simulatedYUnit = getUnitFromLabel(simulatedData.data.y_label);
if (desiredXUnit !== simulatedXUnit) {
const xConvertFactor = convert.fullConversion(
simulatedXUnit,
desiredXUnit
);
const convertedXArray = _simulatedData.data.x.map((x) => {
if (xConvertFactor.status == 0) {
return parseFloat(x) * xConvertFactor.output.num;
} else {
xConvertFactor.messages.forEach((message) => {
errorDiv.innerText += message.message + "\n";
});
}
});
_simulatedData.data.x = convertedXArray;
_simulatedData.data.x_label =
removeUnitFromLabel(_simulatedData.data.x_label) +
"(" +
desiredXUnit +
")";
}
if (desiredYUnit !== simulatedYUnit) {
const yConvertFactor = convert.fullConversion(
simulatedYUnit,
desiredYUnit
);
const convertedYArray = _simulatedData.data.y.map((y) => {
if (yConvertFactor.status == 0) {
return parseFloat(y) * yConvertFactor.output.num;
} else {
yConvertFactor.messages.forEach((message) => {
errorDiv.innerText += message.message + "\n";
});
}
});
_simulatedData.data.y = convertedYArray;
_simulatedData.data.y_label =
removeUnitFromLabel(_simulatedData.data.y_label) +
"(" +
desiredYUnit +
")";
}
resolve(_simulatedData);
} catch (err) {
reject({ status: "error", error: "Error: " + err });
}
});
}
// Gets the simulation data and adds it to the jsonified object
function mergeSimulationData(simulationResult, jsonified, index) {
return new Promise((resolve, reject) => {
try {
jsonified.layout.xaxis.title = simulationResult.data.x_label;
jsonified.layout.yaxis.title = simulationResult.data.y_label;
jsonified.data[index].x = simulationResult.data.x;
jsonified.data[index].y = simulationResult.data.y;
resolve(jsonified);
} catch (err) {
reject({ status: "error", error: "Error: " + err });
}
});
}
// A function that visualizes the data with plotly
function visualizeData(globalData) {
let copyForPlotly = JSON.parse(JSON.stringify(globalData)); // Plotly mutates the input !!!
Plotly.newPlot("plotlyDiv", copyForPlotly.data, copyForPlotly.layout);
}
// A function that will create a csv string from the jsonified data
// Returns Error: "The CSV could not be created: currently the CSV export only supports creating CSV files for XYYY data and not for cases that require XYXY."
function createCSV(jsonified) {
// Defining the variables
let csv = "";
let bulkValues = "";
let errors = false;
const csvHeadersArray = [];
const csvValuesArray = [];
const xLabel = jsonified.layout.xaxis.title;
const yLabel = jsonified.layout.yaxis.title;
const comments = jsonified.comments;
const dataType = jsonified.title;
const chartLabel = jsonified.layout.title;
const dataSets = jsonified.data;
const dataSetIndex = jsonified.data.length - 1;
const dataSet = jsonified.data[dataSetIndex];
let seriesName = "";
// Adding the name of each dataset separated by comma
dataSets.forEach((dataSet) => {
const last =
dataSets.indexOf(dataSet) === dataSets.length - 1 ? true : false;
const suffix = !last ? "," : "";
seriesName += dataSet.name + suffix;
});
// Concatenating the values into the string
csv += "comments: " + comments + "\r\n";
csv += "DataType: " + dataType + "\r\n";
csv += "Chart_label: " + chartLabel + "\r\n";
csv += "x_label: " + xLabel + "\r\n";
csv += "y_label: " + yLabel + "\r\n";
csv += "series_names: " + seriesName + "\r\n";
csv += "x_values";
// Iterating through the data sets and adding the x and y headers to the csv string and checking if all x arrays are equal
dataSets.forEach((dataSet, index) => {
const idx = `_${index + 1}`;
const suffix = index === dataSets.length - 1 ? "\r\n" : "";
csv += ",y" + idx + suffix;
});
dataSets[0].x.forEach((x, _index) => {
let extraYValues = "";
for (let i = 0; i < dataSets.length; i++) {
extraYValues += "," + dataSets[i].y[_index];
}
csv += x + extraYValues + "\r\n";
});
for (const dataSet of dataSets) {
const first_X_array = dataSets[0].x;
// Checking if all the x arrays are equal
if (dataSet.x.toString() !== first_X_array.toString()) {
errors = true;
csv =
"Error: The CSV could not be created: currently the CSV export only supports creating CSV files for XYYY data and not for cases that require XYXY.";
}
}
return {
csv: csv,
filename: chartLabel + ".csv",
};
}
// A function that will create a download link for the csv file
function createDownloadCSVLink(csv, filename) {
let csvFile;
let downloadLink;
// CSV file
csvFile = new Blob([csv], { type: "text/csv" });
// Download link
downloadLink = document.createElement("a");
// File name
downloadLink.download = filename;
// Create a link to the file
downloadLink.href = window.URL.createObjectURL(csvFile);
// Hide download link
downloadLink.style.display = "none";
return downloadLink;
}
// A function that will create a download link for the json file
function createDownloadJSONLink(json, filename) {
let jsonFile;
let downloadLink;
// JSON file
jsonFile = new Blob([JSON.stringify(json)], {
type: "application/json",
});
// Download link
downloadLink = document.createElement("a");
// File name
downloadLink.download = filename;
// Create a link to the file
downloadLink.href = window.URL.createObjectURL(jsonFile);
// Hide download link
downloadLink.style.display = "none";
return downloadLink;
}
// A function that will create a download button for the csv file
function createDownloadCSVButton(csv, filename) {
// Creating a download link for the csv file
const downloadLink = createDownloadCSVLink(csv.csv, filename);
// Creating the button
const downloadButton = document.createElement("button");
// Adding text to the button
downloadButton.innerText = "CSV";
// Adding an event listener to the button
downloadButton.addEventListener("click", () => {
document.body.appendChild(downloadLink);
downloadLink.click();
});
return downloadButton;
}
function createDownlodJSONButton(json, filename) {
// Creating a download link for the csv file
const downloadLink = createDownloadJSONLink(json, filename);
// Creating the button
const downloadButton = document.createElement("button");
// Adding text to the button
downloadButton.innerText = "JSON";
// Adding an event listener to the button
downloadButton.addEventListener("click", () => {
document.body.appendChild(downloadLink);
downloadLink.click();
});
return downloadButton;
}
// A function that will append a download button to the page
// The button will be appended after the element with the id beforeElId
function appendDownloadButtons(jsonified, filename) {
// Parse csv from jsonified
const csvContent = createCSV(jsonified);
// Create download csv button
const downloadCSVButton = createDownloadCSVButton(csvContent, filename);
// Create Download JSON button
const downloadJSONBUTTON = createDownlodJSONButton(jsonified, filename);
// Get the buttons container
const buttonsContainer = document.getElementById(
"downloadButtonsContainer"
);
// insert a download button with downloadLink after downloadJSON
// Clear the container
buttonsContainer.innerHTML =
" Download Last Data Set As:"; // is HTML code to add a space.
// Add download JSON button
buttonsContainer.appendChild(downloadJSONBUTTON);
// Add download CSV button
buttonsContainer.appendChild(downloadCSVButton);
}
// Convert the received dataset units to the first dataset units
function convertUnits(jsonified, globalData) {
return new Promise((resolve, reject) => {
try {
jsonified.data.forEach((dataSet) => {
const newXUnit = getUnitFromLabel(jsonified.layout.xaxis.title);
const newYUnit = getUnitFromLabel(jsonified.layout.yaxis.title);
if (globalData.unit.x !== newXUnit) {
const xConvertFactor = convert.fullConversion(
newXUnit,
globalData.unit.x
);
dataSet.x = dataSet.x.map((x) => {
if (xConvertFactor.status == 0) {
return parseFloat(x) * xConvertFactor.output.num;
} else {
xConvertFactor.messages.forEach((message) => {
errorDiv.innerText += message.message + "\n";
});
}
});
}
if (globalData.unit.y !== newYUnit) {
const yConvertFactor = convert.fullConversion(
newYUnit,
globalData.unit.y
);
dataSet.y = dataSet.y.map((y) => {
if (yConvertFactor.status == 0) {
return parseFloat(y) * yConvertFactor.output.num;
} else {
yConvertFactor.messages.forEach((message) => {
errorDiv.innerText = message.message + "\n";
});
}
});
}
});
resolve(jsonified);
} catch (err) {
reject(err);
}
});
}
async function initializeJSONGrapher() {
try {
const universalSchemas = await prepareUniversalSchemas();
schema1json = universalSchemas[0];
schema2json = universalSchemas[1];
return [schema1json, schema2json];
} catch (err) {
console.log("Error from initializeJSONGrapher: ", err);
}
}
// a function that merges jsonified with the template
function mergeObjects(jsonified, schema_template) {
const merged = JSON.parse(JSON.stringify(jsonified));
merged.data.forEach((dataSet) => {
dataSet.mode = schema_template.data[0].mode;
dataSet.line = schema_template.data[0].mode;
});
return merged;
}
///############################ BELOW IS THE MAIN BLOCK OF CODE FOR JSON GRAPHER ##################################
// STEP 0: Prepare the 'universal' schemas occurs inside initializeJSONGrapher
initializeJSONGrapher()
.then((resp) => {
// Assign variables to the two universal schemas.
schema = resp[0];
plotlyTemplate = resp[1];
// STEP 1: User selects a file from computer or drops a file on the browser
// Checks if the browser supports the File API
if (window.FileList && window.File) {
// Event that fires when the user selects a file from the computer from the choose file button
document
.getElementById("file-selector")
.addEventListener("change", (event) => {
// Launches the loadFile function after the file is selected
loadAndPlotData(event, "change");
});
// Event listener for drag and drop
const dropArea = document.getElementById("file-drop-area");
dropArea.addEventListener("dragover", (event) => {
event.stopPropagation();
event.preventDefault();
event.dataTransfer.dropEffect = "copy";
});
dropArea.addEventListener("drop", (event) => {
event.preventDefault();
// Launches the loadFile function after the file is dropped
loadAndPlotData(event, "drop");
});
}
})
.catch((e) => {
console.log(e);
errorDiv.innerText = "Error fetching json-schema files...\n";
});
// This function is called the user drops a file or upload it via the input button or drag and drop
function loadAndPlotData(event, eventType) {
// Checks if the file is dropped and if it is uploaded via the input button and gets the file
// STEP 1: User selects a file from computer or drops a file on the browser
const file =
eventType === "change"
? event.target.files[0]
: event.dataTransfer.files[0];
// Initialize the reader
const reader = new FileReader();
reader.fileName = file.name;
// Waits for the file to be loaded
reader.addEventListener("load", (event) => {
// Get the loaded data from the reader
const dataLoaded = event.target.result;
document.getElementById("file-selector").value = "";
// STEP 2: If the file is a .csv or .tsv file it is converted to a .json file
// Test what is incoming
let fileType = findFileType(event.target.fileName);
let jsonified;
try {
// try to parse the file as json
jsonified = jsonifyData(fileType, dataLoaded);
} catch (e) {
errorDiv.innerText = `Error: Data record could not be converted to JSON. If it is in a zipfile, unzip before uploading. Error Details: ${e.message} \n`;
}
recentFileName = getFileName(event.target.fileName);
// Checking if the uploaded data is valid against the schema
// STEP 3: Check if the jsonified object is a valid JSON file against the schema
getSchemaType(jsonified).then(([schema_type, schema_template]) => {
if (Object.keys(schema_type).length === 0) {
errorDiv.innerText +=
"Schema check: There was no Schema specific to this DataType, or the schema was not compatible. The default scatter plot schema was used.\n";
schema_type = schema;
}
// validate the json
const validate = ajv.compile(schema_type);
const valid = validate(jsonified);
if (!valid) {
// Console log an error if the data is not valid against the schema
console.log("validate errors: ", JSON.stringify(validate.errors));
// Display an error message if the data is not valid against the schema
errorDiv.innerText += `Json file does not match the schema. ${JSON.stringify(
validate.errors
)}\n`;
errorDiv.innerText += `Json file does not match the schema. ${JSON.stringify(
validate.errors
)}\n`;
} else {
let _jsonified = jsonified;
if (Object.keys(schema_template).length !== 0) {
_jsonified = mergeObjects(jsonified, schema_template);
}
// If the data is valid against the schema, then we can proceed to the next step
// if necessary create download button with json
// STEP 4 and STEP 5 is done in the prepareForPlotting function
prepareForPlotting(_jsonified, recentFileName).then((res) => {
// STEP 6: Provide file with converted units for download as JSON and CSV by buttons
appendDownloadButtons(res.downloadData, res.fileName);
// STEP 7: The plotly template is rendered on the browser
visualizeData(res.data);
});
}
});
});
reader.readAsText(file);
}
// This a function that plots the data on the graph
function prepareForPlotting(jsonified, filename) {
return new Promise(async (resolve, reject) => {
try {
// Checks if the Jsonified is the first file uploaded
if (!globalData) {
let _jsonified = JSON.parse(JSON.stringify(jsonified));
globalData = _jsonified;
// Get the unit from the label
const xUnit = getUnitFromLabel(globalData.layout.xaxis.title);
const yUnit = getUnitFromLabel(globalData.layout.yaxis.title);
// Adding the extracted units to globalData
globalData.unit = {
x: xUnit,
y: yUnit,
};
// STEP 4: Check if the object has a dataSet that has a simulate key in it, and runs the simulate function based on the value provided in the key model
// Iterate through the dataset and check if there is a simulation to run for each dataset
for (const dataSet of globalData.data) {
const index = globalData.data.indexOf(dataSet);
const hasSimulate = checkSimulate(dataSet);
if (hasSimulate) {
const simulatedData = await getAndRunSimulateScript(
dataSet,
globalData,
index
);
// STEP 5: Check if the units in the dataset are the same as the units in the previous object and convert them
const convertSimulatedDataUnits =
await maybeConvertSimulatedDataUnits(
jsonified,
simulatedData,
index
);
const simulatedJsonified = await mergeSimulationData(
convertSimulatedDataUnits,
jsonified,
index
);
jsonified = simulatedJsonified;
// STEP 5: Check if the units in the dataset are the same as the units in the previous object and convert them
// There is no STEP 5 at this line, because the first dataset provided by the user is used to define the units of GlobalData.
}
}
//Finally, return the objects that have been prepared for plotting an downloading.
resolve({
data: globalData,
downloadData: jsonified,
fileName: recentFileName,
});
} else {
// If the Jsonified is not the first file uploaded, then we can proceed to the next step
if (
globalData.title === jsonified.title &&
globalData.layout.xaxis.title.text ===
jsonified.layout.xaxis.title.text &&
globalData.layout.yaxis.title.text ===
jsonified.layout.yaxis.title.text
) {
// create a deep copy of jsonified to avoid mutating the original jsonified
let _jsonified = JSON.parse(JSON.stringify(jsonified));
let convertedJsonified = _jsonified;
let simulatedJsonified;
let convertSimulatedDataUnits;
// STEP 4: Check if the object has a dataSet that has a simulate key in it, and runs the simulate function based on the value provided in the key model
// Iterate through the dataset and check if there is a simulation to run for each dataset
for (const dataSet of _jsonified.data) {
const index = _jsonified.data.indexOf(dataSet);
const hasSimulate = checkSimulate(dataSet);
if (hasSimulate) {
const simulatedData = await getAndRunSimulateScript(
dataSet,
jsonified,
index
);
//This changes the simulated data to have units matching the json object it came from (that is, the layout field)
convertSimulatedDataUnits =
await maybeConvertSimulatedDataUnits(
jsonified,
simulatedData,
index
);
simulatedJsonified = await mergeSimulationData(
convertSimulatedDataUnits,
jsonified,
index
);
// STEP 5: Check if the units in the dataset are the same as the units in the previous object and convert them
convertedJsonified = await convertUnits(
simulatedJsonified,
globalData
);
} else {
// STEP 5: Check if the units in the dataset are the same as the units in the previous object and convert them
convertedJsonified = await convertUnits(
_jsonified,
globalData
);
}
}
// merge the new data with the globalData so everything can be plotted together.
globalData.data = [
...globalData.data,
...convertedJsonified.data,
];