-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.ts
2124 lines (1922 loc) · 75.3 KB
/
index.ts
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
/* TODO:
- mobiles fixes:
- reduce histogram height on small ?
- left todo with full histo:
- adjust time legends choices (all decades ?)
- add play timeline button
- clickable/selectable years url bound?
- homogeneize nodes sizes on time hover with small selection
- fix switch entity on unselected node does not recenter graph / recenter not applied on reloading on comics
- add star on family that focuses sentence in help
- check bad data marvel :
- http://gateway.marvel.com/v1/public/stories/186542/creators incoherent with https://www.marvel.com/comics/issue/84372/damage_control_2022_1
- check why Tiomothy Truman has no comic
- filter creator "Title"
- merge Curt Conners => Lizard
- check gweenpool & jeff missing
- http://localhost:3000/#/creators/?creator=Gail+Simone&comics=73419 should have Braga not Pacheco
- check why zoom on Spiderman 1602 only zooms on regular spiderman
- test new spatialization graphology
- test FA2 + louvain after sparsification
=> scraper comics as counter-truth? :
- select good creators fields
- take from scraping good image url if /clean within (example https://www.marvel.com/comics/issue/51567/captain_britain_and_the_mighty_defenders_2015_1)
- handle or drop missing dates?
- rebuild characters network from comics instead of stories, ex: Silk
- rebuild creators network from cleaned comics instead
- filter imprint marvel
- add cover artist in comics list, not in links used
=> one more check with takoyaki on authors/characters labels + readjust louvain after
- update screenshots + make gif
- update README
- auto data updates
- reorga dossiers
IDEAS:
- add more cases to legend
- build gif of all versions of the app
- improve touch tooltips :
- touchmove should follow across tooltips like histogram's
- better positioning away from the finger
- add urlrooting for modal? and play?
- install app button?
- swipe images with actual slide effect?
- handle old browsers where nodeImages are full black (ex: old iPad)
- handle alternate phone browsers where sigma does not work, ex Samsung Internet on Android 8
- test bipartite network between authors and characters filtered by category of author
- build data on movies and add a switch?
*/
import Papa from "papaparse";
import Graph from "graphology";
import { Sigma } from "sigma";
import { Coordinates } from "sigma/types";
import {
logDebug,
hasClass, addClass, rmClass, switchClass,
fixImage,
formatNumber, formatMonth,
lightenColor,
meanArray,
divWidth, divHeight,
isTouchDevice, webGLSupport,
rotatePosition,
uncompress,
buildComicsList
} from "./utils";
import {
startYear, curYear, totalYears,
picturesLoadingDelay, playComicsDelay,
creatorsRoles, clusters,
extraPalette,
sigmaSettings
} from "./settings";
/* -- Init global state -- */
let entity = "",
selectedNode = null,
selectedNodeType = null,
selectedNodeLabel = null,
sigmaDim = null,
renderer = null,
camera = null,
currentReducers = {nodes: null, edges: null},
animation = null,
clustersLayer = null,
resizeClusterLabels = function() {},
histograms = {
characters: {},
creators: {}
},
suggestions = [],
allSuggestions = [],
comicsReady = null,
comicsBarView = false,
shift = 0,
preventAutoScroll = false,
minComicLiHeight = 100,
hoveredComic = null,
selectedComic = null,
playing = null,
sortComics = "date";
const conf = {},
networks = {},
picturesRenderingDelay = {},
allComics = [],
allComicsMap = {},
allCharacters = {"-1": "missing info"},
allCreators = {"-1": "missing info"},
crossMap = {creators: {}, characters: {}},
charactersComics = {},
creatorsComics = {};
// Init global vars for each view variant
["creators", "characters"].forEach(e => {
picturesRenderingDelay[e] = picturesLoadingDelay;
networks[e] = {
communities: {},
counts: {},
clusters: {}
}
for (let cl in clusters[e]) {
networks[e].clusters[cl] = {};
for (let at in clusters[e][cl])
networks[e].clusters[cl][at] = clusters[e][cl][at];
}
});
// Useful DOM elements
const container = document.getElementById("sigma-container") as HTMLElement,
legendDiv = document.getElementById("legend") as HTMLElement,
controls = document.getElementById("controls") as HTMLElement,
loader = document.getElementById("loader") as HTMLElement,
loaderComics = document.getElementById("loader-comics") as HTMLElement,
loaderList = document.getElementById("loader-list") as HTMLElement,
helpButton = document.getElementById("help") as HTMLElement,
helpModal = document.getElementById("help-modal") as HTMLElement,
helpBox = document.getElementById("help-box") as HTMLElement,
modal = document.getElementById("modal") as HTMLElement,
modalImg = document.getElementById("modal-img") as HTMLImageElement,
modalImgMissing = document.getElementById("modal-img-missing") as HTMLImageElement,
modalNext = document.getElementById("modal-next") as HTMLButtonElement,
modalPrev = document.getElementById("modal-previous") as HTMLButtonElement,
modalPlay = document.getElementById("modal-play") as HTMLButtonElement,
modalPause = document.getElementById("modal-pause") as HTMLButtonElement,
comicsActions = document.getElementById("comics-actions") as HTMLButtonElement,
comicsNext = document.getElementById("comics-next") as HTMLButtonElement,
comicsPrev = document.getElementById("comics-prev") as HTMLButtonElement,
comicsPlay = document.getElementById("comics-play") as HTMLButtonElement,
comicsPause = document.getElementById("comics-pause") as HTMLButtonElement,
filterComics = document.getElementById("comics-filter") as HTMLButtonElement,
filterSearch = document.getElementById("filter-comics") as HTMLButtonElement,
filterInput = document.getElementById("filter-input") as HTMLButtonElement,
sortAlpha = document.getElementById("comics-sort-alpha") as HTMLButtonElement,
sortDate = document.getElementById("comics-sort-date") as HTMLButtonElement,
sideBar = document.getElementById("sidebar") as HTMLImageElement,
explanations = document.getElementById("explanations") as HTMLElement,
viewNodeButton = document.getElementById("view-node") as HTMLElement,
viewComicsButton = document.getElementById("view-comics") as HTMLElement,
orderSpan = document.getElementById("order") as HTMLElement,
nodeDetails = document.getElementById("node-details") as HTMLElement,
nodeLabel = document.getElementById("node-label") as HTMLElement,
nodeImg = document.getElementById("node-img") as HTMLImageElement,
nodeExtra = document.getElementById("node-extra") as HTMLElement,
histogramContainer = document.getElementById("histogram-container") as HTMLElement,
histogramTitle = document.getElementById("histogram-title") as HTMLElement,
histogramDiv = document.getElementById("histogram") as HTMLElement,
histogramHover = document.getElementById("histogram-hover") as HTMLElement,
histogramLegend = document.getElementById("histogram-legend") as HTMLElement,
histoTooltip = document.getElementById("histogram-tooltip") as HTMLElement,
comicsBar = document.getElementById("comics-bar") as HTMLImageElement,
comicsDiv = document.getElementById("comics") as HTMLImageElement,
comicsTitle = document.getElementById("comics-title") as HTMLElement,
comicsSubtitle = document.getElementById("comics-subtitle") as HTMLElement,
comicsList = document.getElementById("comics-list") as HTMLElement,
comicsCache = document.getElementById("comics-cache") as HTMLElement,
comicTitle = document.getElementById("comic-title") as HTMLLinkElement,
comicUrl = document.getElementById("comic-url") as HTMLLinkElement,
comicImg = document.getElementById("comic-img") as HTMLImageElement,
comicDesc = document.getElementById("comic-desc") as HTMLLinkElement,
comicEntities = document.querySelectorAll(".comic-entities") as NodeListOf<HTMLElement>,
comicCreators = document.getElementById("comic-creators") as HTMLElement,
comicCharacters = document.getElementById("comic-characters") as HTMLElement,
searchInput = document.getElementById("search-input") as HTMLInputElement,
searchIcon = document.getElementById("search-icon") as HTMLInputElement,
searchSuggestions = document.getElementById("suggestions") as HTMLDataListElement,
selectSuggestions = document.getElementById("suggestions-select") as HTMLSelectElement,
switchNodeType = document.getElementById("node-type-switch") as HTMLInputElement,
switchTypeLabel = document.getElementById("switch-type") as HTMLInputElement,
globalTooltip = document.getElementById("tooltip") as HTMLElement,
entitySpans = document.querySelectorAll(".entity") as NodeListOf<HTMLElement>,
charactersDetailsSpans = document.querySelectorAll(".characters-details") as NodeListOf<HTMLElement>,
creatorsDetailsSpans = document.querySelectorAll(".creators-details") as NodeListOf<HTMLElement>;
/* -- Load & prepare data -- */
function loadNetwork(ent, callback = null, waitForComics = false) {
if (networks[ent].loaded && (!waitForComics || comicsReady))
return callback ? setTimeout(callback, 0) : null;
if (callback || (waitForComics && !comicsReady))
showLoader();
if (networks[ent].loading) {
if (callback) {
const waiter = setInterval(() => {
if (!networks[ent].loaded || (waitForComics && !comicsReady))
return;
clearInterval(waiter);
return setTimeout(callback, 0);
}, 50);
}
return;
}
logDebug("LOAD NETWORK", {ent});
networks[ent].loading = true;
return fetch("./data/Marvel_" + ent + "_by_stories_full" + ".json.gz")
.then(res => res.arrayBuffer())
.then(content => buildNetwork(content, ent, callback, waitForComics));
}
function computeNodeSize(count) {
return (2/3 + Math.pow(count, 0.2)
* (entity === "characters" ? 1.75 : 1.25)
* 1.25) * sigmaDim / 1000;
};
function buildNetwork(networkData, ent, callback, waitForComics) {
logDebug("BUILD GRAPH", {ent});
const data = networks[ent];
// Parse pako zipped graphology serialized network JSON
uncompress(networkData, "inflate", graphData => {
data.graph = Graph.from(JSON.parse(graphData));
// Identify community ids of main hardcoded colors
data.graph.forEachNode((node, {x, y, label, community}) => {
for (var cluster in data.clusters)
if (data.clusters[cluster].match.indexOf(label) !== -1) {
if (ent === "creators") {
data.clusters[cluster].label = cluster;
data.clusters[cluster].id = cluster.toLowerCase().replace(/ .*$/, "");
if (!data.clusters[cluster].positions)
data.clusters[cluster].positions = [{x: x, y: y}];
else data.clusters[cluster].positions.push({x: x, y: y});
} else {
data.clusters[cluster].community = community;
data.communities[community] = data.clusters[cluster];
data.communities[community].label = cluster.replace(/([a-z&]) ([a-z])/ig, "$1 $2");
data.communities[community].community = community;
}
}
});
// Adjust nodes visual attributes for rendering (size, color)
data.graph.forEachNode((node, {label, stories, image, artist, writer, community}) => {
const artist_ratio = (ent === "creators" ? artist / (writer + artist) : null),
role = artist_ratio !== null
? (artist_ratio > 0.65
? "artist"
: (artist_ratio < 0.34
? "writer"
: "both"
)
) : null,
color = (ent === "characters"
? (data.communities[community] || {color: extraPalette[community % extraPalette.length]}).color
: creatorsRoles[role]
),
key = ent === "characters" ? community : role;
if (!data.counts[key])
data.counts[key] = 0;
data.counts[key]++;
const size = computeNodeSize(stories);
data.graph.mergeNodeAttributes(node, {
name: label,
label: null,
type: "circle",
image: /available/i.test(image) ? "" : image,
size: size,
color: lightenColor(color, 25),
borderColor: lightenColor(color, 25),
borderSize: sigmaDim / 1500,
haloSize: size * 5,
haloIntensity: 0.05 * Math.log(stories),
haloColor: lightenColor(color, 75)
});
if (ent === "creators")
allCreators[node] = label;
else allCharacters[node] = label;
});
if (ent === "creators") {
// Calculate positions of ages labels
for (const cluster in data.clusters) {
data.clusters[cluster].x = meanArray(data.clusters[cluster].positions.map(n => n.x));
data.clusters[cluster].y = meanArray(data.clusters[cluster].positions.map(n => n.y));
}
}
networks[ent].loaded = true;
if (callback) {
if (waitForComics && !comicsReady) {
const waiter = setInterval(() => {
if (waitForComics && !comicsReady)
return;
clearInterval(waiter);
return setTimeout(callback, 0);
}, 50);
} else return setTimeout(callback, 0);
}
});
}
function loadComics() {
logDebug("LOAD COMICS");
fetch("./data/Marvel_comics.csv.gz")
.then((res) => res.arrayBuffer())
.then((data) => uncompress(data, "ungzip", buildComics));
}
function buildComics(comicsData) {
Papa.parse(comicsData, {
worker: true,
header: true,
skipEmptyLines: "greedy",
step: function(c) {
c = c.data;
// Filter comics with missing date
if (!(new Date(c.date)).getFullYear())
return;
allComics.push(c);
allComicsMap[c.id] = c;
c.characters = c.characters.split("|").filter(x => x);
c.characters.forEach(ch => {
if (!charactersComics[ch])
charactersComics[ch] = [];
charactersComics[ch].push(c);
});
const artistsIds = {};
c.artists = c.artists.split("|").filter(x => x);
c.writers = c.writers.split("|").filter(x => x);
c.creators = c.writers.concat(c.artists);
c.artists.forEach(cr => {
if (!creatorsComics[cr])
creatorsComics[cr] = [];
creatorsComics[cr].push({...c, "role": "artist"});
artistsIds[cr] = creatorsComics[cr].length - 1;
});
c.writers.forEach(cr => {
if (!creatorsComics[cr])
creatorsComics[cr] = [];
if (artistsIds[cr])
creatorsComics[cr][artistsIds[cr]].role = "both";
else creatorsComics[cr].push({...c, "role": "writer"});
});
c.creators.forEach(cr => {
c.characters.forEach(ch => {
if (!crossMap.creators[ch])
crossMap.creators[ch] = {};
if (!crossMap.creators[ch][cr])
crossMap.creators[ch][cr] = 0;
crossMap.creators[ch][cr]++;
if (!crossMap.characters[cr])
crossMap.characters[cr] = {};
if (!crossMap.characters[cr][ch])
crossMap.characters[cr][ch] = 0;
crossMap.characters[cr][ch]++;
});
});
},
complete: function() {
comicsReady = true;
loaderComics.style.display = "none";
rmClass(viewComicsButton, "selected");
renderHistogram(selectedNode);
resize(true);
["creators", "characters"].forEach(
e => loadNetwork(e)
);
}
});
}
/* -- Graphs display -- */
function renderNetwork(shouldComicsBarView) {
logDebug("RENDER", {entity, selectedNode, selectedNodeType, selectedNodeLabel, shouldComicsBarView, comicsBarView, selectedComic});
const data = networks[entity];
// Feed communities size to explanations
orderSpan.innerHTML = formatNumber(data.graph.order);
if (entity === "creators") {
Object.keys(creatorsRoles).forEach(k => {
const role = document.getElementById(k + "-color");
role.style.color = lightenColor(creatorsRoles[k]);
role.innerHTML = k + " (" + formatNumber(data.counts[k]) + ")";
})
} else document.getElementById("clusters-legend").innerHTML = Object.keys(data.clusters)
.filter(k => !data.clusters[k].hide)
.map(k =>
'<b style="color: ' + lightenColor(data.clusters[k].color, 25) + '">'
+ k.split(" ").map(x => '<span>' + x + '</span>').join(" ")
+ ' (<span class="color">' + formatNumber(data.counts[data.clusters[k].community]) + '</span>)</b>'
).join(", ");
// Instantiate sigma:
const sigmaDims = container.getBoundingClientRect();
sigmaDim = Math.min(sigmaDims.height, sigmaDims.width);
if (!renderer) {
renderer = new Sigma(data.graph as any, container, sigmaSettings);
// insert the clusters layer underneath the hovers layer
clustersLayer = document.createElement("div");
clustersLayer.id = "clusters-layer";
clustersLayer.style.display = "none";
container.insertBefore(clustersLayer, document.getElementsByClassName("sigma-hovers")[0]);
// Clusters labels position needs to be updated on each render
renderer.on("afterRender", () => {
if (entity === "characters") return;
resizeClusterLabels();
});
// Add pointer on hovering nodes
renderer.on("enterNode", () => container.style.cursor = "pointer");
renderer.on("leaveNode", () => container.style.cursor = "default");
// Handle clicks on nodes
renderer.on("clickNode", (event) => clickNode(event.node));
renderer.on("clickStage", () => {
if (comicsBarView && selectedComic)
setURL(entity, selectedNodeLabel, selectedNodeType, "", sortComics);
else if (comicsBarView)
setURL(entity, selectedNodeLabel, selectedNodeType);
else setSearchQuery();
});
// Bind zoom manipulation buttons
camera = renderer.getCamera();
document.getElementById("zoom-in").onclick =
() => camera.animatedZoom({ duration: 600 });
document.getElementById("zoom-out").onclick =
() => camera.animatedUnzoom({ duration: 600 });
document.getElementById("zoom-reset").onclick =
() => camera.animatedReset({ duration: 300 });
} else {
renderer.setSetting("nodeReducer", (n, attrs) => attrs);
renderer.setSetting("edgeReducer", (edge, attrs) => attrs);
renderer.setGraph(data.graph);
}
renderer.setSetting("minCameraRatio", entity === "creators" ? 0.035 : 0.07);
// Render clusters labels layer on top of sigma for creators
if (entity === "creators") {
let clusterLabelsDoms = "";
for (const cluster in data.clusters) {
const c = data.clusters[cluster];
// adapt the position to viewport coordinates
const viewportPos = renderer.graphToViewport(c as Coordinates);
clusterLabelsDoms += '<div id="community-' + c.id + '" class="cluster-label" style="top: ' + viewportPos.y + 'px; left: ' + viewportPos.x + 'px; color: ' + c.color + '">' + c.label + '</div>';
}
clustersLayer.innerHTML = clusterLabelsDoms;
resizeClusterLabels = () => {
const sigmaDims = container.getBoundingClientRect();
clustersLayer.style.width = sigmaDims.width + "px";
for (const cluster in data.clusters) {
const c = data.clusters[cluster];
const clusterLabel = document.getElementById("community-" + c.id);
if (!clusterLabel) return;
// update position from the viewport
const viewportPos = renderer.graphToViewport(c as Coordinates);
if (viewportPos.x < 5 * cluster.length + 7 || viewportPos.x > sigmaDims.width - 5 * cluster.length - 7 || viewportPos.y > sigmaDims.height - 15)
clusterLabel.style.display = "none";
else {
clusterLabel.style.display = "block";
clusterLabel.style["min-width"] = (10 * cluster.length) + "px";
clusterLabel.style.top = viewportPos.y + 'px';
clusterLabel.style.left = viewportPos.x + 'px';
}
}
};
}
// Prepare list of nodes for search/select suggestions
allSuggestions = data.graph.nodes()
.map((node) => ({
node: node,
label: data.graph.getNodeAttribute(node, "name")
}))
.sort((a, b) => a.label < b.label ? -1 : 1);
function feedAllSuggestions() {
suggestions = allSuggestions.map(x => x);
}
feedAllSuggestions();
// Feed all nodes to select for touchscreens
selectSuggestions.innerHTML = "<option>search…</option>" + allSuggestions
.map((node) => "<option>" + node.label + "</option>")
.join("\n");
selectSuggestions.onchange = () => {
const idx = selectSuggestions.selectedIndex;
clickNode(idx ? allSuggestions[idx - 1].node : null, true, true);
};
function fillSuggestions() {
searchSuggestions.innerHTML = suggestions
.sort((a, b) => a.label < b.label ? -1 : 1)
.map((node) => "<option>" + node.label + "</option>")
.join("\n");
}
fillSuggestions();
// Setup nodes input search for web browsers
function setSearchQuery(query="") {
feedAllSuggestions();
if (searchInput.value !== query)
searchInput.value = query;
if (query) {
const lcQuery = query.toLowerCase();
suggestions = [];
data.graph.forEachNode((node, {label}) => {
if (label.toLowerCase().includes(lcQuery))
suggestions.push({node: node, label: label});
});
const suggestionsMatch = suggestions.filter(x => x.label === query);
if (suggestionsMatch.length === 1) {
clickNode(suggestionsMatch[0].node, true, true);
suggestions = [];
} else if (selectedNode) {
clickNode(null, true, true);
}
} else if (selectedNode) {
clickNode(null, true, true);
feedAllSuggestions();
}
fillSuggestions();
}
searchInput.oninput = () => {
setSearchQuery(searchInput.value || "");
};
searchInput.onblur = () => {
if (!selectedNode)
setSearchQuery();
};
// If a comic is selected we reload the list with it within it
function conditionalOpenComicsBar() {
if (shouldComicsBarView) {
if (!comicsBarView)
displayComics(selectedNode, true, true);
else if (selectedComic) {
selectedComic = allComicsMap[selectedComic] || selectedComic;
selectComic(selectedComic, true, true);
} else unselectComic();
}
hideLoader();
enableSwitchButtons();
}
const sigmaWidth = divWidth("sigma-container");
function finalizeGraph() {
renderer.setSetting("nodeReducer", (n, attrs) => attrs);
// If a node is selected we refocus it
if (selectedNodeLabel && selectedNodeType !== entity)
return loadNetwork(selectedNodeType, () => {
showCanvases();
clickNode(networks[selectedNodeType].graph.findNode((n, {label}) => label === selectedNodeLabel), false, true);
conditionalOpenComicsBar();
}, true);
const node = selectedNodeLabel
? data.graph.findNode((n, {label}) => label === selectedNodeLabel)
: null;
showCanvases();
clickNode(node, false, true);
conditionalOpenComicsBar();
}
resize();
showLoader();
// Zoom in graph on first init network
if (!data.rendered) {
camera.x = 0.5 + (shift / (2 * sigmaWidth));
camera.y = 0.5;
camera.ratio = Math.pow(1.5, 10);
camera.angle = 0;
showCanvases(false);
setTimeout(() => camera.animate(
{ratio: sigmaWidth / (sigmaWidth - shift)},
{duration: 1500},
() => {
data.graph.updateEachNodeAttributes((node, attrs) => ({
...attrs,
type: "image",
label: attrs.name
}), {attributes: ['type', 'label']});
finalizeGraph();
// Load comics data after first network rendered
if (comicsReady === null) {
comicsReady = false;
setTimeout(loadComics, 50);
}
}
), 50);
data.rendered = true;
} else finalizeGraph();
}
searchIcon.onclick = () => searchInput.focus();
function updateShift() {
shift = comicsBarView
? (comicsBar.getBoundingClientRect()["x"]
? divWidth("comics-bar")
: divWidth("sidebar") - divWidth("comics-bar")
) : 0;
}
// Center the camera on the selected node and its neighbors or a selected list of nodes
function centerNode(node, neighbors = null, force = true) {
// cancel pending centering
if (animation)
clearTimeout(animation);
// stop already running centering by requesting an idle animation
if (camera.isAnimated())
camera.animate(
camera.getState,
{duration: 0},
// then only compute positions to run new centering after a delay to filter out too close calls
() => animation = setTimeout(() => runCentering(node, neighbors, force), 50)
);
else animation = setTimeout(() => runCentering(node, neighbors, force), 0);
}
function runCentering(node, neighbors = null, force = true) {
logDebug("CENTER ON", {node, neighbors, force, shift, animation, animated: camera.isAnimated()});
const data = networks[entity];
if (!camera || (!node && !neighbors)) return;
if (!neighbors && data.graph.hasNode(node))
neighbors = data.graph.neighbors(node);
if (node && neighbors.indexOf(node) === -1)
neighbors.push(node);
if (!neighbors.length) {
hideLoader();
return;
}
let x0 = null, x1 = null, y0 = null, y1 = null;
neighbors.forEach(n => {
const pos = renderer.getNodeDisplayData(n);
if (!pos) return;
if (x0 === null || x0 > pos.x) x0 = pos.x;
if (x1 === null || x1 < pos.x) x1 = pos.x;
if (y0 === null || y0 > pos.y) y0 = pos.y;
if (y1 === null || y1 < pos.y) y1 = pos.y;
});
const minCorner = rotatePosition(renderer.framedGraphToViewport({x: x0, y: y0}), camera.angle),
maxCorner = rotatePosition(renderer.framedGraphToViewport({x: x1, y: y1}), camera.angle),
viewPortPosition = renderer.framedGraphToViewport({
x: (x0 + x1) / 2,
y: (y0 + y1) / 2
}),
sigmaDims = container.getBoundingClientRect();
// Handle comicsbar hiding part of the graph
updateShift();
sigmaDims.width -= shift;
// Evaluate required zoom ratio
let ratio = Math.min(
50 / camera.ratio,
Math.max(
1.5 * renderer.getSetting("minCameraRatio") / camera.ratio,
1.5 / Math.min(
sigmaDims.width / Math.abs(maxCorner.x - minCorner.x),
sigmaDims.height / Math.abs(minCorner.y - maxCorner.y)
)
)
);
// Evaluate acceptable window
const minWin = rotatePosition({
x: 0,
y: 0
}, camera.angle),
maxWin = rotatePosition({
x: sigmaDims.width,
y: sigmaDims.height
}, camera.angle),
minPos = rotatePosition({
x: sigmaDims.width / 6,
y: sigmaDims.height / 6
}, camera.angle),
maxPos = rotatePosition({
x: 5 * sigmaDims.width / 6,
y: 5 * sigmaDims.height / 6
}, camera.angle);
// Zoom on node only if force, if nodes outside full window, if nodes are too close together, or if more than 1 node and outside acceptable window
if (force ||
minCorner.x < minWin.x || maxCorner.x > maxWin.x || maxCorner.y < minWin.y || minCorner.y > maxWin.y ||
(ratio !== 0 && (ratio < 0.7 || ratio > 1.55)) ||
(neighbors.length > 1 && (minCorner.x < minPos.x || maxCorner.x > maxPos.x || maxCorner.y < minPos.y || minCorner.y > maxPos.y))
) {
viewPortPosition.x += ratio * shift / 2;
const newCam = renderer.viewportToFramedGraph(viewPortPosition);
newCam["ratio"] = camera.ratio * ratio;
camera.animate(
newCam,
{duration: 300},
hideLoader
);
} else hideLoader();
}
/* -- Graph interactions -- */
function clickNode(node, updateURL = true, center = false) {
logDebug("CLICK NODE", {selectedNode, selectedNodeType, selectedNodeLabel, node, updateURL, center, comicsBarView, selectedComic});
let data = networks[entity];
if (!data.graph || !renderer) return;
// Unhiglight previous node
const sameNode = (node === selectedNode);
if (selectedNode) {
if (data.graph.hasNode(selectedNode))
data.graph.setNodeAttribute(selectedNode, "highlighted", false)
}
stopPlayComics();
if (!node || !sameNode) {
nodeImg.src = "";
modalImg.src = "";
modalImgMissing.style.display = "none";
}
// Reset unselected node view
renderer.setSetting("nodeReducer", (n, attrs) => attrs);
renderer.setSetting("edgeReducer", (edge, attrs) => attrs);
if (!node) {
selectedNode = null;
selectedNodeType = null;
selectedNodeLabel = null;
nodeLabel.style.display = "none";
resize(true);
if (updateURL)
setURL(entity, null, null, selectedComic, sortComics);
selectSuggestions.selectedIndex = 0;
defaultSidebar();
if (comicsBarView && !sameNode)
displayComics(null, true);
return;
}
let relatedNodes = null,
comicsRatio = 0,
nodeEntity = entity;
if (selectedNodeType && selectedNodeType !== entity) {
if (data.graph.hasNode(node))
selectedNodeType = entity;
else {
nodeEntity = selectedNodeType;
data = networks[selectedNodeType];
relatedNodes = crossMap[entity][node] || {};
comicsRatio = allComics.length / (3 * (Object.values(relatedNodes).reduce((sum: number, cur: number) => sum + cur, 0) as number));
logDebug("KEEP NODE", {selectedNode, selectedNodeType, selectedNodeLabel, node, nodeEntity, relatedNodes, comicsRatio});
}
}
if (!data.graph.hasNode(node))
return setURL(entity, null, null, selectedComic, sortComics);
if (updateURL && !sameNode) {
legendDiv.style.display = "none";
setURL(entity, data.graph.getNodeAttribute(node, "label"), entity, selectedComic, sortComics);
}
// Fill sidebar with selected node's details
const attrs = data.graph.getNodeAttributes(node);
selectedNode = node;
selectedNodeLabel = attrs.label;
nodeLabel.style.display = "inline-block";
explanations.style.display = "none";
nodeDetails.style.display = "block";
if (!sameNode) {
nodeDetails.scrollTo(0, 0);
nodeLabel.innerHTML = attrs.label;
nodeImg.src = fixImage(attrs.image_url)
nodeImg.onclick = () => {
modalImg.src = fixImage(attrs.image_url);
stopPlayComics();
modal.style.display = "block";
modalPrev.style.opacity = "0";
modalNext.style.opacity = "0";
modalPlay.style.display = "none";
modalPause.style.display = "none";
};
}
resize(true);
nodeExtra.innerHTML = "";
if (attrs.description)
nodeExtra.innerHTML += "<p>" + attrs.description + "</p>";
nodeExtra.innerHTML += "<p>" +
(nodeEntity === "creators" ? "Credit" : "Account") + "ed " +
"in <b>" + attrs.stories + " stories</b> " +
(entity === nodeEntity
? "shared with<br/>" +
"<b>" + data.graph.degree(node) + " other " + nodeEntity + "</b>"
: (entity === "creators" ? "authored by<br/>" : "featuring<br/>") +
"<b>" + Object.keys(relatedNodes).length + " " + entity + "</b>"
) + "</p>";
if (entity === nodeEntity) {
// Display roles in stories for creators
if (entity === "creators") {
if (attrs.writer === 0 && attrs.artist)
nodeExtra.innerHTML += '<p>Always as <b style="color: ' + lightenColor(creatorsRoles.artist) + '">artist (' + attrs.artist + ')</b></p>';
else if (attrs.artist === 0 && attrs.writer)
nodeExtra.innerHTML += '<p>Always as <b style="color: ' + lightenColor(creatorsRoles.writer) + '">writer (' + attrs.writer + ')</b></p>';
else nodeExtra.innerHTML += '<p>Including <b style="color: ' + lightenColor(creatorsRoles.writer) + '">' + attrs.writer + ' as writer</b><br/>and <b style="color: ' + lightenColor(creatorsRoles.artist) + '">' + attrs.artist + " as artist</b></p>";
}
// Or communities if we have it for characters
else if (data.communities[attrs.community])
nodeExtra.innerHTML += '<p>Attached to the <b style="color: ' + lightenColor(data.communities[attrs.community].color, 25) + '">' + data.communities[attrs.community].label + '</b> <i>family</i></p>';
} else
nodeExtra.innerHTML += '<p>The size of the nodes reflects how often ' +
'the ' + entity + ' are ' +
(nodeEntity === "creators"
? "featured in stories authored by"
: "credited in stories featuring"
) + " " + selectedNodeLabel +
" within Marvel API's data.</p>";
if (attrs.url)
nodeExtra.innerHTML += '<p><a href="' + attrs.url + '" target="_blank">More on Marvel.com…</a></p>';
if (comicsReady)
renderHistogram(node);
selectSuggestions.selectedIndex = allSuggestions.map(x => x.label).indexOf(selectedNodeLabel) + 1;
const comicEntities = selectedComic && selectedComic[selectedNodeType || entity];
if (!comicsBarView || !(selectedComic && comicEntities && comicEntities.indexOf(node) !== -1)) {
if (relatedNodes === null) {
// Highlight clicked node, make it bigger and hide unconnected ones
data.graph.setNodeAttribute(node, "highlighted", true);
renderer.setSetting(
"nodeReducer", (n, attrs) => n === node
? { ...attrs,
zIndex: 2,
size: attrs.size * 1.75,
haloSize: attrs.size * 3.5,
haloIntensity: 0.75,
}
: data.graph.hasEdge(n, node)
? { ...attrs,
haloSize: attrs.size * 2,
haloIntensity: 0.65,
zIndex: 1
}
: { ...attrs,
zIndex: 0,
type: "circle",
haloIntensity: 0,
color: "#2A2A2A",
size: sigmaDim < 500 ? 1 : 2,
label: null
}
);
// Hide unrelated links and highlight, weight and color as the target the node's links
renderer.setSetting(
"edgeReducer", (edge, attrs) =>
data.graph.hasExtremity(edge, node)
? { ...attrs,
zIndex: 0,
color: lightenColor(data.graph.getNodeAttribute(data.graph.opposite(node, edge), 'color'), 25),
size: Math.max(sigmaDim < 500 ? 1 : 2, Math.log(data.graph.getEdgeAttribute(edge, 'weight')) * sigmaDim / 10000)
}
: { ...attrs,
zIndex: 0,
color: "#FFF",
hidden: true
}
);
} else {
// Display the alternate entity graph for the selected node
renderer.setSetting(
"nodeReducer", (n, attrs) => relatedNodes[n] !== undefined
? { ...attrs,
size: computeNodeSize(Math.pow(relatedNodes[n] * comicsRatio, 1.3)),
haloSize: 5 * computeNodeSize(Math.pow(relatedNodes[n] * comicsRatio, 1.3)),
haloIntensity: 0.05 * Math.log(relatedNodes[n] * comicsRatio),
zIndex: 2
}
: { ...attrs,
zIndex: 0,
type: "circle",
haloIntensity: 0,
color: "#2A2A2A",
size: sigmaDim < 500 ? 1 : 2,
label: null
}
);
renderer.setSetting(
"edgeReducer", (edge, attrs) =>
relatedNodes[networks[entity].graph.source(edge)] !== undefined &&
relatedNodes[networks[entity].graph.target(edge)] !== undefined
? { ...attrs,
zIndex: 0,
color: '#444',
size: 1
}
: { ...attrs,
zIndex: 0,
color: "#FFF",
hidden: true
}
);
}
}
if (comicsBarView) {
if (!sameNode)
displayComics(node, true);
else if (selectedComic)
selectComic(selectedComic, true, true);
}
if (!(comicsBarView && selectedComic) && (!updateURL || center)) {
if (relatedNodes)
centerNode(null, Object.keys(relatedNodes));
else centerNode(node);
} else hideLoader();
if (!sameNode)
comicsDiv.scrollTo(0, 0);
};
function getNodeComics(node) {
const comicsList = node === null
? allComics
: charactersComics[node] || creatorsComics[node] || [];
if (hasClass(filterComics, "selected") && filterInput.value)
return comicsList.filter(
c => c.title.toLowerCase().indexOf(filterInput.value.toLowerCase()) !== -1
);
return comicsList;
//.filter(c => (entity === "characters" && c.characters.length) || (entity === "creators" && c.creators.length));
}
function displayComics(node = null, autoReselect = false, resetTitle = true) {
logDebug("DISPLAY COMICS", {selectedNode, node, autoReselect, resetTitle, selectedComic, selectedNodeLabel, sortComics, filter: filterInput.value});
if (comicsBarView && node === selectedNode && !autoReselect && !resetTitle)
return selectedComic ? scrollComicsList() : null;
if (selectedNodeLabel && selectedNodeType && !selectedNode)
clickNode(node, false, false);
if (!selectedComic)
selectedComic = "";
comicsBarView = true;
comicsBar.style.transform = "scaleY(1)";
resize(true);
disableSwitchButtons();
comicsCache.style.display = "none";
setTimeout(() => resize(true), 300);
if (resetTitle && !comicsReady && selectedNodeLabel)
comicsTitle.innerHTML = "... comics" +
" " +
(selectedNodeType === "creators" ? "by" : "with") +
' <span class="red">' + selectedNodeLabel.replace(/ /g, " ") + '</span>';
comicsSubtitle.style.display = (selectedNode && creatorsComics[selectedNode] ? "inline-block" : "none");
comicsList.innerHTML = "";
if (!comicsReady) {
loaderList.style.display = "block";
const waiter = setInterval(() => {
if (!comicsReady)
return;
clearInterval(waiter);
return setTimeout(() => actuallyDisplayComics(node, autoReselect), 0);
}, 50);
} else actuallyDisplayComics(node, autoReselect);
}
function actuallyDisplayComics(node = null, autoReselect = false) {
const graph = networks[entity].graph,
comics = getNodeComics(node)
.sort(sortComics === "date" ? sortByDate : sortByTitle);