-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathSanKEY_script.js
2097 lines (2053 loc) · 77.1 KB
/
SanKEY_script.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
class PlotCreator {
// 1. node_coordinates
/**
* Object containing the coordinates of a single node (used to specify single_link_data).
* @typedef {Object} node_coordinates
* @property {number} column - Index of the column.
* @property {number} node - Index of a node in the specified column.
*/
// 2. link_type
/**
* This property allows specifying shape of the link. It is a two-letter code with 4 possible variants.
* First letter (L - left or R - right) specifies the side of a first node connected by this link.
* Second letter specifies the side of a second connected node. If not precised, link_type is assumed to be
* RL.
* @typedef {('LR','RL','RR','LL')} link_type
*/
// 3. single_sublink_data
/**
* Object containing full data about the sublink.
* @typedef {Object} single_sublink_data
* @property {number} value - Value of the sublink.
* @property {number} shift - Vertical shift of the sublink. Value in the range [0,1) that specifies how much is
* the sublink shifted relatively to the main link, e.g. 0.5 means that the upper border of a sublink
* is exactly at 50% of the main link's height.
* @property {string} [color] - Optional color of the sublink. Color defined here has the highest priority.
*/
// 4. single_link_data
/**
* Object containing full data about the link.
* @typedef {Object} single_link_data
* @property {node_coordinates} from - First node coordinates.
* @property {node_coordinates} to - Second node coordinates.
* @property {number} value - Value of the link.
* @property {link_type} [link_type='RL'] - Optional link type.
* @property {string} [color] - Optional color of the link. Color defined here has the highest priority.
* @property {single_sublink_data[]} [sublinks] - Optional array of the sublinks data.
*/
/////// NODES DATA
// 1. single_node_data
/**
* Object containing full data about the node.
* @typedef {Object} single_node_data
* @property {string} [label] - Node label.
* @property {number} [width] - Optional node width as a ratio of a column width, e.g. 0.5 mean 50% of the column width.
* @property {string} [color] - Optional color of the node. Color defined here has the highest priority.
*/
/////// SETTINGS
/**
* Additional setting of the plot.
* @typedef {Object} settings
* @property {number} vertical_gap_between_nodes - Number between 0 and 1. Minimal size of the total vertical gap between nodes in a column (as a height fraction). E.g. *0.6* means that in each column at least 60% of its height will be the spacing between nodes. The default value is *0.7*.
* @property {number} node_percent_of_column_width - Number between 0 and 1. Standard node width as a fraction of the column width. E.g. *0.6* means that each node will occupy 60% of the column width. The default value is *0.3*.
* @property {boolean} show_column_lines - Boolean, determines whether to show the lines between columns. The default value is *true*.
* @property {boolean} show_column_names - Boolean, determines whether to show the column names. The default value is *true*.
* @property {boolean} show_links_out_of_range - Boolean, determines whether to show links in a situation where both nodes are not in the range of the plot, but the link between them is.
* If set to *true*, each time the plot is being refreshed, PlotCreator will look for such links, by scanning *k* nearest columns on each side of the column range,
* where *k* is the *length* of the longest link in the graph and *length* being defined as *|column_of_the_first_node - column_of_the_second_node|*.
* This may negatively impact the performance, however, unless there are links with the *length* around several thousand columns, the slowdown should not be noticeable. The default value is *true*.
* @property {boolean} node_move_y - Boolean, determines whether the nodes can be moved vertically. The default value is *true*.
* @property {boolean} linear_gradient_links - Boolean, determines whether the links should have a gradient color. The default value is *true*.
* @property {string} plot_background_color - Any CSS color. Plot background color. The default value is *'#f5ecec'*.
* @property {string} default_nodes_color - Any CSS color. Default nodes color. The default value is *'grey'*.
* @property {string} default_links_color - Any CSS color. Default links color. The default value is *'blue'*.
* @property {number} default_links_opacity - Number between 0 and 1. Default links opacity. The default value is *0.25*.
* @property {number} default_gradient_links_opacity - Number between 0 and 1. Default opacity of links if those have a gradient color. The default value is *0.43*.
* @property {string} default_sublinks_color - Any CSS color. Default sublinks color. The default value is *'red'*.
* @property {number} default_sublinks_opacity - Number between 0 and 1. Default sublinks opacity. The default value is *0.8*.
* @property {Object} label_colors_object - An object in which node labels are properties and node colors are the values. By defining such an object, the user can easily link node labels to their color, thus avoiding code redundancy. The default value is *{}*.
* @property {string[]} column_names - An array of column names. If passed, then instead of column indexes, names from this array will be displayed. The default value is *undefined*.
* @property {number} start_node_count_from - Number, determines from which number nodes in the columns are being indexed. __Important: this will only impact the display and PlotCreator’s interface. While defining nodes and links data, the user still needs to use the standard array indexes.__ The default value is *0*.
* @property {number} start_column_count_from - Number, determines from which number columns are being indexed. __Important: this will only impact the display and PlotCreator’s interface. While defining nodes and links data, the user still needs to use the standard array indexes.__ The default value is *0*.
* @property {number} link_min_arc - Number, minimal curvature of the arc when the links have a curved shape, for example when a link connects the left sides of both nodes. The default value is *5*.
* @property {number} link_arc_iterated_increase - Number, determines by how many pixels should increase the arc of the curved links when these are stacked. The default value is *5*.
* @property {Object} lines_style_object - An object that defines styles of the lines between the columns. PlotCreator will recognize all properties that are also defined in the default object and only overwrite those defined by the user. The default values are: *{stroke: 'red', 'stroke-width': 2, 'stroke-opacity': 0.35, 'stroke-dasharray': '5,5'}*.
* @property {Object} column_names_style_object - An object that defines styles of the column names. PlotCreator will recognize all properties that are also defined in the default object and only overwrite those defined by the user. The default values are: *{'font-size':'15px', color:'red', opacity:0.50,'font-weight':'bold'}*.
* @property {CallableFunction} on_node_click_function - Function that will be executed after a node is clicked. PlotCreator will try to pass four arguments to it: *node_info*, *node_data_reference*, *node_element* and *event*.
* @property {CallableFunction} on_link_click_function - Function that will be executed after a link is clicked. PlotCreator will try to pass four arguments to it: *link_info*, *link_data_reference*, *link_element* and *event*.
* @property {CallableFunction} on_node_hover_function - Function that will be executed after a node is hovered. PlotCreator will try to pass four arguments to it: *node_info*, *node_data_reference*, *node_element* and *event*, same as in *on_node_click_function*. **Important: the return value of this function will be set as info bubble's inner HTML**.
* @property {CallableFunction} on_link_hover_function - Function that will be executed after a link is hovered. PlotCreator will try to pass four arguments to it: *link_info*, *link_data_reference*, *link_element* and *event*, same as in *on_link_click_function*. **Important: the return value of this function will be set as info bubble's inner HTML**.
* @property {string} hover_node_cursor - String, appearance of the cursor when a node is being hovered. The default value is *'pointer'*.
* @property {string} hover_link_cursor - String, appearance of the cursor when a link is being hovered. The default value is *'help'*.
* @property {string} grabbing_node_cursor - String, appearance of the cursor when a node is being grabbed. The default value is *'grabbing'*.
*
*/
/**
* Main class to create and manage the Sankey Plot.
* # SanKEY.js
* (c) 2021 Krzysztof Zdąbłasz, GPL 3.0 License, https://github.com/Krzysiekzd/
*
* @param {HTMLElement} dom_container - DOM element in which the plot will be created. Creating a plot inside it may override some of its default styles. In particular, it will set the *overflow* to '*auto*'.
* @param {single_node_data[][]} nodes_data - Nodes data.
* @param {single_link_data[]} links_data - Links data.
* @param {number} plot_width - Width of the plot in pixels.
* @param {number} plot_height - Height of the plot in pixels.
* @param {number} first_column - Index of first column to be shown.
* @param {number} last_column - Index of first column that won't be shown.
* @param {settings} settings - Object with additional plot settings.
*/
#plot_width;
#plot_height;
#vertical_gap_between_nodes;
#node_percent_of_column_width;
#link_min_arc;
#link_arc_iterated_increase;
#first_column;
#last_column;
#show_column_lines;
#show_column_names;
#node_move_y;
#linear_gradient_links;
#show_links_out_of_range;
#plot_background_color;
#default_links_color;
#default_nodes_color;
#default_links_opacity;
#default_gradient_links_opacity;
#default_sublinks_color;
#default_sublinks_opacity;
#hover_node_cursor;
#hover_link_cursor;
#grabbing_node_cursor;
#on_node_click_function;
#on_link_click_function;
#on_node_hover_function;
#on_link_hover_function;
#label_colors_object;
lines_style_object;
column_names_style_object;
#column_names;
#start_node_count_from;
#start_column_count_from;
nodes_data;
links_data_structure;
nodes_data_structure;
#dom_container;
#longest_link_length;
#last_column_width;
sankey_plot;
constructor(
dom_container,
nodes_data,
links_data,
plot_width,
plot_height,
first_column,
last_column,
settings = {}
) {
// REQUIRED ARGUMENTS
this.#dom_container = document.createElement("div");
dom_container.appendChild(this.#dom_container);
this.#dom_container.setAttribute("id", "sankey_plot_auto_container");
this.#dom_container.style.overflow = "auto";
this.#dom_container.classList.add("noselect");
this.nodes_data = nodes_data;
this.links_data_structure = links_data;
this.#plot_width = plot_width;
this.#plot_height = plot_height;
this.#first_column = first_column;
this.#last_column = last_column;
// OPTIONAL ARGUMENTS
const default_settings = {
vertical_gap_between_nodes: 0.7,
node_percent_of_column_width: 0.3,
show_column_lines: true,
show_column_names: true,
show_links_out_of_range: true,
node_move_y: true,
linear_gradient_links: true,
link_min_arc: 5,
link_arc_iterated_increase: 5,
plot_background_color: "#f5ecec",
default_links_color: "blue",
default_nodes_color: "grey",
default_links_opacity: 0.25,
default_gradient_links_opacity: 0.43,
default_sublinks_color: "red",
default_sublinks_opacity: 0.8,
label_colors_object: {},
column_names: undefined,
start_node_count_from: 0,
start_column_count_from: 0,
on_node_click_function: undefined,
on_link_click_function: undefined,
on_node_hover_function: (
node_info,
_node_data_reference,
_node_element,
_event
) => {
return `${node_info["label"]}`;
},
on_link_hover_function: (
link_info,
_link_data_reference,
_link_element,
_event
) => {
return `From: (column - ${link_info["from_column"]}, node - ${link_info["from_node"]}, label - "${link_info["from_label"]}") To: (column - ${link_info["to_column"]}, node - ${link_info["to_node"]}, label - "${link_info["to_label"]}") Value: ${link_info["value"]}`;
},
hover_node_cursor: "pointer",
hover_link_cursor: "help",
grabbing_node_cursor: "grabbing",
};
Object.assign(default_settings, settings);
// define private fields
this.#vertical_gap_between_nodes =
default_settings.vertical_gap_between_nodes;
this.#node_percent_of_column_width =
default_settings.node_percent_of_column_width;
this.#show_column_lines = default_settings.show_column_lines;
this.#show_column_names = default_settings.show_column_names;
this.#show_links_out_of_range = default_settings.show_links_out_of_range;
this.#node_move_y = default_settings.node_move_y;
this.#linear_gradient_links = default_settings.linear_gradient_links;
this.#link_min_arc = default_settings.link_min_arc;
this.#link_arc_iterated_increase =
default_settings.link_arc_iterated_increase;
this.#plot_background_color = default_settings.plot_background_color;
this.#default_links_color = default_settings.default_links_color;
this.#default_nodes_color = default_settings.default_nodes_color;
this.#default_links_opacity = default_settings.default_links_opacity;
this.#default_gradient_links_opacity =
default_settings.default_gradient_links_opacity;
this.#default_sublinks_color = default_settings.default_sublinks_color;
this.#default_sublinks_opacity = default_settings.default_sublinks_opacity;
this.#label_colors_object = default_settings.label_colors_object;
this.#column_names = default_settings.column_names;
this.#start_node_count_from = default_settings.start_node_count_from;
this.#start_column_count_from = default_settings.start_column_count_from;
this.#on_node_click_function = default_settings.on_node_click_function;
this.#on_link_click_function = default_settings.on_link_click_function;
this.#on_node_hover_function = default_settings.on_node_hover_function;
this.#on_link_hover_function = default_settings.on_link_hover_function;
this.#hover_node_cursor = default_settings.hover_node_cursor;
this.#hover_link_cursor = default_settings.hover_link_cursor;
this.#grabbing_node_cursor = default_settings.grabbing_node_cursor;
// Correcting parsed arguments, styles objects parsed separately
this.#first_column -= this.#start_column_count_from;
this.#last_column -= this.#start_column_count_from;
// lines style definition
this.lines_style_object = {
stroke: "red",
"stroke-width": 2,
"stroke-opacity": 0.35,
"stroke-dasharray": "5,5",
};
if (settings.hasOwnProperty("lines_style_object")) {
Object.assign(this.lines_style_object, settings.lines_style_object); // writable
}
// column names style definition
this.column_names_style_object = {
"font-size": "15px",
color: "red",
opacity: 0.5,
"font-weight": "bold",
};
if (settings.hasOwnProperty("column_names_style_object")) {
Object.assign(
this.column_names_style_object,
settings["column_names_style_object"]
); // writable
}
// END OF PARSING ARGUMENTS
this.#longest_link_length = undefined;
this.nodes_data_structure = [];
this.#preprocessLinksData();
this.#sortLinks();
this.#prepareData();
this.#last_column_width =
this.#plot_width / (this.#last_column - this.#first_column); // width of column in last plot spawn, remembered to calculate shift or something, can't remember
this.sankey_plot = this.#setNewPlot();
}
#sortLinks() {
//sort by node order from
this.links_data_structure.sort((a, b) => {
return a["from"]["node"] - b["from"]["node"];
});
// sort by columns
this.links_data_structure.sort((a, b) => {
return a["from"]["column"] - b["from"]["column"];
});
// sort by node order to
this.links_data_structure.sort((a, b) => {
return a["to"]["node"] - b["to"]["node"];
});
// sort by link length
this.links_data_structure.sort((a, b) => {
return (
a["to"]["column"] -
a["from"]["column"] -
(b["to"]["column"] - b["from"]["column"])
);
});
// longest links are now last in the links_data_structure array
const last_link =
this.links_data_structure[this.links_data_structure.length - 1];
this.#longest_link_length =
last_link["to"]["column"] - last_link["from"]["column"];
}
#preprocessLinksData() {
// change or add linktypes and orientation info
for (const i in this.links_data_structure) {
const link = this.links_data_structure[i];
const from_column = link["from"]["column"];
const to_column = link["to"]["column"];
if (from_column === to_column) {
if (link["from"]["node"] === link["to"]["node"]) {
if (["LL", "RR"].includes(link["link_type"])) {
throw new Error(
"RR,LL LINKS CANNOT YET BE DEFINED BETWEEN THE SAME NODE"
);
} else if (
link["link_type"] === undefined ||
link["link_type"] === "LR" ||
link["link_type"] === "RL"
) {
link["link_type"] = "LR";
} else {
throw new Error(`"${link["link_type"]}" IS NOT A VALID LINK TYPE`);
}
} else {
throw new Error(
"LINKS CANNOT BE DEFINED BETWEEN NODES IN THE SAME COLUMN, UNLESS IT'S THE SAME NODE"
);
}
} else if (from_column > to_column) {
if (!link.hasOwnProperty("link_type")) {
link["link_type"] = "LR";
link["reversed"] = true;
const _ = link["from"];
link["from"] = link["to"];
link["to"] = _;
} else if (["LR", "RL", "LL", "RR"].includes(link["link_type"])) {
//reverse link type
link["link_type"] = link["link_type"][1] + link["link_type"][0];
link["reversed"] = true;
const _ = link["from"];
link["from"] = link["to"];
link["to"] = _;
} else {
throw new Error(`"${link["link_type"]}" IS NOT A VALID LINK TYPE`);
}
}
}
}
#prepareData() {
//////////////////////////////////////////////////////////////////////////////////////// NODE_DATA_STRUCTURE CREATE
for (const i in this.nodes_data) {
const column = [];
for (const j in this.nodes_data[i]) {
column.push({
properties_object: this.nodes_data[i][j],
height: 0,
y: 0,
horizontal_shift: 0,
vertical_shift: 0,
left_side_sum: 0,
right_side_sum: 0,
links_references: [],
});
}
this.nodes_data_structure.push(column);
}
//////////////////////////////////////////////////////////////////////////////////////// NODE_DATA_STRUCTURE FILL + checking for sublinks
for (const i in this.links_data_structure) {
const link = this.links_data_structure[i];
this.nodes_data_structure[link["from"]["column"]][link["from"]["node"]][
"links_references"
].push({
link_id: i,
second_node_column: link["to"]["column"],
second_node_position: link["to"]["node"],
});
// In case if the link connects the same node, we don't want to add it to the same 'links references' twice - it would cause bugs. That's why this if is here.
if (
!(
link["to"]["column"] === link["from"]["column"] &&
link["to"]["node"] === link["from"]["node"]
)
) {
this.nodes_data_structure[link["to"]["column"]][link["to"]["node"]][
"links_references"
].push({
link_id: i,
second_node_column: link["from"]["column"],
second_node_position: link["from"]["node"],
});
}
switch (link["link_type"]) {
case "LL":
this.nodes_data_structure[link["from"]["column"]][
link["from"]["node"]
]["left_side_sum"] += link["value"];
this.nodes_data_structure[link["to"]["column"]][link["to"]["node"]][
"left_side_sum"
] += link["value"];
break;
case "LR":
this.nodes_data_structure[link["from"]["column"]][
link["from"]["node"]
]["left_side_sum"] += link["value"];
this.nodes_data_structure[link["to"]["column"]][link["to"]["node"]][
"right_side_sum"
] += link["value"];
break;
case "RR":
this.nodes_data_structure[link["from"]["column"]][
link["from"]["node"]
]["right_side_sum"] += link["value"];
this.nodes_data_structure[link["to"]["column"]][link["to"]["node"]][
"right_side_sum"
] += link["value"];
break;
case "RL":
case undefined:
this.nodes_data_structure[link["from"]["column"]][
link["from"]["node"]
]["right_side_sum"] += link["value"];
this.nodes_data_structure[link["to"]["column"]][link["to"]["node"]][
"left_side_sum"
] += link["value"];
break;
default:
throw new Error(`${link["link_type"]} IS NOT A VALID LINK TYPE`);
}
}
//////////////////////////////////////////////////////////////////////////////////////// NODE_HEIGHT_UNIT AND SETTING (RELATIVE) NODES HIGHT
let max = 0;
const col_sums = [];
for (const i in this.nodes_data_structure) {
let current_column_sum = 0;
for (const j in this.nodes_data_structure[i]) {
const node = this.nodes_data_structure[i][j];
let height = 0;
node["right_side_sum"] > node["left_side_sum"]
? (height = node["right_side_sum"])
: (height = node["left_side_sum"]);
node["height"] = height;
if (height > max) {
max = height;
}
current_column_sum += height;
}
col_sums.push(current_column_sum);
}
const max_column_sum = Math.max.apply(null, col_sums);
this.node_height_unit =
((1 - this.#vertical_gap_between_nodes) * this.#plot_height) /
max_column_sum;
//////////////////////////////////////////////////////////////////////////////////////// SETTING (EXACT) NODES Y COORD AND (EXACT) NODES HEIGHT
for (const i in this.nodes_data_structure) {
const gaps = this.nodes_data_structure[i].length + 1;
const gap_height =
((this.#vertical_gap_between_nodes * this.#plot_height) /
this.node_height_unit +
(max_column_sum - col_sums[i])) /
gaps;
let height_used = gap_height;
for (const j in this.nodes_data_structure[i]) {
const node = this.nodes_data_structure[i][j];
node["y"] = height_used * this.node_height_unit;
height_used += node["height"];
node["height"] *= this.node_height_unit;
height_used += gap_height;
}
}
//////////////////////////////////////////////////////////////////////////////////////// FILL POSITION DATA IN LINKS
for (const column_index in this.nodes_data_structure) {
for (const node_index in this.nodes_data_structure[column_index]) {
const node = this.nodes_data_structure[column_index][node_index];
const left_side_links_normal = [];
const right_side_links_normal = [];
const left_side_links_special = [];
const right_side_links_special = [];
for (const link_index in node["links_references"]) {
const link =
this.links_data_structure[
node["links_references"][link_index]["link_id"]
];
switch (link["link_type"]) {
case "LL":
if (
node["links_references"][link_index]["second_node_column"] >
column_index
) {
left_side_links_special.push(link);
} else {
left_side_links_normal.push(link);
}
break;
case "LR":
if (
node["links_references"][link_index]["second_node_column"] >
column_index
) {
left_side_links_special.push(link);
} else if (
node["links_references"][link_index]["second_node_column"] ==
column_index
) {
left_side_links_special.push(link);
right_side_links_special.push(link);
} else {
right_side_links_special.push(link);
}
break;
case "RR":
if (
node["links_references"][link_index]["second_node_column"] >
column_index
) {
right_side_links_normal.push(link);
} else {
right_side_links_special.push(link);
}
break;
case "RL":
case undefined:
if (
node["links_references"][link_index]["second_node_column"] >
column_index
) {
right_side_links_normal.push(link);
} else {
left_side_links_normal.push(link);
}
break;
default:
throw new Error(`${link["link_type"]} IS NOT A VALID LINK TYPE`);
}
}
// after adding links to arrays
let left_side_occupied_height = 0;
for (const i in left_side_links_normal) {
const link = left_side_links_normal[i];
link["right_side_rel_to_node_height"] = left_side_occupied_height;
left_side_occupied_height += link["value"] * this.node_height_unit;
}
let right_side_occupied_height = 0;
for (const i in right_side_links_normal) {
const link = right_side_links_normal[i];
link["left_side_rel_to_node_height"] = right_side_occupied_height;
right_side_occupied_height += link["value"] * this.node_height_unit;
}
// SPECIAL
left_side_links_special.sort((a, b) => {
return b["to"]["node"] - a["to"]["node"];
}); // ;)
left_side_links_special.sort((a, b) => {
return b["to"]["column"] - a["to"]["column"];
}); // ;)
const node_height = node["height"];
let left_side_curve =
-this.#link_arc_iterated_increase + this.#link_min_arc;
let left_side_occupied_height_special = 0;
for (const i in left_side_links_special) {
const special_link =
left_side_links_special[left_side_links_special.length - 1 - i]; // reversed because of the arcs
const link_height = special_link["value"] * this.node_height_unit;
special_link["left_side_rel_to_node_height"] =
node_height - left_side_occupied_height_special - link_height;
left_side_occupied_height_special += link_height;
special_link["left_side_curve"] =
left_side_curve + this.#link_arc_iterated_increase;
left_side_curve += link_height + this.#link_arc_iterated_increase;
}
right_side_links_special.sort((a, b) => {
return b["from"]["node"] - a["from"]["node"];
}); //?
right_side_links_special.sort((a, b) => {
return a["from"]["column"] - b["from"]["column"];
}); //?
let right_side_curve =
-this.#link_arc_iterated_increase + this.#link_min_arc;
let right_side_occupied_height_special = 0;
for (const i in right_side_links_special) {
const special_link =
right_side_links_special[right_side_links_special.length - 1 - i]; // reversed because of the arcs
const link_height = special_link["value"] * this.node_height_unit;
special_link["right_side_rel_to_node_height"] =
node_height - right_side_occupied_height_special - link_height;
right_side_occupied_height_special += link_height;
special_link["right_side_curve"] =
right_side_curve + this.#link_arc_iterated_increase;
right_side_curve += link_height + this.#link_arc_iterated_increase;
}
}
}
}
#setNewPlot() {
this.#dom_container.replaceChildren();
return new SankeyPlot(
this.#dom_container,
this.nodes_data_structure,
this.links_data_structure,
this.#plot_width,
this.#plot_height,
this.#node_percent_of_column_width,
this.#first_column,
this.#last_column,
this.node_height_unit,
this.#longest_link_length,
this.#last_column_width,
this.#show_column_lines,
this.#show_column_names,
this.#node_move_y,
this.#linear_gradient_links,
this.#link_arc_iterated_increase,
this.#label_colors_object,
this.#plot_background_color,
this.#default_links_color,
this.#default_links_opacity,
this.#default_gradient_links_opacity,
this.#default_sublinks_color,
this.#default_sublinks_opacity,
this.lines_style_object,
this.#column_names,
this.column_names_style_object,
this.#default_nodes_color,
this.#start_node_count_from,
this.#start_column_count_from,
this.#show_links_out_of_range,
this.#on_node_click_function,
this.#on_link_click_function,
this.#on_node_hover_function,
this.#on_link_hover_function,
this.#hover_node_cursor,
this.#hover_link_cursor,
this.#grabbing_node_cursor
);
}
/**
* Changes current column range. Refreshes the plot. *First_column* and *last_column* are column indexes. *Note, that if the default *start_column_count_from* was changed,
* then the indexes here must be shifted accordingly.
* @param {number} first_column - Index of first column to be shown.
* @param {number} last_column - Index of first column that won't be shown.
* @returns {boolean} - Boolean. True if column range was changed successfully.
*/
changeColumnRange(first_column, last_column) {
if (
first_column < this.#start_column_count_from ||
last_column >
this.nodes_data_structure.length + this.#start_column_count_from ||
first_column >= last_column
) {
console.warn(
`CANNOT CHANGE COLUMN RANGE TO (${first_column},${last_column}).`
);
return false;
} else {
this.#first_column = first_column - this.#start_column_count_from;
this.#last_column = last_column - this.#start_column_count_from;
this.reloadPlot();
return true;
}
}
/**
* Plot refresh. Useful when the plot data is manually modified.
*/
reloadPlot() {
this.sankey_plot = undefined; //dont remove - may trigger garbage collector faster
this.sankey_plot = this.#setNewPlot();
}
/**
* Allows changing whether column names are being displayed. Refreshes the plot.
* @param {boolean} boolean
*/
columnNames(boolean) {
this.#show_column_names = boolean;
this.reloadPlot();
}
/**
* Allows changing whether lines between columns are being displayed. Refreshes the plot.
* @param {boolean} boolean
*/
columnLines(boolean) {
this.#show_column_lines = boolean;
this.reloadPlot();
}
/**
* Allows changing whether nodes can be moved vertically. Refreshes the plot.
* @param {boolean} boolean
*/
yMovement(boolean) {
this.#node_move_y = boolean;
this.reloadPlot();
}
/**
* Allows changing whether links have a gradient color. Refreshes the plot
* @param {boolean} boolean
*/
linearGradient(boolean) {
this.#linear_gradient_links = boolean;
this.reloadPlot();
}
/**
* Method that should be used when one wants to remove the plot from DOM and from the memory.
* *Note, that all references pointing to that object should also be removed*.
*/
removePlot() {
this.sankey_plot.clearData();
this.#dom_container.removeChild(this.sankey_plot.dom_node);
this.sankey_plot = undefined;
this.links_data_structure = undefined;
this.nodes_data_structure = undefined;
this.nodes_data = undefined;
this.#dom_container.remove();
}
/**
* Setter for "show_links_out_of_range" setting. Refreshes the plot.
*/
/**
* Setter for "show_links_out_of_range" setting. Refreshes the plot.
*/
setShowLinksOutOfRange(boolean) {
this.#show_links_out_of_range = boolean;
this.reloadPlot();
}
/**
* Setter for "label_colors_object" setting. Refreshes the plot.
*/
setLabelColorsObject(object) {
this.#label_colors_object = object;
this.reloadPlot();
}
/**
* Setter for "default_links_color" setting.
*/
setDefaultNodesColor(color) {
this.#default_nodes_color = color;
this.reloadPlot();
}
/**
* Setter for "default_links_color" setting. Refreshes the plot.
*/
setDefaultSublinksColor(color) {
this.#default_sublinks_color = color;
this.reloadPlot();
}
}
class SankeyPlot {
constructor(
dom_container,
nodes_data,
links_data,
plot_width,
plot_height,
nodes_width_percent,
first_column,
last_column,
node_height_unit,
longest_link_length,
last_column_width,
show_column_lines = true,
show_column_names = true,
node_move_y = true,
linear_gradient_links = true,
link_arc_iterated_increase = 5,
label_colors_object = {},
plot_background_color = "#f5ecec",
default_links_color = "blue",
default_links_opacity = 0.25,
default_gradient_links_opacity = 0.43,
default_sublinks_color = "red",
default_sublinks_opacity = 0.8,
line_definition_object = {
stroke: "red",
"stroke-width": 2,
"stroke-opacity": 0.35,
"stroke-dasharray": "5,5",
},
column_names = undefined,
column_names_style = {
"font-size": "15px",
color: "red",
opacity: 0.5,
"font-weight": "bold",
},
default_nodes_color = "grey",
start_node_count_from = 0,
start_column_count_from = 0,
show_links_out_of_range = true,
on_node_click_function = undefined,
on_link_click_function = undefined,
on_node_hover_function = undefined,
on_link_hover_function = undefined,
hover_node_cursor = "pointer",
hover_link_cursor = "help",
grabbing_node_cursor = "grabbing"
) {
this.dom_container = dom_container;
this.nodes_data_structure = nodes_data;
this.links_data = links_data;
this.plot_width = plot_width;
this.plot_height = plot_height;
this.nodes_width_percent = nodes_width_percent;
this.first_column = first_column;
this.last_column = last_column;
this.selected_node = undefined;
this.node_height_unit = node_height_unit;
this.longest_link_length = longest_link_length;
this.last_column_width = last_column_width;
this.column_width =
this.plot_width / (this.last_column - this.first_column);
this.node_move_y = node_move_y;
this.linear_gradient_links = linear_gradient_links;
this.link_arc_iterated_increase = link_arc_iterated_increase;
this.label_colors_object = label_colors_object;
this.plot_background_color = plot_background_color;
this.default_links_color = default_links_color;
this.default_links_opacity = default_links_opacity;
this.default_gradient_links_opacity = default_gradient_links_opacity;
this.default_sublinks_color = default_sublinks_color;
this.default_sublinks_opacity = default_sublinks_opacity;
this.line_definition_object = line_definition_object;
this.column_names = column_names;
this.column_names_style = column_names_style;
this.default_nodes_color = default_nodes_color;
this.start_node_count_from = start_node_count_from;
this.start_column_count_from = start_column_count_from;
this.show_links_out_of_range = show_links_out_of_range;
this.on_node_click_function = on_node_click_function;
this.on_link_click_function = on_link_click_function;
this.on_node_hover_function = on_node_hover_function;
this.on_link_hover_function = on_link_hover_function;
this.hover_node_cursor = hover_node_cursor;
this.hover_link_cursor = hover_link_cursor;
this.grabbing_node_cursor = grabbing_node_cursor;
this.node_info_div = undefined;
this.mouseovered_node = undefined;
this.link_info_div = undefined;
this.mouseovered_link = undefined;
this.#createDomNode();
this.#addEventListeners();
if (show_column_lines) {
this.#createLines();
}
if (show_column_names) {
this.#createColumnNames();
}
this.linear_gradient_colors_object = {};
this.#createNodes();
this.#createLinks();
}
#createDomNode() {
this.dom_node = document.createElementNS(
"http://www.w3.org/2000/svg",
"svg"
);
this.defs = document.createElementNS("http://www.w3.org/2000/svg", "defs");
this.dom_node.appendChild(this.defs);
set_attributes(this.dom_node, {
width: this.plot_width,
height: this.plot_height,
id: "sankey_field",
viewBox: `0 0 ${this.plot_width} ${this.plot_height}`,
});
this.dom_node.style.backgroundColor = this.plot_background_color;
this.dom_container.appendChild(this.dom_node);
}
#getNodeInfo(e) {
const selected_node =
this.nodes[e.target.getAttribute("column")][
e.target.getAttribute("position")
];
let node_column = selected_node.column;
let node_position = selected_node.position;
const node_data = this.nodes_data_structure[node_column][node_position];
const node_label = selected_node.label;
const node_height = Math.max(
node_data["left_side_sum"],
node_data["right_side_sum"]
);
const number_of_links = node_data["links_references"].length;
const left_side_sum = node_data["left_side_sum"];
const right_side_sum = node_data["right_side_sum"];
// counting left side ande right side links
let number_of_links_left = 0;
let number_of_links_right = 0;
for (const i in node_data["links_references"]) {
const link = this.links_data[node_data["links_references"][i]["link_id"]];
const second_node_col =
node_data["links_references"][i]["second_node_column"];
if (node_column > second_node_col) {
if (!link.hasOwnProperty("link_type")) {
number_of_links_left += 1;
} else if (link["link_type"][1] === "L") {
number_of_links_left += 1;
} else if (link["link_type"][1] === "R") {
number_of_links_right += 1;
}
} else if (node_column < second_node_col) {
if (!link.hasOwnProperty("link_type")) {
number_of_links_right += 1;
} else if (link["link_type"][0] === "L") {
number_of_links_left += 1;
} else if (link["link_type"][0] === "R") {
number_of_links_right += 1;
}
}
}
// end
if (this.column_names) {
node_column = this.column_names[node_column];
} else {
node_column += this.start_column_count_from;
}
node_position += this.start_node_count_from;
return {
label: node_label,
height: node_height,
number_of_links: number_of_links,
left_side_sum: left_side_sum,
right_side_sum: right_side_sum,
column: node_column,
position: node_position,
number_of_links_left: number_of_links_left,
number_of_links_right: number_of_links_right,
};
}
#getLinkInfo(e) {
const link_id = e.target.getAttribute("links_array_id");
const link_data = this.links_data[link_id];
let f_column = parseInt(link_data["from"]["column"]);
let t_column = parseInt(link_data["to"]["column"]);
let f_node = parseInt(link_data["from"]["node"]);
let t_node = parseInt(link_data["to"]["node"]);
if (link_data.hasOwnProperty("reversed")) {
let _ = f_column;
f_column = t_column;
t_column = _;
_ = f_node;
f_node = t_node;
t_node = _;
}
const f_label =
this.nodes_data_structure[f_column][f_node]["properties_object"]["label"];
const t_label =
this.nodes_data_structure[t_column][t_node]["properties_object"]["label"];
let value = link_data["value"];
// check if sublink
const sublink_index = e.target.getAttribute("sublink_index");
if (sublink_index) {
value = link_data["sublinks"][sublink_index]["value"];
}
f_node += this.start_node_count_from;
t_node += this.start_node_count_from;
if (this.column_names) {
f_column = this.column_names[f_column];
t_column = this.column_names[t_column];
} else {
f_column += this.start_column_count_from;
t_column += this.start_column_count_from;
}
return {
from_column: f_column,
to_column: t_column,
from_node: f_node,
to_node: t_node,
from_label: f_label,
to_label: t_label,
value: value,
sublink_data: sublink_index
? link_data["sublinks"][sublink_index]
: undefined,
};
}
#addEventListeners() {
//// MOUSE EVENT LISTENERS DEFINED BY USER
const is_mozilla = navigator.userAgent
.toLocaleLowerCase()