-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtissueExpressionBAR.js
1937 lines (1721 loc) · 63.7 KB
/
tissueExpressionBAR.js
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
/* eslint-disable prefer-destructuring */
//= =========================== Alexander Sullivan =============================
//
// Purpose: Generates eFP tissue expression data
//
//= ============================================================================
/** Stroke data of compendiums that have already been called */
const existingStrokeData = {};
window.existingStrokeData = existingStrokeData;
/**
* Add details to an SVG or SVG-subunit including: hover and outline
* @param {String} elementID Which SVG or SVG-subunit is being found and edited
*/
function addTissueMetadata(elementID) {
// Adjusting for BioticStressPseudomonassyringae's half leaf:
if (elementID.includes("Half_Leaf_Pseudomonas_syringae")) {
elementID += "_outline";
}
// Retrieve document objects:
let svgDoc;
let svgPart;
let svgPartChildren;
if (document.getElementById(createSVGExpressionData.svgObjectName)) {
svgDoc = document.getElementById(createSVGExpressionData.svgObjectName);
svgPart = svgDoc.getElementById(elementID);
svgPartChildren = svgPart.childNodes;
}
/** Increase stroke width within SVG by (multiplied) this much */
const increaseStrokeWidthBy = 2.25;
// Storing stroke widths
let existingStrokeWidth;
let existingStrokeColour;
if (svgDoc && svgPart) {
if (svgPart.getAttribute("stroke-width")) {
existingStrokeWidth = svgPart.getAttribute("stroke-width");
if (svgPart.getAttribute("stroke")) {
existingStrokeColour = svgPart.getAttribute("stroke");
}
} else if (svgPartChildren.length > 0) {
for (const svgChildPart of svgPartChildren) {
if (svgChildPart.nodeName === "path") {
if (svgChildPart.getAttribute("stroke-width")) {
existingStrokeWidth = svgChildPart.getAttribute("stroke-width");
}
if (svgChildPart.getAttribute("stroke")) {
existingStrokeColour = svgChildPart.getAttribute("stroke");
}
}
}
}
if (!existingStrokeData[elementID]) {
existingStrokeData[elementID] = {};
existingStrokeData[elementID].strokeWidth = existingStrokeWidth;
existingStrokeData[elementID].strokeColour = existingStrokeColour;
existingStrokeData[elementID].addedMetadata = false;
}
// Making stroke width thicker
if (svgDoc.getElementById(elementID) && !existingStrokeData[elementID].addedMetadata) {
existingStrokeData[elementID].addedMetadata = true;
const strokeElement = svgDoc.getElementById(elementID);
// Create hover title box
if (strokeElement.getBoundingClientRect()) {
/** Title box's text */
const titleText = svgPart.getElementsByTagName("title")?.[0]?.textContent;
/** Title box's x-coordinate */
const boxLeft = strokeElement.getBoundingClientRect().right;
/** Title box's y-coordinate */
const boxTop = strokeElement.getBoundingClientRect().bottom;
// If all the data is available, add the title box
if (titleText && boxLeft && boxTop) {
ePlantPlantEFPChangeTitlePosition(true, boxLeft, boxTop, titleText);
} else {
// Fail-safe, hide title box
ePlantPlantEFPChangeTitlePosition(false);
}
} else {
// Fail-safe, hide title box
ePlantPlantEFPChangeTitlePosition(false);
}
existingStrokeWidth = Number(existingStrokeWidth);
let newStrokeWidth = existingStrokeWidth * increaseStrokeWidthBy;
const maxStrokeWidth = increaseStrokeWidthBy;
const minStrokeWidth = increaseStrokeWidthBy / 2;
if (newStrokeWidth > maxStrokeWidth && maxStrokeWidth > existingStrokeWidth) {
newStrokeWidth = maxStrokeWidth;
} else if (newStrokeWidth < minStrokeWidth && minStrokeWidth > existingStrokeWidth) {
newStrokeWidth = minStrokeWidth;
} else if (newStrokeWidth === 0) {
newStrokeWidth = increaseStrokeWidthBy;
} else if (!newStrokeWidth) {
newStrokeWidth = minStrokeWidth;
}
/** Boolean to determine if metadata has been added already */
let addedHoverMetadata = false;
if (strokeElement.getAttribute("stroke-width")) {
svgDoc.getElementById(elementID).setAttribute("stroke-width", newStrokeWidth);
svgDoc.getElementById(elementID).setAttribute("stroke", "#000");
addedHoverMetadata = true;
} else if (svgPartChildren && svgPartChildren.length > 0) {
for (const svgChildPart of svgPartChildren) {
if (svgChildPart.nodeName === "path" && svgChildPart.getAttribute("stroke-width")) {
svgChildPart.setAttribute("stroke-width", newStrokeWidth);
if (svgChildPart.getAttribute("stroke")) {
svgChildPart.setAttribute("stroke", "#000");
}
addedHoverMetadata = true;
}
}
}
if (!addedHoverMetadata) {
svgDoc.getElementById(elementID).setAttribute("stroke-width", newStrokeWidth);
svgDoc.getElementById(elementID).setAttribute("stroke", "#000");
}
}
}
}
/**
* Remove details to an SVG or SVG-subunit including: hover and outline
* @param {String} elementID Which SVG or SVG-subunit is being found and edited
*/
function removeTissueMetadata(elementID) {
// Adjusting for BioticStressPseudomonassyringae's half leaf:
if (elementID.includes("Half_Leaf_Pseudomonas_syringae")) {
elementID += "_outline";
}
/** A fallback stroke width for the SVG if one is not already pre-determined */
const fallbackStrokeWidth = 1;
/** A fallback stroke colour (black) for the SVG if one is not already pre-determined */
const fallbackStrokeColour = "#000"; // Black
// Retrieve document objects:
let svgDoc;
let svgPart;
let svgPartChildren;
if (document.getElementById(createSVGExpressionData.svgObjectName)) {
svgDoc = document.getElementById(createSVGExpressionData.svgObjectName);
svgPart = svgDoc.getElementById(elementID);
svgPartChildren = svgPart.childNodes;
}
// If existing stroke data exists, then proceed
if (existingStrokeData[elementID] && existingStrokeData[elementID].addedMetadata) {
existingStrokeData[elementID].addedMetadata = false;
if (svgPart && svgPart.getAttribute("stroke-width")) {
if (Number(existingStrokeData[elementID].strokeWidth) >= 0) {
svgDoc
.getElementById(elementID)
.setAttribute("stroke-width", existingStrokeData[elementID].strokeWidth);
} else if (!existingStrokeData[elementID].strokeWidth) {
svgDoc.getElementById(elementID).removeAttribute("stroke-width");
} else {
svgDoc.getElementById(elementID).setAttribute("stroke-width", fallbackStrokeWidth);
}
if (svgPart.getAttribute("stroke")) {
if (existingStrokeData[elementID].strokeColour) {
svgDoc.getElementById(elementID).setAttribute("stroke", existingStrokeData[elementID].strokeColour);
} else {
svgDoc.getElementById(elementID).setAttribute("stroke", fallbackStrokeColour);
}
}
} else if (svgPartChildren.length > 0) {
for (const svgChildPart of svgPartChildren) {
if (svgChildPart.nodeName === "path") {
if (svgChildPart.getAttribute("stroke-width")) {
if (Number(existingStrokeData[elementID].strokeWidth) >= 0) {
svgChildPart.setAttribute("stroke-width", existingStrokeData[elementID].strokeWidth);
} else if (!existingStrokeData[elementID].strokeWidth) {
svgDoc.getElementById(elementID).removeAttribute("stroke-width");
} else {
svgChildPart.setAttribute("stroke-width", fallbackStrokeWidth);
}
}
if (svgChildPart.getAttribute("stroke")) {
if (existingStrokeData[elementID].strokeColour) {
svgChildPart.setAttribute("stroke", existingStrokeData[elementID].strokeColour);
} else {
svgChildPart.setAttribute("stroke", fallbackStrokeColour);
}
}
}
}
} else {
svgPart.setAttribute("stroke-width", fallbackStrokeWidth);
svgPart.setAttribute("stroke", fallbackStrokeColour);
}
}
// Hide title box
ePlantPlantEFPChangeTitlePosition(false);
}
/**
* General debounce function for the ePlant Plant eFP and its tissue metadata
* @param {Function} func Function to be debounced
* @param {Number} wait Time to wait before executing the function
* @returns {Function} The debounced function
* @example <caption>Example usage of the debounce function where the function is debounced for 250ms and prevents that function from being called again during that weight time</caption>
* debounceTissueMetadata(functionToBeDebounced, 250);
* // returns functionToBeDebounced (after 250ms)
*/
function debounceTissueMetadata(func, wait) {
let timeout;
// eslint-disable-next-line func-names
return function (...args) {
const context = this;
clearTimeout(timeout);
timeout = setTimeout(() => func.apply(context, args), wait);
};
}
/**
* Create and display the ePlant Plant eFP's hover title box
* @param {Boolean} display Whether to display [true] or hide [false, default] the title box
* @param {Number | String} x The x-coordinate of the element being hovered over
* @param {Number | String} y The y-coordinate of the element being hovered over
* @param {String} textContent The text to be displayed in the title box
* @param {String} domID The ID of the title box DOM element
*/
function ePlantPlantEFPChangeTitlePosition(
display = false,
x = 0,
y = 0,
textContent = "",
domID = "ePlant-hover-title-box",
) {
/** DOM of the title box element */
const domElm = document.getElementById(domID);
if (domElm) {
if (!display) {
// Hide title box
domElm.style.display = "none";
} else {
// Display title box
domElm.style.display = "block";
domElm.style.left = `${x}px`;
domElm.style.top = `${y}px`;
domElm.textContent = textContent;
}
}
}
/** ePlant Plant's eFP mouse event data */
const ePlantPlantEFPHandleMouseEventData = {
/** Whether mouse events can occur [true] or not [false, default] */
start: false,
/** Cache last mouse position to calculate next position on drag */
cacheMousePos: { x: null, y: null },
/** Initial height of the SVG */
startHeight: null,
/** How much the SVG has been zoomed in by */
zoomLevel: 1,
};
/**
* Handle mouse events to drag the SVG compendium
* @param {String} domID DOM ID of the SVG container
* @param {String} type What type of event is happening: 'down' to initiate drag, 'move' to drag, 'up' to end drag
* @param {Event} e Mouse event object
* @param {Number} moveBy How much the SVG has been moved by
*/
// eslint-disable-next-line no-unused-vars
function ePlantPlantEFPHandleMouseEvent(domID, type, e, moveBy = 1.5) {
/** SVG document */
const svgElement = domID.firstElementChild;
// If SVG is not loaded, then return
if (svgElement?.viewBox?.baseVal) {
// If the SVG is not yet been cached, then cache it
if (!ePlantPlantEFPHandleMouseEventData.startHeight) {
ePlantPlantEFPHandleMouseEventData.startHeight = svgElement.viewBox.baseVal.height;
}
// Determine if SVG should be draggable or not
if (
type === "down" &&
!ePlantPlantEFPHandleMouseEventData.start &&
window.getSelection() &&
window.getSelection().isCollapsed
) {
// Prevent highlighting of text when dragging
e.preventDefault();
// Cache the mouse position and begin dragging
ePlantPlantEFPHandleMouseEventData.start = true;
ePlantPlantEFPHandleMouseEventData.cacheMousePos = { x: e.clientX, y: e.clientY };
}
// If the SVG is being dragged, then drag it
if (type === "move" && ePlantPlantEFPHandleMouseEventData.start) {
// Prevent highlighting of text when dragging
e.preventDefault();
/** How much the SVG will be dragged */
const moveByValue = svgElement.viewBox.baseVal.height
? window.innerHeight / svgElement.viewBox.baseVal.height / moveBy
: moveBy;
// Calculate the new position of the SVG
/** New X position of SVG */
const xDiff = -(e.clientX - ePlantPlantEFPHandleMouseEventData.cacheMousePos.x) / moveByValue;
/** New Y position of SVG */
const yDiff = -(e.clientY - ePlantPlantEFPHandleMouseEventData.cacheMousePos.y) / moveByValue;
// Find boundaries of the SVG so it does not leave viewpoint
/** Default boundaries for SVG viewpoint */
const defaultScaleBoundaries = 0.95;
/** Boundaries to scale the SVG's viewpoint on the X axis */
let scaleBoundariesX = svgElement.height.baseVal.value
? (defaultScaleBoundaries * 100 - svgElement.height.baseVal.value / svgElement.viewBox.baseVal.height) /
100
: (defaultScaleBoundaries * 100 - window.innerHeight / svgElement.viewBox.baseVal.height) / 100;
// Should be between 0 and 1
if (scaleBoundariesX <= 0 || scaleBoundariesX >= 1) {
scaleBoundariesX = defaultScaleBoundaries;
}
/** Boundaries to scale the SVG's viewpoint on the Y axis */
let scaleBoundariesY = svgElement.width.baseVal.value
? (defaultScaleBoundaries * 100 - svgElement.width.baseVal.value / svgElement.viewBox.baseVal.width) /
100
: (defaultScaleBoundaries * 100 - window.innerWidth / svgElement.viewBox.baseVal.height) / 100;
// Should be between 0 and 1
if (scaleBoundariesY <= 0 || scaleBoundariesY >= 1) {
scaleBoundariesY = defaultScaleBoundaries;
}
/** Current zoom level on the SVG compendium */
const zoomLevel =
1 / ePlantPlantEFPHandleMouseEventData.zoomLevel === 1
? defaultScaleBoundaries
: 1 / ePlantPlantEFPHandleMouseEventData.zoomLevel;
/** Boundaries to scale the SVG's viewpoint on the X axis */
const xBoundaries = svgElement.viewBox.baseVal.width * scaleBoundariesX * zoomLevel;
/** Boundaries for the X axis on the right side of the SVG compendium's viewpoint */
const xRightBoundaries = svgElement.viewBox.baseVal.width * scaleBoundariesX;
/** Boundaries to scale the SVG's viewpoint on the Y axis */
const yBoundaries = svgElement.viewBox.baseVal.height * scaleBoundariesY;
/** Upper boundaries to scale the SVG's viewpoint on the Y axis */
const yUpperBoundaries = yBoundaries * zoomLevel;
// Cache mouse position
ePlantPlantEFPHandleMouseEventData.cacheMousePos = { x: e.clientX, y: e.clientY };
// If SVG's Y position within viewpoint, then move it
if (
svgElement.viewBox.baseVal.y + yDiff <= yUpperBoundaries &&
svgElement.viewBox.baseVal.y + yDiff >= -yBoundaries
) {
svgElement.viewBox.baseVal.y += yDiff;
} else {
// If SVG's Y position is outside viewpoint, then move it to the top or bottom
svgElement.viewBox.baseVal.y =
svgElement.viewBox.baseVal.y + yDiff > 0 ? yUpperBoundaries : -yBoundaries;
}
// If SVG's X position within viewpoint, then move it
if (
svgElement.viewBox.baseVal.x + xDiff <= xBoundaries &&
svgElement.viewBox.baseVal.x + xDiff >= -xRightBoundaries
) {
svgElement.viewBox.baseVal.x += xDiff;
} else {
// If SVG's X position is outside viewpoint, then move it to the left or right
svgElement.viewBox.baseVal.x =
svgElement.viewBox.baseVal.x + xDiff > 0 ? xBoundaries : -xRightBoundaries;
}
}
}
// End dragging
if (type === "up") {
ePlantPlantEFPHandleMouseEventData.start = false;
}
}
/**
* Handle zooming of SVG
* @param {String} domID DOM ID of the SVG container
* @param {Event} e Mouse event object
* @param {Number} changeBy How much the SVG has been moved by
*/
// eslint-disable-next-line no-unused-vars
function ePlantPlantEFPHandleMouseWheel(domID, e, changeBy = 3) {
/** SVG document */
const svgElement = domID.firstElementChild;
/** SVG viewpoint */
const baseValues = svgElement.viewBox.baseVal;
/** If should zoom in [true] or out [false] */
const up = e.deltaY > 0;
/** How much the zoom will zoom in by */
const changeByValue = ePlantPlantEFPHandleMouseEventData.startHeight
? window.innerHeight / ePlantPlantEFPHandleMouseEventData.startHeight / changeBy
: changeBy;
if (
window.getSelection() &&
window.getSelection().isCollapsed &&
baseValues &&
e.deltaY &&
ePlantPlantEFPHandleMouseEventData.start
) {
// Prevent scrolling window
e.preventDefault();
if (up) {
svgElement.viewBox.baseVal.width = baseValues.width * changeByValue;
svgElement.viewBox.baseVal.height = baseValues.height * changeByValue;
ePlantPlantEFPHandleMouseEventData.zoomLevel *= changeByValue;
} else {
svgElement.viewBox.baseVal.width = baseValues.width / changeByValue;
svgElement.viewBox.baseVal.height = baseValues.height / changeByValue;
ePlantPlantEFPHandleMouseEventData.zoomLevel /= changeByValue;
}
}
}
/**
* Create and retrieve expression data in an SVG format
*/
class CreateSVGExpressionData {
constructor() {
// callPlantEFP
this.eFPObjects = {};
// loadSampleData
this.sampleData = {};
this.sampleOptions = [];
this.sampleReadableName = {};
// Top expression data
this.topExpressionValues = {};
this.expressionValues = {};
this.topExpressionOptions = ["Microarray", "RNA-seq"];
// Local storage grabbed
this.localStorageTop = false;
this.localStorageSample = {};
// Local for this class
this.desiredDOMid = "";
/** Markup for the visualization container */
// eslint-disable-next-line no-unused-expressions
this.appendSVG;
// createSVGValues
this.clickList = [];
this.svgValues = {};
this.svgMax = 0;
this.svgMin = 0;
this.svgMaxAverage = 0;
this.svgMaxAverageSample = "";
this.svgMinAverage = 0;
this.svgMinAverageSample = "";
// Store object name:
this.svgObjectName = "";
/** SVG DOM container's height styling */
this.svgContainerHeight = "95vh";
}
/**
* Verify that the locus being called is valid
* IMPORTANT: The current script only works for Arabidopsis thaliana
* TODO: Add support for other languages. Fill list of loci patterns can be found within GAIA's tools (accessible only to BAR developer at the moment)
* @param {String} locus The AGI ID (example: AT3G24650 or AT3G24650.1)
* @returns {Boolean} If locus is valid [true] or not [false, default]
*/
// eslint-disable-next-line class-methods-use-this
verifyLoci(locus) {
// Check if locus is a string
if (typeof locus === "string") {
/** Arabidopsis thaliana locus pattern */
const arabidopsisThalianaPattern = `^[A][T][MC0-9][G][0-9]{5}[.][0-9]{1,2}$|^[A][T][MC0-9][G][0-9]{5}$`;
/** Reg Exp for the locus pattern */
const regexPattern = new RegExp(arabidopsisThalianaPattern, "i");
// If match, then return true, else return false
return Boolean(locus.trim().match(regexPattern));
}
return false;
}
/**
* Create and generate an SVG based on the desired tissue expression locus
* @param {String} locus The AGI ID (example: AT3G24650)
* @param {String} desiredDOMid The desired DOM location or if kept empty, would not replace any DOM elements and just create the related HTML DOM elements within appendSVG
* @param {String} svgName Name of the SVG file without the .svg at the end. Default is set to "default", when left this value, the highest expression value (if any) is chosen and if not, then Abiotic Stress is.
* @param {Boolean} includeDropdownAll true = include a html dropdown/select of all available SVGs/samples, false = don't
* @param {String | Number} containerHeight The height of the SVG container, default is 95vh
*/
generateSVG(
locus = "AT3G24650",
desiredDOMid = undefined,
svgName = "default",
includeDropdownAll = true,
containerHeight = undefined,
) {
if (this.verifyLoci(locus.trim())) {
// Reset variables:
this.svgValues = {};
this.svgMax = undefined;
this.svgMin = undefined;
this.svgMaxAverage = undefined;
this.svgMaxAverageSample = undefined;
this.svgMinAverage = undefined;
this.svgMinAverageSample = undefined;
this.includeDropdownAll = includeDropdownAll;
if (this.clickList.includes(svgName) === false) {
this.clickList.push(svgName);
}
if (containerHeight && typeof containerHeight === "string") {
this.svgContainerHeight = containerHeight.toString();
} else if (containerHeight && typeof containerHeight === "number") {
this.svgContainerHeight = `${containerHeight.toString()}px`;
}
// Initiate scripts
this.desiredDOMid = desiredDOMid;
this.#retrieveTopExpressionValues(svgName, locus.trim().toUpperCase());
} else {
console.error(`Invalid locus: ${locus.trim()}`);
}
}
/**
* Retrieve information about the top expression values for a specific locus
* @param {String} svgName Name of the SVG file without the .svg at the end
* @param {String} locus The AGI ID (example: AT3G24650)
*/
async #retrieveTopExpressionValues(svgName, locus = "AT3G24650") {
let completedFetches = 0;
let localStorageTopExpressionValues = localStorage.getItem("bar_eplant-top-expression-values");
let fetchData = true;
if (!this.localStorageTop) {
if (localStorageTopExpressionValues) {
localStorageTopExpressionValues = JSON.parse(localStorageTopExpressionValues);
// Check if week passed expiration
if (
localStorageTopExpressionValues.expiry &&
new Date().getTime() - localStorageTopExpressionValues.expiry <= 7 * 24 * 60 * 60 * 1000
) {
fetchData = false;
} else if (localStorageTopExpressionValues[locus]) {
fetchData = false;
}
this.topExpressionValues = {
...this.topExpressionValues,
...localStorageTopExpressionValues,
};
this.localStorageTop = true;
}
}
if (this.topExpressionValues[locus]) {
fetchData = false;
}
// If never been called before
if (fetchData) {
for (const topMethod of this.topExpressionOptions) {
const url = `https://bar.utoronto.ca/expression_max_api/max_average?method=${topMethod}`;
const sendHeaders = "application/json";
let postSend = {
loci: [locus.toUpperCase()],
method: topMethod,
};
postSend = JSON.stringify(postSend);
const methods = { mode: "cors" };
methods.method = "POST";
if (sendHeaders) {
methods.headers = {};
methods.headers["Content-type"] = sendHeaders;
}
methods.body = postSend;
// eslint-disable-next-line no-await-in-loop
await fetch(url, methods)
// eslint-disable-next-line no-loop-func
.then(async (response) => {
if (response.status === 200) {
await response.text().then(async (data) => {
let responseData;
if (data.length > 0) {
responseData = JSON.parse(data);
} else {
responseData = {};
}
let topMethodUsed;
const urlQuery = url.split("=");
if (urlQuery.length > 1) {
topMethodUsed = urlQuery[1];
}
if (topMethodUsed && responseData && responseData.wasSuccessful === true) {
if (responseData.maxAverage) {
const tempTopExpressionData = {};
tempTopExpressionData[topMethodUsed] = {};
tempTopExpressionData[topMethodUsed].maxAverage =
responseData.maxAverage[locus.toUpperCase()];
if (responseData.standardDeviation) {
tempTopExpressionData[topMethodUsed].standardDeviation =
responseData.standardDeviation[locus.toUpperCase()];
}
if (responseData.sample) {
tempTopExpressionData[topMethodUsed].sample =
responseData.sample[locus.toUpperCase()];
}
if (responseData.compendium) {
tempTopExpressionData[topMethodUsed].compendium =
responseData.compendium[locus.toUpperCase()];
}
if (!this.topExpressionValues) {
this.topExpressionValues = {};
}
this.topExpressionValues[locus] = {
...this.topExpressionValues[locus],
...tempTopExpressionData,
};
}
}
completedFetches += 1;
if (completedFetches === this.topExpressionOptions.length) {
// Update local storage:
// Add to local storage as well:
if (!localStorageTopExpressionValues || fetchData) {
localStorageTopExpressionValues = {};
localStorageTopExpressionValues[locus] = {
...this.topExpressionValues[locus],
};
localStorageTopExpressionValues.expiry = new Date().getTime();
} else {
localStorageTopExpressionValues[locus] = {
...this.topExpressionValues[locus],
};
}
// Ensure that local storage has no more than 10 entries
if (
localStorageTopExpressionValues &&
Object.keys(localStorageTopExpressionValues).length > 10
) {
// Remove the first entry if not the one we just added and not 'expiry'
for (const key in localStorageTopExpressionValues) {
if (key !== locus && key !== "expiry") {
delete localStorageTopExpressionValues[key];
break;
}
}
}
if (localStorageTopExpressionValues) {
localStorage.setItem(
"bar_eplant-top-expression-values",
JSON.stringify(localStorageTopExpressionValues),
);
this.localStorageTop = true;
}
await this.#loadSampleData(svgName, locus);
}
});
} else if (response.status !== 200) {
completedFetches += 1;
if (completedFetches === this.topExpressionOptions.length) {
await this.#loadSampleData(svgName, locus);
}
console.error(
`fetch error - Status Code: ${response.status}, fetch-url: ${response.url}, document-url: ${window.location.href}`,
);
}
})
// eslint-disable-next-line no-loop-func
.catch(async (err) => {
completedFetches += 1;
if (completedFetches === this.topExpressionOptions.length) {
await this.#loadSampleData(svgName, locus);
}
console.error(err);
});
}
} else if (Object.keys(this.topExpressionValues[locus]).length > 0) {
await this.#loadSampleData(svgName, locus);
} else if (Object.keys(localStorageTopExpressionValues[locus]).length > 0) {
if (!this.topExpressionValues) {
this.topExpressionValues = {};
}
this.topExpressionValues[locus] = localStorageTopExpressionValues[locus];
await this.#loadSampleData(svgName, locus);
}
}
/**
* Calls and stores the sample Data for the SVG, SVG's subunits, datasource and it's name-values
* @param {String} svgName Name of the SVG file without the .svg at the end
* @param {String} locus The AGI ID (example: AT3G24650)
*/
async #loadSampleData(svgName, locus) {
if (Object.keys(this.sampleData).length === 0) {
/** Whether to fetch the sample data container from GitHub (true, default) or not */
let fetchFromGitHub = true;
/** Browser's local storage for the sample data, if exists */
let localStoredSampleData = localStorage?.getItem("bar_eplant-sample-data-storage");
// If the local storage exists, see if it's expired (1 week) to fetch from GitHub or use the local storage data
if (localStoredSampleData) {
// Convert to JSON
localStoredSampleData = JSON.parse(localStoredSampleData);
// If a week has passed since the last time the data was stored
if (
localStoredSampleData.expiry &&
localStoredSampleData.data &&
new Date().getTime() - localStoredSampleData.expiry <= 7 * 24 * 60 * 60 * 1000
) {
// Has not expire, use this data
fetchFromGitHub = false;
this.sampleData = localStoredSampleData.data;
}
}
if (fetchFromGitHub) {
/** GitHub's URL for the sample data container */
const url =
"https://raw.githubusercontent.com/BioAnalyticResource/ePlant_Plant_eFP/master/data/SampleData.min.json";
/** Fetch methods */
const methods = { mode: "cors" };
await fetch(url, methods)
.then(async (response) => {
if (response.status === 200) {
await response.text().then(async (data) => {
/** Response data */
const res = data.length > 0 ? JSON.parse(data) : {};
// Store response
this.sampleData = res;
// Store into local storage
const sampleDataStorage = {
data: res,
expiry: new Date().getTime(),
};
localStorage.setItem(
"bar_eplant-sample-data-storage",
JSON.stringify(sampleDataStorage),
);
});
} else if (response.status !== 200) {
console.error(
`fetch error - Status Code: ${response.status}, fetch-url: ${response.url}, document-url: ${window.location.href}`,
);
}
})
.catch(async (err) => {
console.error(err);
});
}
// Setup and retrieve information about the target SVG and locus
await this.#retrieveSampleData(svgName, locus);
} else if (Object.keys(this.sampleData).length > 0) {
await this.#retrieveSampleData(svgName, locus);
}
}
/**
* Retrieves the sample information relating to an SVG for a specific set of data
* @param {String} svgName Name of the SVG file without the .svg at the end
* @param {String} locus The AGI ID (example: AT3G24650)
*/
async #retrieveSampleData(svgName, locus) {
// Check if svgName contains .svg
if (svgName.substring(-4) === ".svg") {
svgName = svgName.substring(0, svgName.length - 4);
}
if (this.sampleOptions.length === 0) {
for (const [key, value] of Object.entries(this.sampleData)) {
this.sampleOptions.push(key);
this.sampleReadableName[value.name] = key;
}
}
// Create variables that will be used in #retrieveSampleData
const sampleDataKeys = Object.keys(this.sampleData); // All possible SVGs
let sampleDB = ""; // The sample's datasource
let sampleIDList = []; // List of all of the sample's IDs
let sampleSubunits = []; // List of SVG's subunits
await this.#processLocalStorageEFPObjectData();
// Check if valid SVG
if (!sampleDataKeys.includes(svgName) && this.topExpressionValues[locus]) {
// Determine max expression value to default too
let maxExpressionValue = 0;
let maxExpressionCompendium;
for (const [, value] of Object.entries(this.topExpressionValues[locus])) {
if (value.compendium && value.compendium[1] && sampleDataKeys.includes(value.compendium[1])) {
if (value.maxAverage && value.maxAverage[1] && value.maxAverage[1] > maxExpressionValue) {
maxExpressionValue = value.maxAverage[1];
maxExpressionCompendium = value.compendium[1];
}
}
}
if (maxExpressionCompendium) {
svgName = maxExpressionCompendium;
} else {
svgName = "AbioticStress";
}
}
// If still default, load in Abiotic Stress
if (svgName === "default") {
svgName = "AbioticStress";
}
// Create variables for parsing
const sampleInfo = this.sampleData[svgName];
let sampleOptions;
if (sampleInfo && sampleInfo.sample) {
sampleOptions = sampleInfo.sample;
}
if (sampleInfo && sampleInfo.db) {
sampleDB = sampleInfo.db;
}
// If a database is available for this SVG, then find sample ID information
if (sampleDB !== undefined) {
sampleSubunits = Object.keys(sampleInfo.sample);
sampleIDList = [];
for (const sample of sampleSubunits) {
sampleIDList = sampleIDList.concat(sampleOptions[sample]);
}
}
// Call plantefp.cgi webservice to retrieve information about the target tissue expression data
if (!this.eFPObjects[svgName] || !this.eFPObjects[svgName].locusCalled.includes(locus)) {
await this.#callPlantEFP(sampleDB, locus, sampleIDList, svgName, sampleOptions);
} else if (this.eFPObjects[svgName]) {
await this.#addSVGtoDOM(svgName, locus, this.includeDropdownAll);
}
}
async #processLocalStorageEFPObjectData() {
if (Object.keys(this.localStorageSample).length === 0) {
// Grab localStorage's sample data:
let localStorageSampleValues = localStorage.getItem("bar_eplant-efp-data");
if (localStorageSampleValues) {
localStorageSampleValues = JSON.parse(localStorageSampleValues);
this.localStorageSample = localStorageSampleValues;
await this.#checkLocalStorageEFPObjectSize();
// Check if week passed expiration
if (
!localStorageSampleValues.expiry ||
!(new Date().getTime() - localStorageSampleValues.expiry <= 7 * 24 * 60 * 60 * 1000)
) {
// If this.eFPObjects is empty, give it the localStorageSampleValues data
if (Object.keys(this.eFPObjects).length === 0) {
this.eFPObjects = localStorageSampleValues;
} else {
// Go through this.eFPObjects and localStorageSampleValues and add in any missing data
// Data is in format of this.eFPObjects[compendium] and in [compendium], see if there is a [locus].
// See which loci are missing and add them in (if any), and if so, go through the [sample] and add in any missing data
for (const [compendium, compendiumData] of Object.entries(localStorageSampleValues)) {
if (compendium !== "expiry") {
if (this.eFPObjects[compendium]) {
// Check if locus is missing
const missingLoci = [];
// Go through the [locusCalled] array and see if any are missing
for (const locus of compendiumData.locusCalled) {
if (!this.eFPObjects[compendium].locusCalled.includes(locus)) {
missingLoci.push(locus);
}
}
// If there are missing loci, add them in
if (missingLoci.length > 0) {
// Go through the sample data and add in any missing data
for (const [sample, sampleData] of Object.entries(compendiumData.sample)) {
if (this.eFPObjects[compendium].sample[sample]) {
// Go through the [locus] and see if any are missing
for (const locus of missingLoci) {
if (!this.eFPObjects[compendium].sample[sample][locus]) {
this.eFPObjects[compendium].sample[sample][locus] =
sampleData[locus];
}
}
} else {
this.eFPObjects[compendium].sample[sample] = sampleData;
}
}
}
} else {
this.eFPObjects[compendium] = compendiumData;
}
}
}
}
}
}
}
}
async #checkLocalStorageEFPObjectSize(svgKeep = undefined) {
// Ensure that the localStorage is not too large (no more than 1MB)
// If it is, then remove the the first SVG in the eFPObjects object if not the one that is currently being kept (svgKeep) or 'expiry'
// Check size of this.localStorageSample
// Convert to string
const localStorageSampleString = JSON.stringify(this.localStorageSample);
// Get size of string
const localStorageSampleSize = localStorageSampleString.length * 2;
// If the localStorageSampleSize is too large, remove the first SVG in the eFPObjects object if not the one that is currently being kept (svgKeep) or 'expiry'
if (localStorageSampleSize > 1000000) {
// Go through the eFPObjects object and remove the first SVG if not the one that is currently being kept (svgKeep) or 'expiry'
for (const [svgName, _svgData] of Object.entries(this.eFPObjects)) {
if (svgName !== svgKeep && svgName !== "expiry") {
delete this.eFPObjects[svgName];
break;
}
}
}
}
/**
* Calls the plantefp.cgi webservice to retrieve expression data from the BAR
* @param {String} datasource Which database the information is contained in
* @param {String} locus The AGI ID (example: AT3G24650)
* @param {Array} samples List of sample ID's which the exact expression data is related to
* @param {String} svg Which SVG is being called
* @param {Array} sampleSubunits List of the SVG's subunits
*/
async #callPlantEFP(datasource, locus, samples, svg, sampleSubunits) {
// Create URL
let url = "https://bar.utoronto.ca/~asullivan/webservices/plantefp.cgi?";
url += `datasource=${datasource}&`;
url += `id=${locus}&`;
url += "samples=[";
for (let i = 0; i < samples.length; i += 1) {
let sampleName = samples[i].trim();
sampleName = sampleName.replace(/\+/g, "%2B");
sampleName = sampleName.replace(/ /g, "%20");
url += `"${sampleName}"`;
if (i !== samples.length - 1) {
url += ",";
}
}
url += "]";
const methods = { mode: "cors" };
let alreadyRetrievedData = false;
if (this.eFPObjects?.[svg]?.[locus]?.includes("locus")) {
alreadyRetrievedData = true;
}
if (sampleSubunits && !alreadyRetrievedData) {