-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
sigma.ts
2118 lines (1800 loc) · 67.3 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 Camera from "./core/camera";
import MouseCaptor from "./core/captors/mouse";
import {
CameraState,
Coordinates,
Dimensions,
EdgeDisplayData,
Extent,
Listener,
MouseCoords,
NodeDisplayData,
PlainObject,
CoordinateConversionOverride,
TypedEventEmitter,
MouseInteraction,
RenderParams,
} from "./types";
import {
createElement,
getPixelRatio,
createNormalizationFunction,
NormalizationFunction,
cancelFrame,
matrixFromCamera,
requestFrame,
validateGraph,
zIndexOrdering,
getMatrixImpact,
graphExtent,
colorToIndex,
} from "./utils";
import { edgeLabelsToDisplayFromNodes, LabelGrid } from "./core/labels";
import { Settings, validateSettings, resolveSettings } from "./settings";
import { AbstractNodeProgram } from "./rendering/node";
import { AbstractEdgeProgram } from "./rendering/edge";
import TouchCaptor, { FakeSigmaMouseEvent } from "./core/captors/touch";
import { identity, multiplyVec2 } from "./utils/matrices";
import { extend } from "./utils/array";
import { getPixelColor } from "./utils/picking";
/**
* 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 pickingLayers: Set<string> = new Set();
private textures: PlainObject<WebGLTexture> = {};
private frameBuffers: PlainObject<WebGLFramebuffer> = {};
private activeListeners: PlainObject<Listener> = {};
private labelGrid: LabelGrid = new LabelGrid();
private nodeDataCache: Record<string, NodeDisplayData> = {};
private edgeDataCache: Record<string, EdgeDisplayData> = {};
// Indices to keep track of the index of the item inside programs
private nodeProgramIndex: Record<string, number> = {};
private edgeProgramIndex: Record<string, number> = {};
private nodesWithForcedLabels: Set<string> = new Set<string>();
private edgesWithForcedLabels: Set<string> = new Set<string>();
private nodeExtent: { x: Extent; y: Extent } = { x: [0, 1], y: [0, 1] };
private nodeZExtent: [number, number] = [Infinity, -Infinity];
private edgeZExtent: [number, number] = [Infinity, -Infinity];
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 graphToViewportRatio = 1;
private itemIDsIndex: Record<number, { type: "node" | "edge"; id: string }> = {};
private nodeIndices: Record<string, number> = {};
private edgeIndices: Record<string, number> = {};
// Starting dimensions and pixel ratio
private width = 0;
private height = 0;
private pixelRatio = getPixelRatio();
private pickingDownSizingRatio = 2 * this.pixelRatio;
// Graph State
private displayedNodeLabels: Set<string> = new Set();
private displayedEdgeLabels: Set<string> = new Set();
private highlightedNodes: Set<string> = new Set();
private hoveredNode: string | null = null;
private hoveredEdge: string | null = null;
// Internal states
private renderFrame: number | null = null;
private renderHighlightedNodesFrame: number | null = null;
private needToProcess = false;
private checkEdgesEventsFrame: number | null = null;
// Programs
private nodePrograms: { [key: string]: AbstractNodeProgram } = {};
private nodeHoverPrograms: { [key: string]: AbstractNodeProgram } = {};
private edgePrograms: { [key: string]: AbstractEdgeProgram } = {};
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", { picking: settings.enableEdgeEvents });
this.createCanvasContext("edgeLabels");
this.createWebGLContext("nodes", { picking: true });
this.createCanvasContext("labels");
this.createCanvasContext("hovers");
this.createWebGLContext("hoverNodes");
this.createCanvasContext("mouse");
// Initial resize
this.resize();
// Loading programs
for (const type in this.settings.nodeProgramClasses) {
const NodeProgramClass = this.settings.nodeProgramClasses[type];
this.nodePrograms[type] = new NodeProgramClass(this.webGLContexts.nodes, this.frameBuffers.nodes, this);
let NodeHoverProgram = NodeProgramClass;
if (type in this.settings.nodeHoverProgramClasses) {
NodeHoverProgram = this.settings.nodeHoverProgramClasses[type];
}
this.nodeHoverPrograms[type] = new NodeHoverProgram(this.webGLContexts.hoverNodes, null, this);
}
for (const type in this.settings.edgeProgramClasses) {
const EdgeProgramClass = this.settings.edgeProgramClasses[type];
this.edgePrograms[type] = new EdgeProgramClass(this.webGLContexts.edges, this.frameBuffers.edges, this);
}
// 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.refresh();
}
/**---------------------------------------------------------------------------
* 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 WebGL 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; hidden?: boolean; picking?: boolean },
): this {
const canvas = this.createCanvas(id);
if (options?.hidden) canvas.remove();
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);
const gl = context as WebGLRenderingContext;
this.webGLContexts[id] = gl;
// Blending:
gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
// Prepare frame buffer for picking layers:
if (options?.picking) {
this.pickingLayers.add(id);
const newFrameBuffer = gl.createFramebuffer();
if (!newFrameBuffer) throw new Error(`Sigma: cannot create a new frame buffer for layer ${id}`);
this.frameBuffers[id] = newFrameBuffer;
}
return this;
}
/**
* Method (re)binding WebGL texture (for picking).
*
* @return {Sigma}
*/
private resetWebGLTexture(id: string): this {
const gl = this.webGLContexts[id] as WebGLRenderingContext;
const frameBuffer = this.frameBuffers[id];
const currentTexture = this.textures[id];
if (currentTexture) gl.deleteTexture(currentTexture);
const pickingTexture = gl.createTexture();
gl.bindFramebuffer(gl.FRAMEBUFFER, frameBuffer);
gl.bindTexture(gl.TEXTURE_2D, pickingTexture);
gl.texImage2D(
gl.TEXTURE_2D,
0,
gl.RGBA,
this.width / this.pickingDownSizingRatio,
this.height / this.pickingDownSizingRatio,
0,
gl.RGBA,
gl.UNSIGNED_BYTE,
null,
);
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, pickingTexture, 0);
this.textures[id] = pickingTexture as WebGLTexture;
return this;
}
/**
* Method binding camera handlers.
*
* @return {Sigma}
*/
private bindCameraHandlers(): this {
this.activeListeners.camera = () => {
this.scheduleRender();
};
this.camera.on("updated", this.activeListeners.camera);
return this;
}
/**
* Method unbinding camera handlers.
*
* @return {Sigma}
*/
private unbindCameraHandlers(): this {
this.camera.removeListener("updated", this.activeListeners.camera);
return this;
}
/**
* Method that returns the closest node to a given position.
*/
private getNodeAtPosition(position: Coordinates): string | null {
const { x, y } = position;
const color = getPixelColor(this.webGLContexts.nodes, this.frameBuffers.nodes, x, y, this.pickingDownSizingRatio);
const index = colorToIndex(...color);
const itemAt = this.itemIDsIndex[index];
return itemAt && itemAt.type === "node" ? itemAt.id : null;
}
/**
* Method binding event handlers.
*
* @return {Sigma}
*/
private bindEventHandlers(): this {
// Handling window resize
this.activeListeners.handleResize = () => {
// need to call a refresh to rebuild the labelgrid
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) {
if (this.getNodeAtPosition(e) !== this.hoveredNode) {
const node = this.hoveredNode;
this.hoveredNode = null;
this.emit("leaveNode", { ...baseEvent, node });
this.scheduleHighlightedNodesRender();
return;
}
}
if (this.settings.enableEdgeEvents) {
this.checkEdgeHoverEvents(baseEvent);
}
};
// 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 (this.settings.enableEdgeEvents) {
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;
const LAYOUT_IMPACTING_FIELDS = new Set(["x", "y", "zIndex", "type"]);
this.activeListeners.eachNodeAttributesUpdatedGraphUpdate = (e: { hints?: { attributes?: string[] } }) => {
const updatedFields = e.hints?.attributes;
// we process all nodes
this.graph.forEachNode((node) => this.updateNode(node));
// if coord, type or zIndex have changed, we need to schedule a render
// (zIndex for the programIndex)
const layoutChanged = !updatedFields || updatedFields.some((f) => LAYOUT_IMPACTING_FIELDS.has(f));
this.refresh({ partialGraph: { nodes: graph.nodes() }, skipIndexation: !layoutChanged, schedule: true });
};
this.activeListeners.eachEdgeAttributesUpdatedGraphUpdate = (e: { hints?: { attributes?: string[] } }) => {
const updatedFields = e.hints?.attributes;
// we process all edges
this.graph.forEachEdge((edge) => this.updateEdge(edge));
const layoutChanged = updatedFields && ["zIndex", "type"].some((f) => updatedFields?.includes(f));
this.refresh({ partialGraph: { edges: graph.edges() }, skipIndexation: !layoutChanged, schedule: true });
};
// On add node, we add the node in indices and then call for a render
this.activeListeners.addNodeGraphUpdate = (payload: { key: string }): void => {
const node = payload.key;
// we process the node
this.addNode(node);
// schedule a render for the node
this.refresh({ partialGraph: { nodes: [node] }, skipIndexation: false, schedule: true });
};
// On update node, we update indices and then call for a render
this.activeListeners.updateNodeGraphUpdate = (payload: { key: string }): void => {
const node = payload.key;
// schedule a render for the node
this.refresh({ partialGraph: { nodes: [node] }, skipIndexation: false, schedule: true });
};
// On drop node, we remove the node from indices and then call for a refresh
this.activeListeners.dropNodeGraphUpdate = (payload: { key: string }): void => {
const node = payload.key;
// we process the node
this.removeNode(node);
// schedule a render for everything
this.refresh({ schedule: true });
};
// On add edge, we remove the edge from indices and then call for a refresh
this.activeListeners.addEdgeGraphUpdate = (payload: { key: string }): void => {
const edge = payload.key;
// we process the edge
this.addEdge(edge);
// schedule a render for the edge
this.refresh({ partialGraph: { edges: [edge] }, schedule: true });
};
// On update edge, we update indices and then call for a refresh
this.activeListeners.updateEdgeGraphUpdate = (payload: { key: string }): void => {
const edge = payload.key;
// schedule a repaint for the edge
this.refresh({ partialGraph: { edges: [edge] }, skipIndexation: false, schedule: true });
};
// On drop edge, we remove the edge from indices and then call for a refresh
this.activeListeners.dropEdgeGraphUpdate = (payload: { key: string }): void => {
const edge = payload.key;
// we process the edge
this.removeEdge(edge);
// schedule a render for all edges
this.refresh({ schedule: true });
};
// On clear edges, we clear the edge indices and then call for a refresh
this.activeListeners.clearEdgesGraphUpdate = (): void => {
// we clear the edge data structures
this.clearEdgeState();
this.clearEdgeIndices();
// schedule a render for all edges
this.refresh({ schedule: true });
};
// On graph clear, we clear indices and then call for a refresh
this.activeListeners.clearGraphUpdate = (): void => {
// clear graph state
this.clearEdgeState();
this.clearNodeState();
// clear graph indices
this.clearEdgeIndices();
this.clearNodeIndices();
// schedule a render for all
this.refresh({ schedule: true });
};
graph.on("nodeAdded", this.activeListeners.addNodeGraphUpdate);
graph.on("nodeDropped", this.activeListeners.dropNodeGraphUpdate);
graph.on("nodeAttributesUpdated", this.activeListeners.updateNodeGraphUpdate);
graph.on("eachNodeAttributesUpdated", this.activeListeners.eachNodeAttributesUpdatedGraphUpdate);
graph.on("edgeAdded", this.activeListeners.addEdgeGraphUpdate);
graph.on("edgeDropped", this.activeListeners.dropEdgeGraphUpdate);
graph.on("edgeAttributesUpdated", this.activeListeners.updateEdgeGraphUpdate);
graph.on("eachEdgeAttributesUpdated", this.activeListeners.eachEdgeAttributesUpdatedGraphUpdate);
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.addNodeGraphUpdate);
graph.removeListener("nodeDropped", this.activeListeners.dropNodeGraphUpdate);
graph.removeListener("nodeAttributesUpdated", this.activeListeners.updateNodeGraphUpdate);
graph.removeListener("eachNodeAttributesUpdated", this.activeListeners.eachNodeAttributesUpdatedGraphUpdate);
graph.removeListener("edgeAdded", this.activeListeners.addEdgeGraphUpdate);
graph.removeListener("edgeDropped", this.activeListeners.dropEdgeGraphUpdate);
graph.removeListener("edgeAttributesUpdated", this.activeListeners.updateEdgeGraphUpdate);
graph.removeListener("eachEdgeAttributesUpdated", this.activeListeners.eachEdgeAttributesUpdatedGraphUpdate);
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 color = getPixelColor(this.webGLContexts.edges, this.frameBuffers.edges, x, y, this.pickingDownSizingRatio);
const index = colorToIndex(...color);
const itemAt = this.itemIDsIndex[index];
return itemAt && itemAt.type === "edge" ? itemAt.id : null;
}
/**
* Method used to process the whole graph's data.
* - extent
* - normalizationFunction
* - compute node's coordinate
* - labelgrid
* - program data allocation
* @return {Sigma}
*/
private process(): this {
const graph = this.graph;
const settings = this.settings;
const dimensions = this.getDimensions();
//
// NODES
//
this.nodeExtent = graphExtent(this.graph);
this.normalizationFunction = createNormalizationFunction(this.customBBox || this.nodeExtent);
// 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(),
dimensions,
this.getGraphDimensions(),
this.getSetting("stagePadding") || 0,
);
// 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);
const nodesPerPrograms: Record<string, number> = {};
const nodeIndices: typeof this.nodeIndices = {};
const edgeIndices: typeof this.edgeIndices = {};
const itemIDsIndex: typeof this.itemIDsIndex = {};
let incrID = 1;
let nodes = graph.nodes();
// Do some indexation on the whole graph
for (let i = 0, l = nodes.length; i < l; i++) {
const node = nodes[i];
const data = this.nodeDataCache[node];
// Get initial coordinates
const attrs = graph.getNodeAttributes(node);
data.x = attrs.x;
data.y = attrs.y;
this.normalizationFunction.applyTo(data);
// labelgrid
if (typeof data.label === "string" && !data.hidden)
this.labelGrid.add(node, data.size, this.framedGraphToViewport(data, { matrix: nullCameraMatrix }));
// update count per program
nodesPerPrograms[data.type] = (nodesPerPrograms[data.type] || 0) + 1;
}
this.labelGrid.organize();
// Allocate memory to programs
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}"!`);
}
this.nodePrograms[type].reallocate(nodesPerPrograms[type] || 0);
// We reset that count here, so that we can reuse it while calling the Program#process methods:
nodesPerPrograms[type] = 0;
}
// Order nodes by zIndex before to add them to program
if (this.settings.zIndex && this.nodeZExtent[0] !== this.nodeZExtent[1])
nodes = zIndexOrdering<string>(
this.nodeZExtent,
(node: string): number => this.nodeDataCache[node].zIndex,
nodes,
);
// Add data to programs
for (let i = 0, l = nodes.length; i < l; i++) {
const node = nodes[i];
nodeIndices[node] = incrID;
itemIDsIndex[nodeIndices[node]] = { type: "node", id: node };
incrID++;
const data = this.nodeDataCache[node];
this.addNodeToProgram(node, nodeIndices[node], nodesPerPrograms[data.type]++);
}
//
// EDGES
//
const edgesPerPrograms: Record<string, number> = {};
let edges = graph.edges();
// Allocate memory to programs
for (let i = 0, l = edges.length; i < l; i++) {
const edge = edges[i];
const data = this.edgeDataCache[edge];
edgesPerPrograms[data.type] = (edgesPerPrograms[data.type] || 0) + 1;
}
// Order edges by zIndex before to add them to program
if (this.settings.zIndex && this.edgeZExtent[0] !== this.edgeZExtent[1])
edges = zIndexOrdering<string>(
this.edgeZExtent,
(edge: string): number => this.edgeDataCache[edge].zIndex,
edges,
);
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}"!`);
}
this.edgePrograms[type].reallocate(edgesPerPrograms[type] || 0);
// We reset that count here, so that we can reuse it while calling the Program#process methods:
edgesPerPrograms[type] = 0;
}
// Add data to programs
for (let i = 0, l = edges.length; i < l; i++) {
const edge = edges[i];
edgeIndices[edge] = incrID;
itemIDsIndex[edgeIndices[edge]] = { type: "edge", id: edge };
incrID++;
const data = this.edgeDataCache[edge];
this.addEdgeToProgram(edge, edgeIndices[edge], edgesPerPrograms[data.type]++);
}
this.itemIDsIndex = itemIDsIndex;
this.nodeIndices = nodeIndices;
this.edgeIndices = edgeIndices;
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 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.displayedNodeLabels = 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.displayedNodeLabels.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 ||
y > this.height + Y_LABEL_MARGIN
)
continue;
// Because displayed edge labels depend directly on actually rendered node
// labels, we need to only add to this.displayedNodeLabels nodes whose label
// is rendered.
// This makes this.displayedNodeLabels depend on viewport, which might become
// an issue once we start memoizing getLabelsToDisplay.
this.displayedNodeLabels.add(node);
const { nodeProgramClasses, defaultDrawNodeLabel } = this.settings;
const drawLabel = nodeProgramClasses[data.type].drawLabel || defaultDrawNodeLabel;
drawLabel(
context,
{
key: node,
...data,
size,
x,
y,
},
this.settings,
);
}
return this;
}
/**
* Method used to render edge labels, based on which node labels were
* rendered.
*
* @return {Sigma}
*/
private renderEdgeLabels(): this {
if (!this.settings.renderEdgeLabels) return this;
const context = this.canvasContexts.edgeLabels;
// Clearing
context.clearRect(0, 0, this.width, this.height);
const edgeLabelsToDisplay = edgeLabelsToDisplayFromNodes({
graph: this.graph,
hoveredNode: this.hoveredNode,
displayedNodeLabels: this.displayedNodeLabels,
highlightedNodes: this.highlightedNodes,
});
extend(edgeLabelsToDisplay, this.edgesWithForcedLabels);
const displayedLabels = new Set<string>();
for (let i = 0, l = edgeLabelsToDisplay.length; i < l; i++) {
const edge = edgeLabelsToDisplay[i],
extremities = this.graph.extremities(edge),
sourceData = this.nodeDataCache[extremities[0]],
targetData = this.nodeDataCache[extremities[1]],
edgeData = this.edgeDataCache[edge];
// If the edge was already drawn (like if it is eligible AND has
// `forceLabel`), we don't want to draw it again
if (displayedLabels.has(edge)) continue;
// If the edge is hidden we don't need to display its label
// NOTE: the test on sourceData & targetData is probably paranoid at this point?
if (edgeData.hidden || sourceData.hidden || targetData.hidden) {
continue;
}
const { edgeProgramClasses, defaultDrawEdgeLabel } = this.settings;
const drawLabel = edgeProgramClasses[edgeData.type].drawLabel || defaultDrawEdgeLabel;
drawLabel(
context,
{
key: edge,
...edgeData,