-
Notifications
You must be signed in to change notification settings - Fork 0
/
vivagraph.min.js
7312 lines (6103 loc) · 231 KB
/
vivagraph.min.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(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.Viva=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
/**
* This is an entry point for global namespace. If you want to use separate
* modules individually - you are more than welcome to do so.
*/
var random = require('ngraph.random');
var Viva = {
lazyExtend: function() {
return require('ngraph.merge').apply(this, arguments);
},
randomIterator: function() {
return random.randomIterator.apply(random, arguments);
},
random: function() {
return random.random.apply(random, arguments);
},
events: require('ngraph.events')
};
Viva.Graph = {
version: require('./version.js'),
graph: require('ngraph.graph'),
serializer: function() {
return {
loadFromJSON: require('ngraph.fromjson'),
storeToJSON: require('ngraph.tojson')
};
},
centrality: require('./Algorithms/centrality.js'),
operations: require('./Algorithms/operations.js'),
geom: function() {
return {
intersect: require('gintersect'),
intersectRect: require('./Utils/intersectRect.js')
};
},
webgl: require('./WebGL/webgl.js'),
webglInputEvents: require('./WebGL/webglInputEvents.js'),
generator: function() {
return require('ngraph.generators');
},
Input: {
domInputManager: require('./Input/domInputManager.js'),
webglInputManager: require('./Input/webglInputManager.js')
},
Utils: {
// TODO: move to Input
dragndrop: require('./Input/dragndrop.js'),
findElementPosition: require('./Utils/findElementPosition.js'),
timer: require('./Utils/timer.js'),
getDimension: require('./Utils/getDimensions.js'),
events: require('./Utils/backwardCompatibleEvents.js')
},
Layout: {
forceDirected: require('ngraph.forcelayout'),
constant: require('./Layout/constant.js')
},
View: {
// TODO: Move `webglXXX` out to webgl namespace
Texture: require('./WebGL/texture.js'),
// TODO: This should not be even exported
webglAtlas: require('./WebGL/webglAtlas.js'),
webglImageNodeProgram: require('./WebGL/webglImageNodeProgram.js'),
webglLinkProgram: require('./WebGL/webglLinkProgram.js'),
webglNodeProgram: require('./WebGL/webglNodeProgram.js'),
webglLine: require('./WebGL/webglLine.js'),
webglSquare: require('./WebGL/webglSquare.js'),
webglImage: require('./WebGL/webglImage.js'),
webglGraphics: require('./View/webglGraphics.js'),
// TODO: Deprecate this:
_webglUtil: {
parseColor: require('./WebGL/parseColor.js')
},
// TODO: move to svg namespace
svgGraphics: require('./View/svgGraphics.js'),
renderer: require('./View/renderer.js'),
// deprecated
cssGraphics: function() {
throw new Error('cssGraphics is deprecated. Please use older version of vivagraph (< 0.7) if you need it');
},
svgNodeFactory: function() {
throw new Error('svgNodeFactory is deprecated. Please use older version of vivagraph (< 0.7) if you need it');
},
community: function() {
throw new Error('community is deprecated. Please use vivagraph < 0.7 if you need it, or `https://github.com/anvaka/ngraph.slpa` module');
}
},
Rect: require('./Utils/rect.js'),
svg: require('simplesvg'),
// TODO: should be camelCase
BrowserInfo: require('./Utils/browserInfo.js')
};
module.exports = Viva;
},{"./Algorithms/centrality.js":36,"./Algorithms/operations.js":37,"./Input/domInputManager.js":38,"./Input/dragndrop.js":39,"./Input/webglInputManager.js":40,"./Layout/constant.js":41,"./Utils/backwardCompatibleEvents.js":42,"./Utils/browserInfo.js":43,"./Utils/findElementPosition.js":45,"./Utils/getDimensions.js":46,"./Utils/intersectRect.js":47,"./Utils/rect.js":49,"./Utils/timer.js":50,"./View/renderer.js":52,"./View/svgGraphics.js":53,"./View/webglGraphics.js":54,"./WebGL/parseColor.js":55,"./WebGL/texture.js":56,"./WebGL/webgl.js":57,"./WebGL/webglAtlas.js":58,"./WebGL/webglImage.js":59,"./WebGL/webglImageNodeProgram.js":60,"./WebGL/webglInputEvents.js":61,"./WebGL/webglLine.js":62,"./WebGL/webglLinkProgram.js":63,"./WebGL/webglNodeProgram.js":64,"./WebGL/webglSquare.js":65,"./version.js":66,"gintersect":3,"ngraph.events":9,"ngraph.forcelayout":11,"ngraph.fromjson":13,"ngraph.generators":14,"ngraph.graph":16,"ngraph.merge":17,"ngraph.random":30,"ngraph.tojson":31,"simplesvg":32}],2:[function(require,module,exports){
addEventListener.removeEventListener = removeEventListener
addEventListener.addEventListener = addEventListener
module.exports = addEventListener
var Events = null
function addEventListener(el, eventName, listener, useCapture) {
Events = Events || (
document.addEventListener ?
{add: stdAttach, rm: stdDetach} :
{add: oldIEAttach, rm: oldIEDetach}
)
return Events.add(el, eventName, listener, useCapture)
}
function removeEventListener(el, eventName, listener, useCapture) {
Events = Events || (
document.addEventListener ?
{add: stdAttach, rm: stdDetach} :
{add: oldIEAttach, rm: oldIEDetach}
)
return Events.rm(el, eventName, listener, useCapture)
}
function stdAttach(el, eventName, listener, useCapture) {
el.addEventListener(eventName, listener, useCapture)
}
function stdDetach(el, eventName, listener, useCapture) {
el.removeEventListener(eventName, listener, useCapture)
}
function oldIEAttach(el, eventName, listener, useCapture) {
if(useCapture) {
throw new Error('cannot useCapture in oldIE')
}
el.attachEvent('on' + eventName, listener)
}
function oldIEDetach(el, eventName, listener, useCapture) {
el.detachEvent('on' + eventName, listener)
}
},{}],3:[function(require,module,exports){
module.exports = intersect;
/**
* Original authors: Mukesh Prasad, Appeared in Graphics Gem II book
* http://www.opensource.apple.com/source/graphviz/graphviz-498/graphviz/dynagraph/common/xlines.c
* and adopted to javascript version by Andrei Kashcha.
*
* This function computes whether two line segments,
* respectively joining the input points (x1,y1) -- (x2,y2)
* and the input points (x3,y3) -- (x4,y4) intersect.
* If the lines intersect, the output variables x, y are
* set to coordinates of the point of intersection.
*
* @param {Number} x1 First line segment coordinates
* @param {Number} y1 First line segment coordinates
* @param {Number} x2 First line segment coordinates
* @param {Number} x2 First line segment coordinates
*
* @param {Number} x3 Second line segment coordinates
* @param {Number} y3 Second line segment coordinates
* @param {Number} x4 Second line segment coordinates
* @param {Number} x4 Second line segment coordinates
*
* @return {Object} x, y coordinates of intersection point or falsy value if no
* intersection found..
*/
function intersect(
x1, y1, x2, y2, // first line segment
x3, y3, x4, y4 // second line segment
) {
var a1, a2, b1, b2, c1, c2, /* Coefficients of line eqns. */
r1, r2, r3, r4, /* 'Sign' values */
denom, offset, num, /* Intermediate values */
result = {
x: 0,
y: 0
};
/* Compute a1, b1, c1, where line joining points 1 and 2
* is "a1 x + b1 y + c1 = 0".
*/
a1 = y2 - y1;
b1 = x1 - x2;
c1 = x2 * y1 - x1 * y2;
/* Compute r3 and r4.
*/
r3 = a1 * x3 + b1 * y3 + c1;
r4 = a1 * x4 + b1 * y4 + c1;
/* Check signs of r3 and r4. If both point 3 and point 4 lie on
* same side of line 1, the line segments do not intersect.
*/
if (r3 !== 0 && r4 !== 0 && ((r3 >= 0) === (r4 >= 4))) {
return null; //no intersection.
}
/* Compute a2, b2, c2 */
a2 = y4 - y3;
b2 = x3 - x4;
c2 = x4 * y3 - x3 * y4;
/* Compute r1 and r2 */
r1 = a2 * x1 + b2 * y1 + c2;
r2 = a2 * x2 + b2 * y2 + c2;
/* Check signs of r1 and r2. If both point 1 and point 2 lie
* on same side of second line segment, the line segments do
* not intersect.
*/
if (r1 !== 0 && r2 !== 0 && ((r1 >= 0) === (r2 >= 0))) {
return null; // no intersection;
}
/* Line segments intersect: compute intersection point.
*/
denom = a1 * b2 - a2 * b1;
if (denom === 0) {
return null; // Actually collinear..
}
offset = denom < 0 ? -denom / 2 : denom / 2;
offset = 0.0;
/* The denom/2 is to get rounding instead of truncating. It
* is added or subtracted to the numerator, depending upon the
* sign of the numerator.
*/
num = b1 * c2 - b2 * c1;
result.x = (num < 0 ? num - offset : num + offset) / denom;
num = a2 * c1 - a1 * c2;
result.y = (num < 0 ? num - offset : num + offset) / denom;
return result;
}
},{}],4:[function(require,module,exports){
module.exports.degree = require('./src/degree.js');
module.exports.betweenness = require('./src/betweenness.js');
module.exports.closeness = require('./src/closeness.js');
module.exports.eccentricity = require('./src/eccentricity.js');
},{"./src/betweenness.js":5,"./src/closeness.js":6,"./src/degree.js":7,"./src/eccentricity.js":8}],5:[function(require,module,exports){
module.exports = betweennes;
/**
* I'm using http://www.inf.uni-konstanz.de/algo/publications/b-vspbc-08.pdf
* as a reference for this implementation
*/
function betweennes(graph, oriented) {
var Q = [],
S = []; // Queue and Stack
// list of predcessors on shorteest paths from source
var pred = Object.create(null);
// distance from source
var dist = Object.create(null);
// number of shortest paths from source to key
var sigma = Object.create(null);
// dependency of source on key
var delta = Object.create(null);
var currentNode;
var centrality = Object.create(null);
graph.forEachNode(setCentralityToZero);
graph.forEachNode(calculateCentrality);
if (!oriented) {
// The centrality scores need to be divided by two if the graph is not oriented,
// since all shortest paths are considered twice
Object.keys(centrality).forEach(divideByTwo);
}
return centrality;
function divideByTwo(key) {
centrality[key] /= 2;
}
function setCentralityToZero(node) {
centrality[node.id] = 0;
}
function calculateCentrality(node) {
currentNode = node.id;
singleSourceShortestPath(currentNode);
accumulate();
}
function accumulate() {
graph.forEachNode(setDeltaToZero);
while (S.length) {
var w = S.pop();
var coeff = (1 + delta[w])/sigma[w];
var predcessors = pred[w];
for (var idx = 0; idx < predcessors.length; ++idx) {
var v = predcessors[idx];
delta[v] += sigma[v] * coeff;
}
if (w !== currentNode) {
centrality[w] += delta[w];
}
}
}
function setDeltaToZero(node) {
delta[node.id] = 0;
}
function singleSourceShortestPath(source) {
graph.forEachNode(initNode);
dist[source] = 0;
sigma[source] = 1;
Q.push(source);
while (Q.length) {
var v = Q.shift();
S.push(v);
graph.forEachLinkedNode(v, toId, oriented);
}
function toId(otherNode) {
// NOTE: This code will also consider multi-edges, which are often
// ignored by popular software (Gephi/NetworkX). Depending on your use
// case this may not be desired and deduping needs to be performed. To
// save memory I'm not deduping here...
processNode(otherNode.id);
}
function initNode(node) {
var nodeId = node.id;
pred[nodeId] = []; // empty list
dist[nodeId] = -1;
sigma[nodeId] = 0;
}
function processNode(w) {
// path discovery
if (dist[w] === -1) {
// Node w is found for the first time
dist[w] = dist[v] + 1;
Q.push(w);
}
// path counting
if (dist[w] === dist[v] + 1) {
// edge (v, w) on a shortest path
sigma[w] += sigma[v];
pred[w].push(v);
}
}
}
}
},{}],6:[function(require,module,exports){
module.exports = closeness;
/**
* In a connected graph, the normalized closeness centrality of a node is the average
* length of the shortest path between the node and all other nodes in the
* graph. Thus the more central a node is, the closer it is to all other nodes.
*/
function closeness(graph, oriented) {
var Q = [];
// list of predcessors on shortest paths from source
// distance from source
var dist = Object.create(null);
var currentNode;
var centrality = Object.create(null);
graph.forEachNode(setCentralityToZero);
graph.forEachNode(calculateCentrality);
return centrality;
function setCentralityToZero(node) {
centrality[node.id] = 0;
}
function calculateCentrality(node) {
currentNode = node.id;
singleSourceShortestPath(currentNode);
accumulate();
}
function accumulate() {
// Add all distances for node to array, excluding -1s
var distances = Object.keys(dist).map(function(key) {return dist[key]}).filter(function(val){return val !== -1});
// Set number of reachable nodes
var reachableNodesTotal = distances.length;
// Compute sum of all distances for node
var totalDistance = distances.reduce(function(a,b) { return a + b });
if (totalDistance > 0) {
centrality[currentNode] = ((reachableNodesTotal - 1) / totalDistance);
} else {
centrality[currentNode] = 0;
}
}
function singleSourceShortestPath(source) {
graph.forEachNode(initNode);
dist[source] = 0;
Q.push(source);
while (Q.length) {
var v = Q.shift();
graph.forEachLinkedNode(v, processNode, oriented);
}
function initNode(node) {
var nodeId = node.id;
dist[nodeId] = -1;
}
function processNode(otherNode) {
var w = otherNode.id
if (dist[w] === -1) {
// Node w is found for the first time
dist[w] = dist[v] + 1;
Q.push(w);
}
}
}
}
},{}],7:[function(require,module,exports){
module.exports = degree;
/**
* Calculates graph nodes degree centrality (in/out or both).
*
* @see http://en.wikipedia.org/wiki/Centrality#Degree_centrality
*
* @param {ngraph.graph} graph object for which we are calculating centrality.
* @param {string} [kind=both] What kind of degree centrality needs to be calculated:
* 'in' - calculate in-degree centrality
* 'out' - calculate out-degree centrality
* 'inout' - (default) generic degree centrality is calculated
*/
function degree(graph, kind) {
var getNodeDegree;
var result = Object.create(null);
kind = (kind || 'both').toLowerCase();
if (kind === 'both' || kind === 'inout') {
getNodeDegree = inoutDegreeCalculator;
} else if (kind === 'in') {
getNodeDegree = inDegreeCalculator;
} else if (kind === 'out') {
getNodeDegree = outDegreeCalculator;
} else {
throw new Error('Expected centrality degree kind is: in, out or both');
}
graph.forEachNode(calculateNodeDegree);
return result;
function calculateNodeDegree(node) {
var links = graph.getLinks(node.id);
result[node.id] = getNodeDegree(links, node.id);
}
}
function inDegreeCalculator(links, nodeId) {
var total = 0;
if (!links) return total;
for (var i = 0; i < links.length; i += 1) {
total += (links[i].toId === nodeId) ? 1 : 0;
}
return total;
}
function outDegreeCalculator(links, nodeId) {
var total = 0;
if (!links) return total;
for (var i = 0; i < links.length; i += 1) {
total += (links[i].fromId === nodeId) ? 1 : 0;
}
return total;
}
function inoutDegreeCalculator(links) {
if (!links) return 0;
return links.length;
}
},{}],8:[function(require,module,exports){
module.exports = eccentricity;
/**
* The eccentricity centrality of a node is the greatest distance between that node and
* any other node in the network.
*/
function eccentricity(graph, oriented) {
var Q = [];
// distance from source
var dist = Object.create(null);
var currentNode;
var centrality = Object.create(null);
graph.forEachNode(setCentralityToZero);
graph.forEachNode(calculateCentrality);
return centrality;
function setCentralityToZero(node) {
centrality[node.id] = 0;
}
function calculateCentrality(node) {
currentNode = node.id;
singleSourceShortestPath(currentNode);
accumulate();
}
function accumulate() {
var maxDist = 0;
Object.keys(dist).forEach(function (key) {
var val = dist[key];
if (maxDist < val) maxDist = val;
});
centrality[currentNode] = maxDist;
}
function singleSourceShortestPath(source) {
graph.forEachNode(initNode);
dist[source] = 0;
Q.push(source);
while (Q.length) {
var v = Q.shift();
graph.forEachLinkedNode(v, processNode, oriented);
}
function initNode(node) {
var nodeId = node.id;
dist[nodeId] = -1;
}
function processNode(otherNode) {
var w = otherNode.id
if (dist[w] === -1) {
// Node w is found for the first time
dist[w] = dist[v] + 1;
Q.push(w);
}
}
}
}
},{}],9:[function(require,module,exports){
module.exports = function(subject) {
validateSubject(subject);
var eventsStorage = createEventsStorage(subject);
subject.on = eventsStorage.on;
subject.off = eventsStorage.off;
subject.fire = eventsStorage.fire;
return subject;
};
function createEventsStorage(subject) {
// Store all event listeners to this hash. Key is event name, value is array
// of callback records.
//
// A callback record consists of callback function and its optional context:
// { 'eventName' => [{callback: function, ctx: object}] }
var registeredEvents = Object.create(null);
return {
on: function (eventName, callback, ctx) {
if (typeof callback !== 'function') {
throw new Error('callback is expected to be a function');
}
var handlers = registeredEvents[eventName];
if (!handlers) {
handlers = registeredEvents[eventName] = [];
}
handlers.push({callback: callback, ctx: ctx});
return subject;
},
off: function (eventName, callback) {
var wantToRemoveAll = (typeof eventName === 'undefined');
if (wantToRemoveAll) {
// Killing old events storage should be enough in this case:
registeredEvents = Object.create(null);
return subject;
}
if (registeredEvents[eventName]) {
var deleteAllCallbacksForEvent = (typeof callback !== 'function');
if (deleteAllCallbacksForEvent) {
delete registeredEvents[eventName];
} else {
var callbacks = registeredEvents[eventName];
for (var i = 0; i < callbacks.length; ++i) {
if (callbacks[i].callback === callback) {
callbacks.splice(i, 1);
}
}
}
}
return subject;
},
fire: function (eventName) {
var callbacks = registeredEvents[eventName];
if (!callbacks) {
return subject;
}
var fireArguments;
if (arguments.length > 1) {
fireArguments = Array.prototype.splice.call(arguments, 1);
}
for(var i = 0; i < callbacks.length; ++i) {
var callbackInfo = callbacks[i];
callbackInfo.callback.apply(callbackInfo.ctx, fireArguments);
}
return subject;
}
};
}
function validateSubject(subject) {
if (!subject) {
throw new Error('Eventify cannot use falsy object as events subject');
}
var reservedWords = ['on', 'fire', 'off'];
for (var i = 0; i < reservedWords.length; ++i) {
if (subject.hasOwnProperty(reservedWords[i])) {
throw new Error("Subject cannot be eventified, since it already has property '" + reservedWords[i] + "'");
}
}
}
},{}],10:[function(require,module,exports){
module.exports = exposeProperties;
/**
* Augments `target` object with getter/setter functions, which modify settings
*
* @example
* var target = {};
* exposeProperties({ age: 42}, target);
* target.age(); // returns 42
* target.age(24); // make age 24;
*
* var filteredTarget = {};
* exposeProperties({ age: 42, name: 'John'}, filteredTarget, ['name']);
* filteredTarget.name(); // returns 'John'
* filteredTarget.age === undefined; // true
*/
function exposeProperties(settings, target, filter) {
var needsFilter = Object.prototype.toString.call(filter) === '[object Array]';
if (needsFilter) {
for (var i = 0; i < filter.length; ++i) {
augment(settings, target, filter[i]);
}
} else {
for (var key in settings) {
augment(settings, target, key);
}
}
}
function augment(source, target, key) {
if (source.hasOwnProperty(key)) {
if (typeof target[key] === 'function') {
// this accessor is already defined. Ignore it
return;
}
target[key] = function (value) {
if (value !== undefined) {
source[key] = value;
return target;
}
return source[key];
}
}
}
},{}],11:[function(require,module,exports){
module.exports = createLayout;
module.exports.simulator = require('ngraph.physics.simulator');
var eventify = require('ngraph.events');
/**
* Creates force based layout for a given graph.
*
* @param {ngraph.graph} graph which needs to be laid out
* @param {object} physicsSettings if you need custom settings
* for physics simulator you can pass your own settings here. If it's not passed
* a default one will be created.
*/
function createLayout(graph, physicsSettings) {
if (!graph) {
throw new Error('Graph structure cannot be undefined');
}
var createSimulator = require('ngraph.physics.simulator');
var physicsSimulator = createSimulator(physicsSettings);
var nodeMass = defaultNodeMass
if (physicsSettings && typeof physicsSettings.nodeMass === 'function') {
nodeMass = physicsSettings.nodeMass
}
var nodeBodies = Object.create(null);
var springs = {};
var bodiesCount = 0;
var springTransform = physicsSimulator.settings.springTransform || noop;
// Initialize physics with what we have in the graph:
initPhysics();
listenToEvents();
var wasStable = false;
var api = {
/**
* Performs one step of iterative layout algorithm
*
* @returns {boolean} true if the system should be considered stable; Flase otherwise.
* The system is stable if no further call to `step()` can improve the layout.
*/
step: function() {
if (bodiesCount === 0) return true; // TODO: This will never fire 'stable'
var lastMove = physicsSimulator.step();
// Save the movement in case if someone wants to query it in the step
// callback.
api.lastMove = lastMove;
// Allow listeners to perform low-level actions after nodes are updated.
api.fire('step');
var ratio = lastMove/bodiesCount;
var isStableNow = ratio <= 0.01; // TODO: The number is somewhat arbitrary...
if (wasStable !== isStableNow) {
wasStable = isStableNow;
onStableChanged(isStableNow);
}
return isStableNow;
},
/**
* For a given `nodeId` returns position
*/
getNodePosition: function (nodeId) {
return getInitializedBody(nodeId).pos;
},
/**
* Sets position of a node to a given coordinates
* @param {string} nodeId node identifier
* @param {number} x position of a node
* @param {number} y position of a node
* @param {number=} z position of node (only if applicable to body)
*/
setNodePosition: function (nodeId) {
var body = getInitializedBody(nodeId);
body.setPosition.apply(body, Array.prototype.slice.call(arguments, 1));
physicsSimulator.invalidateBBox();
},
/**
* @returns {Object} Link position by link id
* @returns {Object.from} {x, y} coordinates of link start
* @returns {Object.to} {x, y} coordinates of link end
*/
getLinkPosition: function (linkId) {
var spring = springs[linkId];
if (spring) {
return {
from: spring.from.pos,
to: spring.to.pos
};
}
},
/**
* @returns {Object} area required to fit in the graph. Object contains
* `x1`, `y1` - top left coordinates
* `x2`, `y2` - bottom right coordinates
*/
getGraphRect: function () {
return physicsSimulator.getBBox();
},
/**
* Iterates over each body in the layout simulator and performs a callback(body, nodeId)
*/
forEachBody: forEachBody,
/*
* Requests layout algorithm to pin/unpin node to its current position
* Pinned nodes should not be affected by layout algorithm and always
* remain at their position
*/
pinNode: function (node, isPinned) {
var body = getInitializedBody(node.id);
body.isPinned = !!isPinned;
},
/**
* Checks whether given graph's node is currently pinned
*/
isNodePinned: function (node) {
return getInitializedBody(node.id).isPinned;
},
/**
* Request to release all resources
*/
dispose: function() {
graph.off('changed', onGraphChanged);
api.fire('disposed');
},
/**
* Gets physical body for a given node id. If node is not found undefined
* value is returned.
*/
getBody: getBody,
/**
* Gets spring for a given edge.
*
* @param {string} linkId link identifer. If two arguments are passed then
* this argument is treated as formNodeId
* @param {string=} toId when defined this parameter denotes head of the link
* and first argument is trated as tail of the link (fromId)
*/
getSpring: getSpring,
/**
* [Read only] Gets current physics simulator
*/
simulator: physicsSimulator,
/**
* Gets the graph that was used for layout
*/
graph: graph,
/**
* Gets amount of movement performed during last step opeartion
*/
lastMove: 0
};
eventify(api);
return api;
function forEachBody(cb) {
Object.keys(nodeBodies).forEach(function(bodyId) {
cb(nodeBodies[bodyId], bodyId);
});
}
function getSpring(fromId, toId) {
var linkId;
if (toId === undefined) {
if (typeof fromId !== 'object') {
// assume fromId as a linkId:
linkId = fromId;
} else {
// assume fromId to be a link object:
linkId = fromId.id;
}
} else {
// toId is defined, should grab link:
var link = graph.hasLink(fromId, toId);
if (!link) return;
linkId = link.id;
}
return springs[linkId];
}
function getBody(nodeId) {
return nodeBodies[nodeId];
}
function listenToEvents() {
graph.on('changed', onGraphChanged);
}
function onStableChanged(isStable) {
api.fire('stable', isStable);
}
function onGraphChanged(changes) {
for (var i = 0; i < changes.length; ++i) {
var change = changes[i];
if (change.changeType === 'add') {
if (change.node) {
initBody(change.node.id);
}
if (change.link) {
initLink(change.link);
}
} else if (change.changeType === 'remove') {
if (change.node) {
releaseNode(change.node);
}
if (change.link) {
releaseLink(change.link);
}
}
}
bodiesCount = graph.getNodesCount();
}
function initPhysics() {
bodiesCount = 0;
graph.forEachNode(function (node) {
initBody(node.id);
bodiesCount += 1;
});
graph.forEachLink(initLink);
}
function initBody(nodeId) {
var body = nodeBodies[nodeId];
if (!body) {
var node = graph.getNode(nodeId);
if (!node) {
throw new Error('initBody() was called with unknown node id');
}
var pos = node.position;
if (!pos) {
var neighbors = getNeighborBodies(node);
pos = physicsSimulator.getBestNewBodyPosition(neighbors);
}
body = physicsSimulator.addBodyAt(pos);
body.id = nodeId;
nodeBodies[nodeId] = body;
updateBodyMass(nodeId);
if (isNodeOriginallyPinned(node)) {
body.isPinned = true;
}
}
}
function releaseNode(node) {
var nodeId = node.id;
var body = nodeBodies[nodeId];
if (body) {
nodeBodies[nodeId] = null;
delete nodeBodies[nodeId];