-
Notifications
You must be signed in to change notification settings - Fork 26
/
cytoscape-fcose.js
1549 lines (1313 loc) · 55.9 KB
/
cytoscape-fcose.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory(require("cose-base"));
else if(typeof define === 'function' && define.amd)
define(["cose-base"], factory);
else if(typeof exports === 'object')
exports["cytoscapeFcose"] = factory(require("cose-base"));
else
root["cytoscapeFcose"] = factory(root["coseBase"]);
})(this, function(__WEBPACK_EXTERNAL_MODULE__140__) {
return /******/ (() => { // webpackBootstrap
/******/ "use strict";
/******/ var __webpack_modules__ = ({
/***/ 658:
/***/ ((module) => {
// Simple, internal Object.assign() polyfill for options objects etc.
module.exports = Object.assign != null ? Object.assign.bind(Object) : function (tgt) {
for (var _len = arguments.length, srcs = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
srcs[_key - 1] = arguments[_key];
}
srcs.forEach(function (src) {
Object.keys(src).forEach(function (k) {
return tgt[k] = src[k];
});
});
return tgt;
};
/***/ }),
/***/ 548:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();
/*
* Auxiliary functions
*/
var LinkedList = __webpack_require__(140).layoutBase.LinkedList;
var auxiliary = {};
// get the top most nodes
auxiliary.getTopMostNodes = function (nodes) {
var nodesMap = {};
for (var i = 0; i < nodes.length; i++) {
nodesMap[nodes[i].id()] = true;
}
var roots = nodes.filter(function (ele, i) {
if (typeof ele === "number") {
ele = i;
}
var parent = ele.parent()[0];
while (parent != null) {
if (nodesMap[parent.id()]) {
return false;
}
parent = parent.parent()[0];
}
return true;
});
return roots;
};
// find disconnected components and create dummy nodes that connect them
auxiliary.connectComponents = function (cy, eles, topMostNodes, dummyNodes) {
var queue = new LinkedList();
var visited = new Set();
var visitedTopMostNodes = [];
var currentNeighbor = void 0;
var minDegreeNode = void 0;
var minDegree = void 0;
var isConnected = false;
var count = 1;
var nodesConnectedToDummy = [];
var components = [];
var _loop = function _loop() {
var cmpt = cy.collection();
components.push(cmpt);
var currentNode = topMostNodes[0];
var childrenOfCurrentNode = cy.collection();
childrenOfCurrentNode.merge(currentNode).merge(currentNode.descendants().intersection(eles));
visitedTopMostNodes.push(currentNode);
childrenOfCurrentNode.forEach(function (node) {
queue.push(node);
visited.add(node);
cmpt.merge(node);
});
var _loop2 = function _loop2() {
currentNode = queue.shift();
// Traverse all neighbors of this node
var neighborNodes = cy.collection();
currentNode.neighborhood().nodes().forEach(function (node) {
if (eles.intersection(currentNode.edgesWith(node)).length > 0) {
neighborNodes.merge(node);
}
});
for (var i = 0; i < neighborNodes.length; i++) {
var neighborNode = neighborNodes[i];
currentNeighbor = topMostNodes.intersection(neighborNode.union(neighborNode.ancestors()));
if (currentNeighbor != null && !visited.has(currentNeighbor[0])) {
var childrenOfNeighbor = currentNeighbor.union(currentNeighbor.descendants());
childrenOfNeighbor.forEach(function (node) {
queue.push(node);
visited.add(node);
cmpt.merge(node);
if (topMostNodes.has(node)) {
visitedTopMostNodes.push(node);
}
});
}
}
};
while (queue.length != 0) {
_loop2();
}
cmpt.forEach(function (node) {
eles.intersection(node.connectedEdges()).forEach(function (e) {
// connectedEdges() usually cached
if (cmpt.has(e.source()) && cmpt.has(e.target())) {
// has() is cheap
cmpt.merge(e);
}
});
});
if (visitedTopMostNodes.length == topMostNodes.length) {
isConnected = true;
}
if (!isConnected || isConnected && count > 1) {
minDegreeNode = visitedTopMostNodes[0];
minDegree = minDegreeNode.connectedEdges().length;
visitedTopMostNodes.forEach(function (node) {
if (node.connectedEdges().length < minDegree) {
minDegree = node.connectedEdges().length;
minDegreeNode = node;
}
});
nodesConnectedToDummy.push(minDegreeNode.id());
// TO DO: Check efficiency of this part
var temp = cy.collection();
temp.merge(visitedTopMostNodes[0]);
visitedTopMostNodes.forEach(function (node) {
temp.merge(node);
});
visitedTopMostNodes = [];
topMostNodes = topMostNodes.difference(temp);
count++;
}
};
do {
_loop();
} while (!isConnected);
if (dummyNodes) {
if (nodesConnectedToDummy.length > 0) {
dummyNodes.set('dummy' + (dummyNodes.size + 1), nodesConnectedToDummy);
}
}
return components;
};
// relocates componentResult to originalCenter if there is no fixedNodeConstraint
auxiliary.relocateComponent = function (originalCenter, componentResult, options) {
if (!options.fixedNodeConstraint) {
var minXCoord = Number.POSITIVE_INFINITY;
var maxXCoord = Number.NEGATIVE_INFINITY;
var minYCoord = Number.POSITIVE_INFINITY;
var maxYCoord = Number.NEGATIVE_INFINITY;
if (options.quality == "draft") {
// calculate current bounding box
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = componentResult.nodeIndexes[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var _ref = _step.value;
var _ref2 = _slicedToArray(_ref, 2);
var key = _ref2[0];
var value = _ref2[1];
var cyNode = options.cy.getElementById(key);
if (cyNode) {
var nodeBB = cyNode.boundingBox();
var leftX = componentResult.xCoords[value] - nodeBB.w / 2;
var rightX = componentResult.xCoords[value] + nodeBB.w / 2;
var topY = componentResult.yCoords[value] - nodeBB.h / 2;
var bottomY = componentResult.yCoords[value] + nodeBB.h / 2;
if (leftX < minXCoord) minXCoord = leftX;
if (rightX > maxXCoord) maxXCoord = rightX;
if (topY < minYCoord) minYCoord = topY;
if (bottomY > maxYCoord) maxYCoord = bottomY;
}
}
// find difference between current and original center
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
var diffOnX = originalCenter.x - (maxXCoord + minXCoord) / 2;
var diffOnY = originalCenter.y - (maxYCoord + minYCoord) / 2;
// move component to original center
componentResult.xCoords = componentResult.xCoords.map(function (x) {
return x + diffOnX;
});
componentResult.yCoords = componentResult.yCoords.map(function (y) {
return y + diffOnY;
});
} else {
// calculate current bounding box
Object.keys(componentResult).forEach(function (item) {
var node = componentResult[item];
var leftX = node.getRect().x;
var rightX = node.getRect().x + node.getRect().width;
var topY = node.getRect().y;
var bottomY = node.getRect().y + node.getRect().height;
if (leftX < minXCoord) minXCoord = leftX;
if (rightX > maxXCoord) maxXCoord = rightX;
if (topY < minYCoord) minYCoord = topY;
if (bottomY > maxYCoord) maxYCoord = bottomY;
});
// find difference between current and original center
var _diffOnX = originalCenter.x - (maxXCoord + minXCoord) / 2;
var _diffOnY = originalCenter.y - (maxYCoord + minYCoord) / 2;
// move component to original center
Object.keys(componentResult).forEach(function (item) {
var node = componentResult[item];
node.setCenter(node.getCenterX() + _diffOnX, node.getCenterY() + _diffOnY);
});
}
}
};
auxiliary.calcBoundingBox = function (parentNode, xCoords, yCoords, nodeIndexes) {
// calculate bounds
var left = Number.MAX_SAFE_INTEGER;
var right = Number.MIN_SAFE_INTEGER;
var top = Number.MAX_SAFE_INTEGER;
var bottom = Number.MIN_SAFE_INTEGER;
var nodeLeft = void 0;
var nodeRight = void 0;
var nodeTop = void 0;
var nodeBottom = void 0;
var nodes = parentNode.descendants().not(":parent");
var s = nodes.length;
for (var i = 0; i < s; i++) {
var node = nodes[i];
nodeLeft = xCoords[nodeIndexes.get(node.id())] - node.width() / 2;
nodeRight = xCoords[nodeIndexes.get(node.id())] + node.width() / 2;
nodeTop = yCoords[nodeIndexes.get(node.id())] - node.height() / 2;
nodeBottom = yCoords[nodeIndexes.get(node.id())] + node.height() / 2;
if (left > nodeLeft) {
left = nodeLeft;
}
if (right < nodeRight) {
right = nodeRight;
}
if (top > nodeTop) {
top = nodeTop;
}
if (bottom < nodeBottom) {
bottom = nodeBottom;
}
}
var boundingBox = {};
boundingBox.topLeftX = left;
boundingBox.topLeftY = top;
boundingBox.width = right - left;
boundingBox.height = bottom - top;
return boundingBox;
};
// This function finds and returns parent nodes whose all children are hidden
auxiliary.calcParentsWithoutChildren = function (cy, eles) {
var parentsWithoutChildren = cy.collection();
eles.nodes(':parent').forEach(function (parent) {
var check = false;
parent.children().forEach(function (child) {
if (child.css('display') != 'none') {
check = true;
}
});
if (!check) {
parentsWithoutChildren.merge(parent);
}
});
return parentsWithoutChildren;
};
module.exports = auxiliary;
/***/ }),
/***/ 816:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
/**
The implementation of the postprocessing part that applies CoSE layout over the spectral layout
*/
var aux = __webpack_require__(548);
var CoSELayout = __webpack_require__(140).CoSELayout;
var CoSENode = __webpack_require__(140).CoSENode;
var PointD = __webpack_require__(140).layoutBase.PointD;
var DimensionD = __webpack_require__(140).layoutBase.DimensionD;
var LayoutConstants = __webpack_require__(140).layoutBase.LayoutConstants;
var FDLayoutConstants = __webpack_require__(140).layoutBase.FDLayoutConstants;
var CoSEConstants = __webpack_require__(140).CoSEConstants;
// main function that cose layout is processed
var coseLayout = function coseLayout(options, spectralResult) {
var cy = options.cy;
var eles = options.eles;
var nodes = eles.nodes();
var edges = eles.edges();
var nodeIndexes = void 0;
var xCoords = void 0;
var yCoords = void 0;
var idToLNode = {};
if (options.randomize) {
nodeIndexes = spectralResult["nodeIndexes"];
xCoords = spectralResult["xCoords"];
yCoords = spectralResult["yCoords"];
}
var isFn = function isFn(fn) {
return typeof fn === 'function';
};
var optFn = function optFn(opt, ele) {
if (isFn(opt)) {
return opt(ele);
} else {
return opt;
}
};
/**** Postprocessing functions ****/
var parentsWithoutChildren = aux.calcParentsWithoutChildren(cy, eles);
// transfer cytoscape nodes to cose nodes
var processChildrenList = function processChildrenList(parent, children, layout, options) {
var size = children.length;
for (var i = 0; i < size; i++) {
var theChild = children[i];
var children_of_children = null;
if (theChild.intersection(parentsWithoutChildren).length == 0) {
children_of_children = theChild.children();
}
var theNode = void 0;
var dimensions = theChild.layoutDimensions({
nodeDimensionsIncludeLabels: options.nodeDimensionsIncludeLabels
});
if (theChild.outerWidth() != null && theChild.outerHeight() != null) {
if (options.randomize) {
if (!theChild.isParent()) {
theNode = parent.add(new CoSENode(layout.graphManager, new PointD(xCoords[nodeIndexes.get(theChild.id())] - dimensions.w / 2, yCoords[nodeIndexes.get(theChild.id())] - dimensions.h / 2), new DimensionD(parseFloat(dimensions.w), parseFloat(dimensions.h))));
} else {
var parentInfo = aux.calcBoundingBox(theChild, xCoords, yCoords, nodeIndexes);
if (theChild.intersection(parentsWithoutChildren).length == 0) {
theNode = parent.add(new CoSENode(layout.graphManager, new PointD(parentInfo.topLeftX, parentInfo.topLeftY), new DimensionD(parentInfo.width, parentInfo.height)));
} else {
// for the parentsWithoutChildren
theNode = parent.add(new CoSENode(layout.graphManager, new PointD(parentInfo.topLeftX, parentInfo.topLeftY), new DimensionD(parseFloat(dimensions.w), parseFloat(dimensions.h))));
}
}
} else {
theNode = parent.add(new CoSENode(layout.graphManager, new PointD(theChild.position('x') - dimensions.w / 2, theChild.position('y') - dimensions.h / 2), new DimensionD(parseFloat(dimensions.w), parseFloat(dimensions.h))));
}
} else {
theNode = parent.add(new CoSENode(this.graphManager));
}
// Attach id to the layout node and repulsion value
theNode.id = theChild.data("id");
theNode.nodeRepulsion = optFn(options.nodeRepulsion, theChild);
// Attach the paddings of cy node to layout node
theNode.paddingLeft = parseInt(theChild.css('padding'));
theNode.paddingTop = parseInt(theChild.css('padding'));
theNode.paddingRight = parseInt(theChild.css('padding'));
theNode.paddingBottom = parseInt(theChild.css('padding'));
//Attach the label properties to both compound and simple nodes if labels will be included in node dimensions
//These properties will be used while updating bounds of compounds during iterations or tiling
//and will be used for simple nodes while transferring final positions to cytoscape
if (options.nodeDimensionsIncludeLabels) {
theNode.labelWidth = theChild.boundingBox({ includeLabels: true, includeNodes: false, includeOverlays: false }).w;
theNode.labelHeight = theChild.boundingBox({ includeLabels: true, includeNodes: false, includeOverlays: false }).h;
theNode.labelPosVertical = theChild.css("text-valign");
theNode.labelPosHorizontal = theChild.css("text-halign");
}
// Map the layout node
idToLNode[theChild.data("id")] = theNode;
if (isNaN(theNode.rect.x)) {
theNode.rect.x = 0;
}
if (isNaN(theNode.rect.y)) {
theNode.rect.y = 0;
}
if (children_of_children != null && children_of_children.length > 0) {
var theNewGraph = void 0;
theNewGraph = layout.getGraphManager().add(layout.newGraph(), theNode);
processChildrenList(theNewGraph, children_of_children, layout, options);
}
}
};
// transfer cytoscape edges to cose edges
var processEdges = function processEdges(layout, gm, edges) {
var idealLengthTotal = 0;
var edgeCount = 0;
for (var i = 0; i < edges.length; i++) {
var edge = edges[i];
var sourceNode = idToLNode[edge.data("source")];
var targetNode = idToLNode[edge.data("target")];
if (sourceNode && targetNode && sourceNode !== targetNode && sourceNode.getEdgesBetween(targetNode).length == 0) {
var e1 = gm.add(layout.newEdge(), sourceNode, targetNode);
e1.id = edge.id();
e1.idealLength = optFn(options.idealEdgeLength, edge);
e1.edgeElasticity = optFn(options.edgeElasticity, edge);
idealLengthTotal += e1.idealLength;
edgeCount++;
}
}
// we need to update the ideal edge length constant with the avg. ideal length value after processing edges
// in case there is no edge, use other options
if (options.idealEdgeLength != null) {
if (edgeCount > 0) CoSEConstants.DEFAULT_EDGE_LENGTH = FDLayoutConstants.DEFAULT_EDGE_LENGTH = idealLengthTotal / edgeCount;else if (!isFn(options.idealEdgeLength)) // in case there is no edge, but option gives a value to use
CoSEConstants.DEFAULT_EDGE_LENGTH = FDLayoutConstants.DEFAULT_EDGE_LENGTH = options.idealEdgeLength;else // in case there is no edge and we cannot get a value from option (because it's a function)
CoSEConstants.DEFAULT_EDGE_LENGTH = FDLayoutConstants.DEFAULT_EDGE_LENGTH = 50;
// we need to update these constant values based on the ideal edge length constant
CoSEConstants.MIN_REPULSION_DIST = FDLayoutConstants.MIN_REPULSION_DIST = FDLayoutConstants.DEFAULT_EDGE_LENGTH / 10.0;
CoSEConstants.DEFAULT_RADIAL_SEPARATION = FDLayoutConstants.DEFAULT_EDGE_LENGTH;
}
};
// transfer cytoscape constraints to cose layout
var processConstraints = function processConstraints(layout, options) {
// get nodes to be fixed
if (options.fixedNodeConstraint) {
layout.constraints["fixedNodeConstraint"] = options.fixedNodeConstraint;
}
// get nodes to be aligned
if (options.alignmentConstraint) {
layout.constraints["alignmentConstraint"] = options.alignmentConstraint;
}
// get nodes to be relatively placed
if (options.relativePlacementConstraint) {
layout.constraints["relativePlacementConstraint"] = options.relativePlacementConstraint;
}
};
/**** Apply postprocessing ****/
if (options.nestingFactor != null) CoSEConstants.PER_LEVEL_IDEAL_EDGE_LENGTH_FACTOR = FDLayoutConstants.PER_LEVEL_IDEAL_EDGE_LENGTH_FACTOR = options.nestingFactor;
if (options.gravity != null) CoSEConstants.DEFAULT_GRAVITY_STRENGTH = FDLayoutConstants.DEFAULT_GRAVITY_STRENGTH = options.gravity;
if (options.numIter != null) CoSEConstants.MAX_ITERATIONS = FDLayoutConstants.MAX_ITERATIONS = options.numIter;
if (options.gravityRange != null) CoSEConstants.DEFAULT_GRAVITY_RANGE_FACTOR = FDLayoutConstants.DEFAULT_GRAVITY_RANGE_FACTOR = options.gravityRange;
if (options.gravityCompound != null) CoSEConstants.DEFAULT_COMPOUND_GRAVITY_STRENGTH = FDLayoutConstants.DEFAULT_COMPOUND_GRAVITY_STRENGTH = options.gravityCompound;
if (options.gravityRangeCompound != null) CoSEConstants.DEFAULT_COMPOUND_GRAVITY_RANGE_FACTOR = FDLayoutConstants.DEFAULT_COMPOUND_GRAVITY_RANGE_FACTOR = options.gravityRangeCompound;
if (options.initialEnergyOnIncremental != null) CoSEConstants.DEFAULT_COOLING_FACTOR_INCREMENTAL = FDLayoutConstants.DEFAULT_COOLING_FACTOR_INCREMENTAL = options.initialEnergyOnIncremental;
if (options.tilingCompareBy != null) CoSEConstants.TILING_COMPARE_BY = options.tilingCompareBy;
if (options.quality == 'proof') LayoutConstants.QUALITY = 2;else LayoutConstants.QUALITY = 0;
CoSEConstants.NODE_DIMENSIONS_INCLUDE_LABELS = FDLayoutConstants.NODE_DIMENSIONS_INCLUDE_LABELS = LayoutConstants.NODE_DIMENSIONS_INCLUDE_LABELS = options.nodeDimensionsIncludeLabels;
CoSEConstants.DEFAULT_INCREMENTAL = FDLayoutConstants.DEFAULT_INCREMENTAL = LayoutConstants.DEFAULT_INCREMENTAL = !options.randomize;
CoSEConstants.ANIMATE = FDLayoutConstants.ANIMATE = LayoutConstants.ANIMATE = options.animate;
CoSEConstants.TILE = options.tile;
CoSEConstants.TILING_PADDING_VERTICAL = typeof options.tilingPaddingVertical === 'function' ? options.tilingPaddingVertical.call() : options.tilingPaddingVertical;
CoSEConstants.TILING_PADDING_HORIZONTAL = typeof options.tilingPaddingHorizontal === 'function' ? options.tilingPaddingHorizontal.call() : options.tilingPaddingHorizontal;
CoSEConstants.DEFAULT_INCREMENTAL = FDLayoutConstants.DEFAULT_INCREMENTAL = LayoutConstants.DEFAULT_INCREMENTAL = true;
CoSEConstants.PURE_INCREMENTAL = !options.randomize;
LayoutConstants.DEFAULT_UNIFORM_LEAF_NODE_SIZES = options.uniformNodeDimensions;
// This part is for debug/demo purpose
if (options.step == "transformed") {
CoSEConstants.TRANSFORM_ON_CONSTRAINT_HANDLING = true;
CoSEConstants.ENFORCE_CONSTRAINTS = false;
CoSEConstants.APPLY_LAYOUT = false;
}
if (options.step == "enforced") {
CoSEConstants.TRANSFORM_ON_CONSTRAINT_HANDLING = false;
CoSEConstants.ENFORCE_CONSTRAINTS = true;
CoSEConstants.APPLY_LAYOUT = false;
}
if (options.step == "cose") {
CoSEConstants.TRANSFORM_ON_CONSTRAINT_HANDLING = false;
CoSEConstants.ENFORCE_CONSTRAINTS = false;
CoSEConstants.APPLY_LAYOUT = true;
}
if (options.step == "all") {
if (options.randomize) CoSEConstants.TRANSFORM_ON_CONSTRAINT_HANDLING = true;else CoSEConstants.TRANSFORM_ON_CONSTRAINT_HANDLING = false;
CoSEConstants.ENFORCE_CONSTRAINTS = true;
CoSEConstants.APPLY_LAYOUT = true;
}
if (options.fixedNodeConstraint || options.alignmentConstraint || options.relativePlacementConstraint) {
CoSEConstants.TREE_REDUCTION_ON_INCREMENTAL = false;
} else {
CoSEConstants.TREE_REDUCTION_ON_INCREMENTAL = true;
}
var coseLayout = new CoSELayout();
var gm = coseLayout.newGraphManager();
processChildrenList(gm.addRoot(), aux.getTopMostNodes(nodes), coseLayout, options);
processEdges(coseLayout, gm, edges);
processConstraints(coseLayout, options);
coseLayout.runLayout();
return idToLNode;
};
module.exports = { coseLayout: coseLayout };
/***/ }),
/***/ 212:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
/**
The implementation of the fcose layout algorithm
*/
var assign = __webpack_require__(658);
var aux = __webpack_require__(548);
var _require = __webpack_require__(657),
spectralLayout = _require.spectralLayout;
var _require2 = __webpack_require__(816),
coseLayout = _require2.coseLayout;
var defaults = Object.freeze({
// 'draft', 'default' or 'proof'
// - 'draft' only applies spectral layout
// - 'default' improves the quality with subsequent CoSE layout (fast cooling rate)
// - 'proof' improves the quality with subsequent CoSE layout (slow cooling rate)
quality: "default",
// Use random node positions at beginning of layout
// if this is set to false, then quality option must be "proof"
randomize: true,
// Whether or not to animate the layout
animate: true,
// Duration of animation in ms, if enabled
animationDuration: 1000,
// Easing of animation, if enabled
animationEasing: undefined,
// Fit the viewport to the repositioned nodes
fit: true,
// Padding around layout
padding: 30,
// Whether to include labels in node dimensions. Valid in "proof" quality
nodeDimensionsIncludeLabels: false,
// Whether or not simple nodes (non-compound nodes) are of uniform dimensions
uniformNodeDimensions: false,
// Whether to pack disconnected components - valid only if randomize: true
packComponents: true,
// Layout step - all, transformed, enforced, cose - for debug purpose only
step: "all",
/* spectral layout options */
// False for random, true for greedy
samplingType: true,
// Sample size to construct distance matrix
sampleSize: 25,
// Separation amount between nodes
nodeSeparation: 75,
// Power iteration tolerance
piTol: 0.0000001,
/* CoSE layout options */
// Node repulsion (non overlapping) multiplier
nodeRepulsion: function nodeRepulsion(node) {
return 4500;
},
// Ideal edge (non nested) length
idealEdgeLength: function idealEdgeLength(edge) {
return 50;
},
// Divisor to compute edge forces
edgeElasticity: function edgeElasticity(edge) {
return 0.45;
},
// Nesting factor (multiplier) to compute ideal edge length for nested edges
nestingFactor: 0.1,
// Gravity force (constant)
gravity: 0.25,
// Maximum number of iterations to perform
numIter: 2500,
// For enabling tiling
tile: true,
// The function that specifies the criteria for comparing nodes while sorting them during tiling operation.
// Takes the node id as a parameter and the default tiling operation is perfomed when this option is not set.
tilingCompareBy: undefined,
// Represents the amount of the vertical space to put between the zero degree members during the tiling operation(can also be a function)
tilingPaddingVertical: 10,
// Represents the amount of the horizontal space to put between the zero degree members during the tiling operation(can also be a function)
tilingPaddingHorizontal: 10,
// Gravity range (constant) for compounds
gravityRangeCompound: 1.5,
// Gravity force (constant) for compounds
gravityCompound: 1.0,
// Gravity range (constant)
gravityRange: 3.8,
// Initial cooling factor for incremental layout
initialEnergyOnIncremental: 0.3,
/* constraint options */
// Fix required nodes to predefined positions
// [{nodeId: 'n1', position: {x: 100, y: 200}, {...}]
fixedNodeConstraint: undefined,
// Align required nodes in vertical/horizontal direction
// {vertical: [['n1', 'n2')], ['n3', 'n4']], horizontal: ['n2', 'n4']}
alignmentConstraint: undefined,
// Place two nodes relatively in vertical/horizontal direction
// [{top: 'n1', bottom: 'n2', gap: 100}, {left: 'n3', right: 'n4', gap: 75}]
relativePlacementConstraint: undefined,
/* layout event callbacks */
ready: function ready() {}, // on layoutready
stop: function stop() {} // on layoutstop
});
var Layout = function () {
function Layout(options) {
_classCallCheck(this, Layout);
this.options = assign({}, defaults, options);
}
_createClass(Layout, [{
key: 'run',
value: function run() {
var layout = this;
var options = this.options;
var cy = options.cy;
var eles = options.eles;
var spectralResult = [];
var xCoords = void 0;
var yCoords = void 0;
var coseResult = [];
var components = void 0;
var componentCenters = [];
// basic validity check for constraint inputs
if (options.fixedNodeConstraint && (!Array.isArray(options.fixedNodeConstraint) || options.fixedNodeConstraint.length == 0)) {
options.fixedNodeConstraint = undefined;
}
if (options.alignmentConstraint) {
if (options.alignmentConstraint.vertical && (!Array.isArray(options.alignmentConstraint.vertical) || options.alignmentConstraint.vertical.length == 0)) {
options.alignmentConstraint.vertical = undefined;
}
if (options.alignmentConstraint.horizontal && (!Array.isArray(options.alignmentConstraint.horizontal) || options.alignmentConstraint.horizontal.length == 0)) {
options.alignmentConstraint.horizontal = undefined;
}
}
if (options.relativePlacementConstraint && (!Array.isArray(options.relativePlacementConstraint) || options.relativePlacementConstraint.length == 0)) {
options.relativePlacementConstraint = undefined;
}
// if any constraint exists, set some options
var constraintExist = options.fixedNodeConstraint || options.alignmentConstraint || options.relativePlacementConstraint;
if (constraintExist) {
// constraints work with these options
options.tile = false;
options.packComponents = false;
}
// decide component packing is enabled or not
var layUtil = void 0;
var packingEnabled = false;
if (cy.layoutUtilities && options.packComponents) {
layUtil = cy.layoutUtilities("get");
if (!layUtil) layUtil = cy.layoutUtilities();
packingEnabled = true;
}
if (eles.nodes().length > 0) {
// if packing is not enabled, perform layout on the whole graph
if (!packingEnabled) {
// store component center
var boundingBox = options.eles.boundingBox();
componentCenters.push({ x: boundingBox.x1 + boundingBox.w / 2, y: boundingBox.y1 + boundingBox.h / 2 });
// apply spectral layout
if (options.randomize) {
var result = spectralLayout(options);
spectralResult.push(result);
}
// apply cose layout as postprocessing
if (options.quality == "default" || options.quality == "proof") {
coseResult.push(coseLayout(options, spectralResult[0]));
aux.relocateComponent(componentCenters[0], coseResult[0], options); // relocate center to original position
} else {
aux.relocateComponent(componentCenters[0], spectralResult[0], options); // relocate center to original position
}
} else {
// packing is enabled
var topMostNodes = aux.getTopMostNodes(options.eles.nodes());
components = aux.connectComponents(cy, options.eles, topMostNodes);
// store component centers
components.forEach(function (component) {
var boundingBox = component.boundingBox();
componentCenters.push({ x: boundingBox.x1 + boundingBox.w / 2, y: boundingBox.y1 + boundingBox.h / 2 });
});
//send each component to spectral layout if randomized
if (options.randomize) {
components.forEach(function (component) {
options.eles = component;
spectralResult.push(spectralLayout(options));
});
}
if (options.quality == "default" || options.quality == "proof") {
var toBeTiledNodes = cy.collection();
if (options.tile) {
// behave nodes to be tiled as one component
var nodeIndexes = new Map();
var _xCoords = [];
var _yCoords = [];
var count = 0;
var tempSpectralResult = { nodeIndexes: nodeIndexes, xCoords: _xCoords, yCoords: _yCoords };
var indexesToBeDeleted = [];
components.forEach(function (component, index) {
if (component.edges().length == 0) {
component.nodes().forEach(function (node, i) {
toBeTiledNodes.merge(component.nodes()[i]);
if (!node.isParent()) {
tempSpectralResult.nodeIndexes.set(component.nodes()[i].id(), count++);
tempSpectralResult.xCoords.push(component.nodes()[0].position().x);
tempSpectralResult.yCoords.push(component.nodes()[0].position().y);
}
});
indexesToBeDeleted.push(index);
}
});
if (toBeTiledNodes.length > 1) {
var _boundingBox = toBeTiledNodes.boundingBox();
componentCenters.push({ x: _boundingBox.x1 + _boundingBox.w / 2, y: _boundingBox.y1 + _boundingBox.h / 2 });
components.push(toBeTiledNodes);
spectralResult.push(tempSpectralResult);
for (var i = indexesToBeDeleted.length - 1; i >= 0; i--) {
components.splice(indexesToBeDeleted[i], 1);
spectralResult.splice(indexesToBeDeleted[i], 1);
componentCenters.splice(indexesToBeDeleted[i], 1);
};
}
}
components.forEach(function (component, index) {
// send each component to cose layout
options.eles = component;
coseResult.push(coseLayout(options, spectralResult[index]));
aux.relocateComponent(componentCenters[index], coseResult[index], options); // relocate center to original position
});
} else {
components.forEach(function (component, index) {
aux.relocateComponent(componentCenters[index], spectralResult[index], options); // relocate center to original position
});
}
// packing
var componentsEvaluated = new Set();
if (components.length > 1) {
var subgraphs = [];
var hiddenEles = eles.filter(function (ele) {
return ele.css('display') == 'none';
});
components.forEach(function (component, index) {
var nodeIndexes = void 0;
if (options.quality == "draft") {
nodeIndexes = spectralResult[index].nodeIndexes;
}
if (component.nodes().not(hiddenEles).length > 0) {
var subgraph = {};
subgraph.edges = [];
subgraph.nodes = [];
var nodeIndex = void 0;
component.nodes().not(hiddenEles).forEach(function (node) {
if (options.quality == "draft") {
if (!node.isParent()) {
nodeIndex = nodeIndexes.get(node.id());
subgraph.nodes.push({ x: spectralResult[index].xCoords[nodeIndex] - node.boundingbox().w / 2, y: spectralResult[index].yCoords[nodeIndex] - node.boundingbox().h / 2, width: node.boundingbox().w, height: node.boundingbox().h });
} else {
var parentInfo = aux.calcBoundingBox(node, spectralResult[index].xCoords, spectralResult[index].yCoords, nodeIndexes);
subgraph.nodes.push({ x: parentInfo.topLeftX, y: parentInfo.topLeftY, width: parentInfo.width, height: parentInfo.height });
}
} else {
if (coseResult[index][node.id()]) {
subgraph.nodes.push({ x: coseResult[index][node.id()].getLeft(), y: coseResult[index][node.id()].getTop(), width: coseResult[index][node.id()].getWidth(), height: coseResult[index][node.id()].getHeight() });
}
}
});
component.edges().forEach(function (edge) {
var source = edge.source();
var target = edge.target();
if (source.css("display") != "none" && target.css("display") != "none") {
if (options.quality == "draft") {
var sourceNodeIndex = nodeIndexes.get(source.id());
var targetNodeIndex = nodeIndexes.get(target.id());
var sourceCenter = [];
var targetCenter = [];
if (source.isParent()) {
var parentInfo = aux.calcBoundingBox(source, spectralResult[index].xCoords, spectralResult[index].yCoords, nodeIndexes);
sourceCenter.push(parentInfo.topLeftX + parentInfo.width / 2);
sourceCenter.push(parentInfo.topLeftY + parentInfo.height / 2);
} else {
sourceCenter.push(spectralResult[index].xCoords[sourceNodeIndex]);
sourceCenter.push(spectralResult[index].yCoords[sourceNodeIndex]);
}
if (target.isParent()) {
var _parentInfo = aux.calcBoundingBox(target, spectralResult[index].xCoords, spectralResult[index].yCoords, nodeIndexes);
targetCenter.push(_parentInfo.topLeftX + _parentInfo.width / 2);
targetCenter.push(_parentInfo.topLeftY + _parentInfo.height / 2);
} else {
targetCenter.push(spectralResult[index].xCoords[targetNodeIndex]);
targetCenter.push(spectralResult[index].yCoords[targetNodeIndex]);
}
subgraph.edges.push({ startX: sourceCenter[0], startY: sourceCenter[1], endX: targetCenter[0], endY: targetCenter[1] });
} else {
if (coseResult[index][source.id()] && coseResult[index][target.id()]) {
subgraph.edges.push({ startX: coseResult[index][source.id()].getCenterX(), startY: coseResult[index][source.id()].getCenterY(), endX: coseResult[index][target.id()].getCenterX(), endY: coseResult[index][target.id()].getCenterY() });
}
}
}
});
if (subgraph.nodes.length > 0) {
subgraphs.push(subgraph);
componentsEvaluated.add(index);
}
}
});
var shiftResult = layUtil.packComponents(subgraphs, options.randomize).shifts;
if (options.quality == "draft") {
spectralResult.forEach(function (result, index) {
var newXCoords = result.xCoords.map(function (x) {
return x + shiftResult[index].dx;
});
var newYCoords = result.yCoords.map(function (y) {
return y + shiftResult[index].dy;
});
result.xCoords = newXCoords;
result.yCoords = newYCoords;
});
} else {
var _count = 0;
componentsEvaluated.forEach(function (index) {
Object.keys(coseResult[index]).forEach(function (item) {
var nodeRectangle = coseResult[index][item];
nodeRectangle.setCenter(nodeRectangle.getCenterX() + shiftResult[_count].dx, nodeRectangle.getCenterY() + shiftResult[_count].dy);
});
_count++;
});
}
}
}
}
// get each element's calculated position
var getPositions = function getPositions(ele, i) {
if (options.quality == "default" || options.quality == "proof") {
if (typeof ele === "number") {
ele = i;
}
var pos = void 0;
var node = void 0;
var theId = ele.data('id');
coseResult.forEach(function (result) {
if (theId in result) {
pos = { x: result[theId].getRect().getCenterX(), y: result[theId].getRect().getCenterY() };
node = result[theId];
}
});
if (options.nodeDimensionsIncludeLabels) {
if (node.labelWidth) {
if (node.labelPosHorizontal == "left") {
pos.x += node.labelWidth / 2;
} else if (node.labelPosHorizontal == "right") {
pos.x -= node.labelWidth / 2;
}
}
if (node.labelHeight) {
if (node.labelPosVertical == "top") {
pos.y += node.labelHeight / 2;
} else if (node.labelPosVertical == "bottom") {
pos.y -= node.labelHeight / 2;
}
}
}
if (pos == undefined) pos = { x: ele.position("x"), y: ele.position("y") };
return {
x: pos.x,
y: pos.y
};
} else {
var _pos = void 0;
spectralResult.forEach(function (result) {
var index = result.nodeIndexes.get(ele.id());
if (index != undefined) {
_pos = { x: result.xCoords[index], y: result.yCoords[index] };
}
});
if (_pos == undefined) _pos = { x: ele.position("x"), y: ele.position("y") };
return {
x: _pos.x,
y: _pos.y
};
}
};
// quality = "draft" and randomize = false are contradictive so in that case positions don't change
if (options.quality == "default" || options.quality == "proof" || options.randomize) {
// transfer calculated positions to nodes (positions of only simple nodes are evaluated, compounds are positioned automatically)
var parentsWithoutChildren = aux.calcParentsWithoutChildren(cy, eles);
var _hiddenEles = eles.filter(function (ele) {
return ele.css('display') == 'none';
});
options.eles = eles.not(_hiddenEles);
eles.nodes().not(":parent").not(_hiddenEles).layoutPositions(layout, options, getPositions);
if (parentsWithoutChildren.length > 0) {
parentsWithoutChildren.forEach(function (ele) {
ele.position(getPositions(ele));
});