-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
Copy pathsigma.ts
1845 lines (1518 loc) · 56.7 KB
/
sigma.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
/**
* Sigma.js
* ========
* @module
*/
import Graph from "graphology-types";
import extend from "@yomguithereal/helpers/extend";
import Camera from "./core/camera";
import MouseCaptor from "./core/captors/mouse";
import QuadTree from "./core/quadtree";
import {
CameraState,
Coordinates,
Dimensions,
EdgeDisplayData,
Extent,
Listener,
MouseCoords,
NodeDisplayData,
PlainObject,
CoordinateConversionOverride,
TypedEventEmitter,
MouseInteraction,
} from "./types";
import {
createElement,
getPixelRatio,
createNormalizationFunction,
NormalizationFunction,
cancelFrame,
matrixFromCamera,
requestFrame,
validateGraph,
zIndexOrdering,
getMatrixImpact,
graphExtent,
} from "./utils";
import { edgeLabelsToDisplayFromNodes, LabelGrid } from "./core/labels";
import { Settings, validateSettings, resolveSettings } from "./settings";
import { INodeProgram } from "./rendering/webgl/programs/common/node";
import { IEdgeProgram } from "./rendering/webgl/programs/common/edge";
import TouchCaptor, { FakeSigmaMouseEvent } from "./core/captors/touch";
import { identity, multiplyVec2 } from "./utils/matrices";
import { doEdgeCollideWithPoint, isPixelColored } from "./utils/edge-collisions";
/**
* Constants.
*/
const X_LABEL_MARGIN = 150;
const Y_LABEL_MARGIN = 50;
/**
* Important functions.
*/
function applyNodeDefaults(settings: Settings, key: string, data: Partial<NodeDisplayData>): NodeDisplayData {
if (!data.hasOwnProperty("x") || !data.hasOwnProperty("y"))
throw new Error(
`Sigma: could not find a valid position (x, y) for node "${key}". All your nodes must have a number "x" and "y". Maybe your forgot to apply a layout or your "nodeReducer" is not returning the correct data?`,
);
if (!data.color) data.color = settings.defaultNodeColor;
if (!data.label && data.label !== "") data.label = null;
if (data.label !== undefined && data.label !== null) data.label = "" + data.label;
else data.label = null;
if (!data.size) data.size = 2;
if (!data.hasOwnProperty("hidden")) data.hidden = false;
if (!data.hasOwnProperty("highlighted")) data.highlighted = false;
if (!data.hasOwnProperty("forceLabel")) data.forceLabel = false;
if (!data.type || data.type === "") data.type = settings.defaultNodeType;
if (!data.zIndex) data.zIndex = 0;
return data as NodeDisplayData;
}
function applyEdgeDefaults(settings: Settings, key: string, data: Partial<EdgeDisplayData>): EdgeDisplayData {
if (!data.color) data.color = settings.defaultEdgeColor;
if (!data.label) data.label = "";
if (!data.size) data.size = 0.5;
if (!data.hasOwnProperty("hidden")) data.hidden = false;
if (!data.hasOwnProperty("forceLabel")) data.forceLabel = false;
if (!data.type || data.type === "") data.type = settings.defaultEdgeType;
if (!data.zIndex) data.zIndex = 0;
return data as EdgeDisplayData;
}
/**
* Event types.
*/
export interface SigmaEventPayload {
event: MouseCoords;
preventSigmaDefault(): void;
}
export interface SigmaStageEventPayload extends SigmaEventPayload {}
export interface SigmaNodeEventPayload extends SigmaEventPayload {
node: string;
}
export interface SigmaEdgeEventPayload extends SigmaEventPayload {
edge: string;
}
export type SigmaStageEvents = {
[E in MouseInteraction as `${E}Stage`]: (payload: SigmaStageEventPayload) => void;
};
export type SigmaNodeEvents = {
[E in MouseInteraction as `${E}Node`]: (payload: SigmaNodeEventPayload) => void;
};
export type SigmaEdgeEvents = {
[E in MouseInteraction as `${E}Edge`]: (payload: SigmaEdgeEventPayload) => void;
};
export type SigmaAdditionalEvents = {
// Lifecycle events
beforeRender(): void;
afterRender(): void;
resize(): void;
kill(): void;
// Additional node events
enterNode(payload: SigmaNodeEventPayload): void;
leaveNode(payload: SigmaNodeEventPayload): void;
// Additional edge events
enterEdge(payload: SigmaEdgeEventPayload): void;
leaveEdge(payload: SigmaEdgeEventPayload): void;
};
export type SigmaEvents = SigmaStageEvents & SigmaNodeEvents & SigmaEdgeEvents & SigmaAdditionalEvents;
/**
* Main class.
*
* @constructor
* @param {Graph} graph - Graph to render.
* @param {HTMLElement} container - DOM container in which to render.
* @param {object} settings - Optional settings.
*/
export default class Sigma<GraphType extends Graph = Graph> extends TypedEventEmitter<SigmaEvents> {
private settings: Settings;
private graph: GraphType;
private mouseCaptor: MouseCaptor;
private touchCaptor: TouchCaptor;
private container: HTMLElement;
private elements: PlainObject<HTMLCanvasElement> = {};
private canvasContexts: PlainObject<CanvasRenderingContext2D> = {};
private webGLContexts: PlainObject<WebGLRenderingContext> = {};
private activeListeners: PlainObject<Listener> = {};
private quadtree: QuadTree = new QuadTree();
private labelGrid: LabelGrid = new LabelGrid();
private nodeDataCache: Record<string, NodeDisplayData> = {};
private edgeDataCache: Record<string, EdgeDisplayData> = {};
private nodesWithForcedLabels: string[] = [];
private edgesWithForcedLabels: string[] = [];
private nodeExtent: { x: Extent; y: Extent } = { x: [0, 1], y: [0, 1] };
private matrix: Float32Array = identity();
private invMatrix: Float32Array = identity();
private correctionRatio = 1;
private customBBox: { x: Extent; y: Extent } | null = null;
private normalizationFunction: NormalizationFunction = createNormalizationFunction({
x: [0, 1],
y: [0, 1],
});
// Cache:
private cameraSizeRatio = 1;
// Starting dimensions and pixel ratio
private width = 0;
private height = 0;
private pixelRatio = getPixelRatio();
// State
private displayedLabels: Set<string> = new Set();
private highlightedNodes: Set<string> = new Set();
private hoveredNode: string | null = null;
private hoveredEdge: string | null = null;
private renderFrame: number | null = null;
private renderHighlightedNodesFrame: number | null = null;
private needToProcess = false;
private needToSoftProcess = false;
private checkEdgesEventsFrame: number | null = null;
// Programs
private nodePrograms: { [key: string]: INodeProgram } = {};
private nodeHoverPrograms: { [key: string]: INodeProgram } = {};
private edgePrograms: { [key: string]: IEdgeProgram } = {};
private camera: Camera;
constructor(graph: GraphType, container: HTMLElement, settings: Partial<Settings> = {}) {
super();
// Resolving settings
this.settings = resolveSettings(settings);
// Validating
validateSettings(this.settings);
validateGraph(graph);
if (!(container instanceof HTMLElement)) throw new Error("Sigma: container should be an html element.");
// Properties
this.graph = graph;
this.container = container;
// Initializing contexts
this.createWebGLContext("edges", { preserveDrawingBuffer: true });
this.createCanvasContext("edgeLabels");
this.createWebGLContext("nodes");
this.createCanvasContext("labels");
this.createCanvasContext("hovers");
this.createWebGLContext("hoverNodes");
this.createCanvasContext("mouse");
// Blending
for (const key in this.webGLContexts) {
const gl = this.webGLContexts[key];
gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
gl.enable(gl.BLEND);
}
// Loading programs
for (const type in this.settings.nodeProgramClasses) {
const NodeProgramClass = this.settings.nodeProgramClasses[type];
this.nodePrograms[type] = new NodeProgramClass(this.webGLContexts.nodes, this);
let NodeHoverProgram = NodeProgramClass;
if (type in this.settings.nodeHoverProgramClasses) {
NodeHoverProgram = this.settings.nodeHoverProgramClasses[type];
}
this.nodeHoverPrograms[type] = new NodeHoverProgram(this.webGLContexts.hoverNodes, this);
}
for (const type in this.settings.edgeProgramClasses) {
const EdgeProgramClass = this.settings.edgeProgramClasses[type];
this.edgePrograms[type] = new EdgeProgramClass(this.webGLContexts.edges, this);
}
// Initial resize
this.resize();
// Initializing the camera
this.camera = new Camera();
// Binding camera events
this.bindCameraHandlers();
// Initializing captors
this.mouseCaptor = new MouseCaptor(this.elements.mouse, this);
this.touchCaptor = new TouchCaptor(this.elements.mouse, this);
// Binding event handlers
this.bindEventHandlers();
// Binding graph handlers
this.bindGraphHandlers();
// Trigger eventual settings-related things
this.handleSettingsUpdate();
// Processing data for the first time & render
this.process();
this.render();
}
/**---------------------------------------------------------------------------
* Internal methods.
**---------------------------------------------------------------------------
*/
/**
* Internal function used to create a canvas element.
* @param {string} id - Context's id.
* @return {Sigma}
*/
private createCanvas(id: string): HTMLCanvasElement {
const canvas: HTMLCanvasElement = createElement<HTMLCanvasElement>(
"canvas",
{
position: "absolute",
},
{
class: `sigma-${id}`,
},
);
this.elements[id] = canvas;
this.container.appendChild(canvas);
return canvas;
}
/**
* Internal function used to create a canvas context and add the relevant
* DOM elements.
*
* @param {string} id - Context's id.
* @return {Sigma}
*/
private createCanvasContext(id: string): this {
const canvas = this.createCanvas(id);
const contextOptions = {
preserveDrawingBuffer: false,
antialias: false,
};
this.canvasContexts[id] = canvas.getContext("2d", contextOptions) as CanvasRenderingContext2D;
return this;
}
/**
* Internal function used to create a canvas context and add the relevant
* DOM elements.
*
* @param {string} id - Context's id.
* @param {object?} options - #getContext params to override (optional)
* @return {Sigma}
*/
private createWebGLContext(id: string, options?: { preserveDrawingBuffer?: boolean; antialias?: boolean }): this {
const canvas = this.createCanvas(id);
const contextOptions = {
preserveDrawingBuffer: false,
antialias: false,
...(options || {}),
};
let context;
// First we try webgl2 for an easy performance boost
context = canvas.getContext("webgl2", contextOptions);
// Else we fall back to webgl
if (!context) context = canvas.getContext("webgl", contextOptions);
// Edge, I am looking right at you...
if (!context) context = canvas.getContext("experimental-webgl", contextOptions);
this.webGLContexts[id] = context as WebGLRenderingContext;
return this;
}
/**
* Method binding camera handlers.
*
* @return {Sigma}
*/
private bindCameraHandlers(): this {
this.activeListeners.camera = () => {
this._scheduleRefresh();
};
this.camera.on("updated", this.activeListeners.camera);
return this;
}
/**
* Method that checks whether or not a node collides with a given position.
*/
private mouseIsOnNode({ x, y }: Coordinates, { x: nodeX, y: nodeY }: Coordinates, size: number): boolean {
return (
x > nodeX - size &&
x < nodeX + size &&
y > nodeY - size &&
y < nodeY + size &&
Math.sqrt(Math.pow(x - nodeX, 2) + Math.pow(y - nodeY, 2)) < size
);
}
/**
* Method that returns all nodes in quad at a given position.
*/
private getQuadNodes(position: Coordinates): string[] {
const mouseGraphPosition = this.viewportToFramedGraph(position);
return this.quadtree.point(mouseGraphPosition.x, 1 - mouseGraphPosition.y);
}
/**
* Method that returns the closest node to a given position.
*/
private getNodeAtPosition(position: Coordinates): string | null {
const { x, y } = position;
const quadNodes = this.getQuadNodes(position);
// We will hover the node whose center is closest to mouse
let minDistance = Infinity,
nodeAtPosition = null;
for (let i = 0, l = quadNodes.length; i < l; i++) {
const node = quadNodes[i];
const data = this.nodeDataCache[node];
const nodePosition = this.framedGraphToViewport(data);
const size = this.scaleSize(data.size);
if (!data.hidden && this.mouseIsOnNode(position, nodePosition, size)) {
const distance = Math.sqrt(Math.pow(x - nodePosition.x, 2) + Math.pow(y - nodePosition.y, 2));
// TODO: sort by min size also for cases where center is the same
if (distance < minDistance) {
minDistance = distance;
nodeAtPosition = node;
}
}
}
return nodeAtPosition;
}
/**
* Method binding event handlers.
*
* @return {Sigma}
*/
private bindEventHandlers(): this {
// Handling window resize
this.activeListeners.handleResize = () => {
this.needToSoftProcess = true;
this._scheduleRefresh();
};
window.addEventListener("resize", this.activeListeners.handleResize);
// Handling mouse move
this.activeListeners.handleMove = (e: MouseCoords): void => {
const baseEvent = {
event: e,
preventSigmaDefault(): void {
e.preventSigmaDefault();
},
};
const nodeToHover = this.getNodeAtPosition(e);
if (nodeToHover && this.hoveredNode !== nodeToHover && !this.nodeDataCache[nodeToHover].hidden) {
// Handling passing from one node to the other directly
if (this.hoveredNode) this.emit("leaveNode", { ...baseEvent, node: this.hoveredNode });
this.hoveredNode = nodeToHover;
this.emit("enterNode", { ...baseEvent, node: nodeToHover });
this.scheduleHighlightedNodesRender();
return;
}
// Checking if the hovered node is still hovered
if (this.hoveredNode) {
const data = this.nodeDataCache[this.hoveredNode];
const pos = this.framedGraphToViewport(data);
const size = this.scaleSize(data.size);
if (!this.mouseIsOnNode(e, pos, size)) {
const node = this.hoveredNode;
this.hoveredNode = null;
this.emit("leaveNode", { ...baseEvent, node });
this.scheduleHighlightedNodesRender();
return;
}
}
if (this.settings.enableEdgeHoverEvents === true) {
this.checkEdgeHoverEvents(baseEvent);
} else if (this.settings.enableEdgeHoverEvents === "debounce") {
if (!this.checkEdgesEventsFrame)
this.checkEdgesEventsFrame = requestFrame(() => {
this.checkEdgeHoverEvents(baseEvent);
this.checkEdgesEventsFrame = null;
});
}
};
// Handling click
const createMouseListener = (eventType: MouseInteraction): ((e: MouseCoords) => void) => {
return (e) => {
const baseEvent = {
event: e,
preventSigmaDefault(): void {
e.preventSigmaDefault();
},
};
const isFakeSigmaMouseEvent = (e.original as FakeSigmaMouseEvent).isFakeSigmaMouseEvent;
const nodeAtPosition = isFakeSigmaMouseEvent ? this.getNodeAtPosition(e) : this.hoveredNode;
if (nodeAtPosition)
return this.emit(`${eventType}Node`, {
...baseEvent,
node: nodeAtPosition,
});
if (eventType === "wheel" ? this.settings.enableEdgeWheelEvents : this.settings.enableEdgeClickEvents) {
const edge = this.getEdgeAtPoint(e.x, e.y);
if (edge) return this.emit(`${eventType}Edge`, { ...baseEvent, edge });
}
return this.emit(`${eventType}Stage`, baseEvent);
};
};
this.activeListeners.handleClick = createMouseListener("click");
this.activeListeners.handleRightClick = createMouseListener("rightClick");
this.activeListeners.handleDoubleClick = createMouseListener("doubleClick");
this.activeListeners.handleWheel = createMouseListener("wheel");
this.activeListeners.handleDown = createMouseListener("down");
this.mouseCaptor.on("mousemove", this.activeListeners.handleMove);
this.mouseCaptor.on("click", this.activeListeners.handleClick);
this.mouseCaptor.on("rightClick", this.activeListeners.handleRightClick);
this.mouseCaptor.on("doubleClick", this.activeListeners.handleDoubleClick);
this.mouseCaptor.on("wheel", this.activeListeners.handleWheel);
this.mouseCaptor.on("mousedown", this.activeListeners.handleDown);
// TODO
// Deal with Touch captor events
return this;
}
/**
* Method binding graph handlers
*
* @return {Sigma}
*/
private bindGraphHandlers(): this {
const graph = this.graph;
this.activeListeners.graphUpdate = () => {
this.needToProcess = true;
this._scheduleRefresh();
};
this.activeListeners.softGraphUpdate = () => {
this.needToSoftProcess = true;
this._scheduleRefresh();
};
this.activeListeners.dropNodeGraphUpdate = (e: { key: string }): void => {
delete this.nodeDataCache[e.key];
if (this.hoveredNode === e.key) this.hoveredNode = null;
this.activeListeners.graphUpdate();
};
this.activeListeners.dropEdgeGraphUpdate = (e: { key: string }): void => {
delete this.edgeDataCache[e.key];
if (this.hoveredEdge === e.key) this.hoveredEdge = null;
this.activeListeners.graphUpdate();
};
this.activeListeners.clearEdgesGraphUpdate = (): void => {
this.edgeDataCache = {};
this.hoveredEdge = null;
this.activeListeners.graphUpdate();
};
this.activeListeners.clearGraphUpdate = (): void => {
this.nodeDataCache = {};
this.hoveredNode = null;
this.activeListeners.clearEdgesGraphUpdate();
};
graph.on("nodeAdded", this.activeListeners.graphUpdate);
graph.on("nodeDropped", this.activeListeners.dropNodeGraphUpdate);
graph.on("nodeAttributesUpdated", this.activeListeners.softGraphUpdate);
graph.on("eachNodeAttributesUpdated", this.activeListeners.graphUpdate);
graph.on("edgeAdded", this.activeListeners.graphUpdate);
graph.on("edgeDropped", this.activeListeners.dropEdgeGraphUpdate);
graph.on("edgeAttributesUpdated", this.activeListeners.softGraphUpdate);
graph.on("eachEdgeAttributesUpdated", this.activeListeners.graphUpdate);
graph.on("edgesCleared", this.activeListeners.clearEdgesGraphUpdate);
graph.on("cleared", this.activeListeners.clearGraphUpdate);
return this;
}
/**
* Method used to unbind handlers from the graph.
*
* @return {undefined}
*/
private unbindGraphHandlers() {
const graph = this.graph;
graph.removeListener("nodeAdded", this.activeListeners.graphUpdate);
graph.removeListener("nodeDropped", this.activeListeners.dropNodeGraphUpdate);
graph.removeListener("nodeAttributesUpdated", this.activeListeners.softGraphUpdate);
graph.removeListener("eachNodeAttributesUpdated", this.activeListeners.graphUpdate);
graph.removeListener("edgeAdded", this.activeListeners.graphUpdate);
graph.removeListener("edgeDropped", this.activeListeners.dropEdgeGraphUpdate);
graph.removeListener("edgeAttributesUpdated", this.activeListeners.softGraphUpdate);
graph.removeListener("eachEdgeAttributesUpdated", this.activeListeners.graphUpdate);
graph.removeListener("edgesCleared", this.activeListeners.clearEdgesGraphUpdate);
graph.removeListener("cleared", this.activeListeners.clearGraphUpdate);
}
/**
* Method dealing with "leaveEdge" and "enterEdge" events.
*
* @return {Sigma}
*/
private checkEdgeHoverEvents(payload: SigmaEventPayload): this {
const edgeToHover = this.hoveredNode ? null : this.getEdgeAtPoint(payload.event.x, payload.event.y);
if (edgeToHover !== this.hoveredEdge) {
if (this.hoveredEdge) this.emit("leaveEdge", { ...payload, edge: this.hoveredEdge });
if (edgeToHover) this.emit("enterEdge", { ...payload, edge: edgeToHover });
this.hoveredEdge = edgeToHover;
}
return this;
}
/**
* Method looking for an edge colliding with a given point at (x, y). Returns
* the key of the edge if any, or null else.
*/
private getEdgeAtPoint(x: number, y: number): string | null {
const { edgeDataCache, nodeDataCache } = this;
// Check first that pixel is colored:
// Note that mouse positions must be corrected by pixel ratio to correctly
// index the drawing buffer.
if (!isPixelColored(this.webGLContexts.edges, x * this.pixelRatio, y * this.pixelRatio)) return null;
// Check for each edge if it collides with the point:
const { x: graphX, y: graphY } = this.viewportToGraph({ x, y });
// To translate edge thicknesses to the graph system, we observe by how much
// the length of a non-null edge is transformed to between the graph system
// and the viewport system:
let transformationRatio = 0;
this.graph.someEdge((key, _, sourceId, targetId, { x: xs, y: ys }, { x: xt, y: yt }) => {
if (edgeDataCache[key].hidden || nodeDataCache[sourceId].hidden || nodeDataCache[targetId].hidden) return false;
if (xs !== xt || ys !== yt) {
const graphLength = Math.sqrt(Math.pow(xt - xs, 2) + Math.pow(yt - ys, 2));
const { x: vp_xs, y: vp_ys } = this.graphToViewport({ x: xs, y: ys });
const { x: vp_xt, y: vp_yt } = this.graphToViewport({ x: xt, y: yt });
const viewportLength = Math.sqrt(Math.pow(vp_xt - vp_xs, 2) + Math.pow(vp_yt - vp_ys, 2));
transformationRatio = graphLength / viewportLength;
return true;
}
});
// If no non-null edge has been found, return null:
if (!transformationRatio) return null;
// Now we can look for matching edges:
const edges = this.graph.filterEdges((key, edgeAttributes, sourceId, targetId, sourcePosition, targetPosition) => {
if (edgeDataCache[key].hidden || nodeDataCache[sourceId].hidden || nodeDataCache[targetId].hidden) return false;
if (
doEdgeCollideWithPoint(
graphX,
graphY,
sourcePosition.x,
sourcePosition.y,
targetPosition.x,
targetPosition.y,
// Adapt the edge size to the zoom ratio:
(edgeDataCache[key].size * transformationRatio) / this.cameraSizeRatio,
)
) {
return true;
}
});
if (edges.length === 0) return null; // no edges found
// if none of the edges have a zIndex, selected the most recently created one to match the rendering order
let selectedEdge = edges[edges.length - 1];
// otherwise select edge with highest zIndex
let highestZIndex = -Infinity;
for (const edge of edges) {
const zIndex = this.graph.getEdgeAttribute(edge, "zIndex");
if (zIndex >= highestZIndex) {
selectedEdge = edge;
highestZIndex = zIndex;
}
}
return selectedEdge;
}
/**
* Method used to process the whole graph's data.
*
* @return {Sigma}
*/
private process(keepArrays = false): this {
const graph = this.graph;
const settings = this.settings;
const dimensions = this.getDimensions();
const nodeZExtent: [number, number] = [Infinity, -Infinity];
const edgeZExtent: [number, number] = [Infinity, -Infinity];
// Clearing the quad
this.quadtree.clear();
// Resetting the label grid
// TODO: it's probably better to do this explicitly or on resizes for layout and anims
this.labelGrid.resizeAndClear(dimensions, settings.labelGridCellSize);
// Clear the highlightedNodes
this.highlightedNodes = new Set();
// Computing extents
this.nodeExtent = graphExtent(graph);
// Resetting `forceLabel` indices
this.nodesWithForcedLabels = [];
this.edgesWithForcedLabels = [];
// NOTE: it is important to compute this matrix after computing the node's extent
// because #.getGraphDimensions relies on it
const nullCamera = new Camera();
const nullCameraMatrix = matrixFromCamera(
nullCamera.getState(),
this.getDimensions(),
this.getGraphDimensions(),
this.getSetting("stagePadding") || 0,
);
// Rescaling function
this.normalizationFunction = createNormalizationFunction(this.customBBox || this.nodeExtent);
const nodesPerPrograms: Record<string, number> = {};
let nodes = graph.nodes();
for (let i = 0, l = nodes.length; i < l; i++) {
const node = nodes[i];
// Node display data resolution:
// 1. First we get the node's attributes
// 2. We optionally reduce them using the function provided by the user
// Note that this function must return a total object and won't be merged
// 3. We apply our defaults, while running some vital checks
// 4. We apply the normalization function
// We shallow copy node data to avoid dangerous behaviors from reducers
let attr = Object.assign({}, graph.getNodeAttributes(node));
if (settings.nodeReducer) attr = settings.nodeReducer(node, attr);
const data = applyNodeDefaults(this.settings, node, attr);
nodesPerPrograms[data.type] = (nodesPerPrograms[data.type] || 0) + 1;
this.nodeDataCache[node] = data;
this.normalizationFunction.applyTo(data);
if (data.forceLabel) this.nodesWithForcedLabels.push(node);
if (this.settings.zIndex) {
if (data.zIndex < nodeZExtent[0]) nodeZExtent[0] = data.zIndex;
if (data.zIndex > nodeZExtent[1]) nodeZExtent[1] = data.zIndex;
}
}
for (const type in this.nodePrograms) {
if (!this.nodePrograms.hasOwnProperty(type)) {
throw new Error(`Sigma: could not find a suitable program for node type "${type}"!`);
}
if (!keepArrays) this.nodePrograms[type].allocate(nodesPerPrograms[type] || 0);
// We reset that count here, so that we can reuse it while calling the Program#process methods:
nodesPerPrograms[type] = 0;
}
// Handling node z-index
// TODO: z-index needs us to compute display data before hand
if (this.settings.zIndex && nodeZExtent[0] !== nodeZExtent[1])
nodes = zIndexOrdering<string>(nodeZExtent, (node: string): number => this.nodeDataCache[node].zIndex, nodes);
for (let i = 0, l = nodes.length; i < l; i++) {
const node = nodes[i];
const data = this.nodeDataCache[node];
this.quadtree.add(node, data.x, 1 - data.y, data.size / this.width);
if (typeof data.label === "string" && !data.hidden)
this.labelGrid.add(node, data.size, this.framedGraphToViewport(data, { matrix: nullCameraMatrix }));
const nodeProgram = this.nodePrograms[data.type];
if (!nodeProgram) throw new Error(`Sigma: could not find a suitable program for node type "${data.type}"!`);
nodeProgram.process(data, data.hidden, nodesPerPrograms[data.type]++);
// Save the node in the highlighted set if needed
if (data.highlighted && !data.hidden) this.highlightedNodes.add(node);
}
this.labelGrid.organize();
const edgesPerPrograms: Record<string, number> = {};
let edges = graph.edges();
for (let i = 0, l = edges.length; i < l; i++) {
const edge = edges[i];
// Edge display data resolution:
// 1. First we get the edge's attributes
// 2. We optionally reduce them using the function provided by the user
// Note that this function must return a total object and won't be merged
// 3. We apply our defaults, while running some vital checks
// We shallow copy edge data to avoid dangerous behaviors from reducers
let attr = Object.assign({}, graph.getEdgeAttributes(edge));
if (settings.edgeReducer) attr = settings.edgeReducer(edge, attr);
const data = applyEdgeDefaults(this.settings, edge, attr);
edgesPerPrograms[data.type] = (edgesPerPrograms[data.type] || 0) + 1;
this.edgeDataCache[edge] = data;
if (data.forceLabel && !data.hidden) this.edgesWithForcedLabels.push(edge);
if (this.settings.zIndex) {
if (data.zIndex < edgeZExtent[0]) edgeZExtent[0] = data.zIndex;
if (data.zIndex > edgeZExtent[1]) edgeZExtent[1] = data.zIndex;
}
}
for (const type in this.edgePrograms) {
if (!this.edgePrograms.hasOwnProperty(type)) {
throw new Error(`Sigma: could not find a suitable program for edge type "${type}"!`);
}
if (!keepArrays) this.edgePrograms[type].allocate(edgesPerPrograms[type] || 0);
// We reset that count here, so that we can reuse it while calling the Program#process methods:
edgesPerPrograms[type] = 0;
}
// Handling edge z-index
if (this.settings.zIndex && edgeZExtent[0] !== edgeZExtent[1])
edges = zIndexOrdering(edgeZExtent, (edge: string): number => this.edgeDataCache[edge].zIndex, edges);
for (let i = 0, l = edges.length; i < l; i++) {
const edge = edges[i];
const data = this.edgeDataCache[edge];
const extremities = graph.extremities(edge),
sourceData = this.nodeDataCache[extremities[0]],
targetData = this.nodeDataCache[extremities[1]];
const hidden = data.hidden || sourceData.hidden || targetData.hidden;
this.edgePrograms[data.type].process(sourceData, targetData, data, hidden, edgesPerPrograms[data.type]++);
}
for (const type in this.edgePrograms) {
const program = this.edgePrograms[type];
if (!keepArrays && typeof program.computeIndices === "function") program.computeIndices();
}
return this;
}
/**
* Method that backports potential settings updates where it's needed.
* @private
*/
private handleSettingsUpdate(): this {
this.camera.minRatio = this.settings.minCameraRatio;
this.camera.maxRatio = this.settings.maxCameraRatio;
this.camera.setState(this.camera.validateState(this.camera.getState()));
return this;
}
/**
* Method that decides whether to reprocess graph or not, and then render the
* graph.
*
* @return {Sigma}
*/
private _refresh(): this {
// Do we need to process data?
if (this.needToProcess) {
this.process();
} else if (this.needToSoftProcess) {
this.process(true);
}
// Resetting state
this.needToProcess = false;
this.needToSoftProcess = false;
// Rendering
this.render();
return this;
}
/**
* Method that schedules a `_refresh` call if none has been scheduled yet. It
* will then be processed next available frame.
*
* @return {Sigma}
*/
private _scheduleRefresh(): this {
if (!this.renderFrame) {
this.renderFrame = requestFrame(() => {
this._refresh();
this.renderFrame = null;
});
}
return this;
}
/**
* Method used to render labels.
*
* @return {Sigma}
*/
private renderLabels(): this {
if (!this.settings.renderLabels) return this;
const cameraState = this.camera.getState();
// Selecting labels to draw
const labelsToDisplay = this.labelGrid.getLabelsToDisplay(cameraState.ratio, this.settings.labelDensity);
extend(labelsToDisplay, this.nodesWithForcedLabels);
this.displayedLabels = new Set();
// Drawing labels
const context = this.canvasContexts.labels;
for (let i = 0, l = labelsToDisplay.length; i < l; i++) {
const node = labelsToDisplay[i];
const data = this.nodeDataCache[node];
// If the node was already drawn (like if it is eligible AND has
// `forceLabel`), we don't want to draw it again
// NOTE: we can do better probably
if (this.displayedLabels.has(node)) continue;
// If the node is hidden, we don't need to display its label obviously
if (data.hidden) continue;
const { x, y } = this.framedGraphToViewport(data);
// NOTE: we can cache the labels we need to render until the camera's ratio changes
const size = this.scaleSize(data.size);
// Is node big enough?
if (!data.forceLabel && size < this.settings.labelRenderedSizeThreshold) continue;
// Is node actually on screen (with some margin)
// NOTE: we used to rely on the quadtree for this, but the coordinates
// conversion make it unreliable and at that point we already converted
// to viewport coordinates and since the label grid already culls the
// number of potential labels to display this looks like a good
// performance compromise.
// NOTE: labelGrid.getLabelsToDisplay could probably optimize by not
// considering cells obviously outside of the range of the current
// view rectangle.
if (
x < -X_LABEL_MARGIN ||
x > this.width + X_LABEL_MARGIN ||
y < -Y_LABEL_MARGIN ||