-
Notifications
You must be signed in to change notification settings - Fork 8
/
dagre.js
11478 lines (9956 loc) · 315 KB
/
dagre.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(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.dagre = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
/*
Copyright (c) 2012-2014 Chris Pettitt
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
module.exports = {
graphlib: require("./lib/graphlib"),
layout: require("./lib/layout"),
debug: require("./lib/debug"),
util: {
time: require("./lib/util").time,
notime: require("./lib/util").notime
},
version: require("./lib/version")
};
},{"./lib/debug":6,"./lib/graphlib":7,"./lib/layout":9,"./lib/util":29,"./lib/version":30}],2:[function(require,module,exports){
"use strict";
var _ = require("./lodash"),
greedyFAS = require("./greedy-fas");
module.exports = {
run: run,
undo: undo
};
function run(g) {
var fas = (g.graph().acyclicer === "greedy"
? greedyFAS(g, weightFn(g))
: dfsFAS(g));
_.forEach(fas, function(e) {
var label = g.edge(e);
g.removeEdge(e);
label.forwardName = e.name;
label.reversed = true;
g.setEdge(e.w, e.v, label, _.uniqueId("rev"));
});
function weightFn(g) {
return function(e) {
return g.edge(e).weight;
};
}
}
function dfsFAS(g) {
var fas = [],
stack = {},
visited = {};
function dfs(v) {
if (_.has(visited, v)) {
return;
}
visited[v] = true;
stack[v] = true;
_.forEach(g.outEdges(v), function(e) {
if (_.has(stack, e.w)) {
fas.push(e);
} else {
dfs(e.w);
}
});
delete stack[v];
}
_.forEach(g.nodes(), dfs);
return fas;
}
function undo(g) {
_.forEach(g.edges(), function(e) {
var label = g.edge(e);
if (label.reversed) {
g.removeEdge(e);
var forwardName = label.forwardName;
delete label.reversed;
delete label.forwardName;
g.setEdge(e.w, e.v, label, forwardName);
}
});
}
},{"./greedy-fas":8,"./lodash":10}],3:[function(require,module,exports){
var _ = require("./lodash"),
util = require("./util");
module.exports = addBorderSegments;
function addBorderSegments(g) {
function dfs(v) {
var children = g.children(v),
node = g.node(v);
if (children.length) {
_.forEach(children, dfs);
}
if (_.has(node, "minRank")) {
node.borderLeft = [];
node.borderRight = [];
for (var rank = node.minRank, maxRank = node.maxRank + 1;
rank < maxRank;
++rank) {
addBorderNode(g, "borderLeft", "_bl", v, node, rank);
addBorderNode(g, "borderRight", "_br", v, node, rank);
}
}
}
_.forEach(g.children(), dfs);
}
function addBorderNode(g, prop, prefix, sg, sgNode, rank) {
var label = { width: 0, height: 0, rank: rank, borderType: prop },
prev = sgNode[prop][rank - 1],
curr = util.addDummyNode(g, "border", label, prefix);
sgNode[prop][rank] = curr;
g.setParent(curr, sg);
if (prev) {
g.setEdge(prev, curr, { weight: 1 });
}
}
},{"./lodash":10,"./util":29}],4:[function(require,module,exports){
"use strict";
var _ = require("./lodash");
module.exports = {
adjust: adjust,
undo: undo
};
function adjust(g) {
var rankDir = g.graph().rankdir.toLowerCase();
if (rankDir === "lr" || rankDir === "rl") {
swapWidthHeight(g);
}
}
function undo(g) {
var rankDir = g.graph().rankdir.toLowerCase();
if (rankDir === "bt" || rankDir === "rl") {
reverseY(g);
}
if (rankDir === "lr" || rankDir === "rl") {
swapXY(g);
swapWidthHeight(g);
}
}
function swapWidthHeight(g) {
_.forEach(g.nodes(), function(v) { swapWidthHeightOne(g.node(v)); });
_.forEach(g.edges(), function(e) { swapWidthHeightOne(g.edge(e)); });
}
function swapWidthHeightOne(attrs) {
var w = attrs.width;
attrs.width = attrs.height;
attrs.height = w;
}
function reverseY(g) {
_.forEach(g.nodes(), function(v) { reverseYOne(g.node(v)); });
_.forEach(g.edges(), function(e) {
var edge = g.edge(e);
_.forEach(edge.points, reverseYOne);
if (_.has(edge, "y")) {
reverseYOne(edge);
}
});
}
function reverseYOne(attrs) {
attrs.y = -attrs.y;
}
function swapXY(g) {
_.forEach(g.nodes(), function(v) { swapXYOne(g.node(v)); });
_.forEach(g.edges(), function(e) {
var edge = g.edge(e);
_.forEach(edge.points, swapXYOne);
if (_.has(edge, "x")) {
swapXYOne(edge);
}
});
}
function swapXYOne(attrs) {
var x = attrs.x;
attrs.x = attrs.y;
attrs.y = x;
}
},{"./lodash":10}],5:[function(require,module,exports){
/*
* Simple doubly linked list implementation derived from Cormen, et al.,
* "Introduction to Algorithms".
*/
module.exports = List;
function List() {
var sentinel = {};
sentinel._next = sentinel._prev = sentinel;
this._sentinel = sentinel;
}
List.prototype.dequeue = function() {
var sentinel = this._sentinel,
entry = sentinel._prev;
if (entry !== sentinel) {
unlink(entry);
return entry;
}
};
List.prototype.enqueue = function(entry) {
var sentinel = this._sentinel;
if (entry._prev && entry._next) {
unlink(entry);
}
entry._next = sentinel._next;
sentinel._next._prev = entry;
sentinel._next = entry;
entry._prev = sentinel;
};
List.prototype.toString = function() {
var strs = [],
sentinel = this._sentinel,
curr = sentinel._prev;
while (curr !== sentinel) {
strs.push(JSON.stringify(curr, filterOutLinks));
curr = curr._prev;
}
return "[" + strs.join(", ") + "]";
};
function unlink(entry) {
entry._prev._next = entry._next;
entry._next._prev = entry._prev;
delete entry._next;
delete entry._prev;
}
function filterOutLinks(k, v) {
if (k !== "_next" && k !== "_prev") {
return v;
}
}
},{}],6:[function(require,module,exports){
var _ = require("./lodash"),
util = require("./util"),
Graph = require("./graphlib").Graph;
module.exports = {
debugOrdering: debugOrdering
};
/* istanbul ignore next */
function debugOrdering(g) {
var layerMatrix = util.buildLayerMatrix(g);
var h = new Graph({ compound: true, multigraph: true }).setGraph({});
_.forEach(g.nodes(), function(v) {
h.setNode(v, { label: v });
h.setParent(v, "layer" + g.node(v).rank);
});
_.forEach(g.edges(), function(e) {
h.setEdge(e.v, e.w, {}, e.name);
});
_.forEach(layerMatrix, function(layer, i) {
var layerV = "layer" + i;
h.setNode(layerV, { rank: "same" });
_.reduce(layer, function(u, v) {
h.setEdge(u, v, { style: "invis" });
return v;
});
});
return h;
}
},{"./graphlib":7,"./lodash":10,"./util":29}],7:[function(require,module,exports){
/* global window */
var graphlib;
if (typeof require === "function") {
try {
graphlib = require("graphlib");
} catch (e) {}
}
if (!graphlib) {
graphlib = window.graphlib;
}
module.exports = graphlib;
},{"graphlib":31}],8:[function(require,module,exports){
var _ = require("./lodash"),
Graph = require("./graphlib").Graph,
List = require("./data/list");
/*
* A greedy heuristic for finding a feedback arc set for a graph. A feedback
* arc set is a set of edges that can be removed to make a graph acyclic.
* The algorithm comes from: P. Eades, X. Lin, and W. F. Smyth, "A fast and
* effective heuristic for the feedback arc set problem." This implementation
* adjusts that from the paper to allow for weighted edges.
*/
module.exports = greedyFAS;
var DEFAULT_WEIGHT_FN = _.constant(1);
function greedyFAS(g, weightFn) {
if (g.nodeCount() <= 1) {
return [];
}
var state = buildState(g, weightFn || DEFAULT_WEIGHT_FN);
var results = doGreedyFAS(state.graph, state.buckets, state.zeroIdx);
// Expand multi-edges
return _.flatten(_.map(results, function(e) {
return g.outEdges(e.v, e.w);
}), true);
}
function doGreedyFAS(g, buckets, zeroIdx) {
var results = [],
sources = buckets[buckets.length - 1],
sinks = buckets[0];
var entry;
while (g.nodeCount()) {
while ((entry = sinks.dequeue())) { removeNode(g, buckets, zeroIdx, entry); }
while ((entry = sources.dequeue())) { removeNode(g, buckets, zeroIdx, entry); }
if (g.nodeCount()) {
for (var i = buckets.length - 2; i > 0; --i) {
entry = buckets[i].dequeue();
if (entry) {
results = results.concat(removeNode(g, buckets, zeroIdx, entry, true));
break;
}
}
}
}
return results;
}
function removeNode(g, buckets, zeroIdx, entry, collectPredecessors) {
var results = collectPredecessors ? [] : undefined;
_.forEach(g.inEdges(entry.v), function(edge) {
var weight = g.edge(edge),
uEntry = g.node(edge.v);
if (collectPredecessors) {
results.push({ v: edge.v, w: edge.w });
}
uEntry.out -= weight;
assignBucket(buckets, zeroIdx, uEntry);
});
_.forEach(g.outEdges(entry.v), function(edge) {
var weight = g.edge(edge),
w = edge.w,
wEntry = g.node(w);
wEntry["in"] -= weight;
assignBucket(buckets, zeroIdx, wEntry);
});
g.removeNode(entry.v);
return results;
}
function buildState(g, weightFn) {
var fasGraph = new Graph(),
maxIn = 0,
maxOut = 0;
_.forEach(g.nodes(), function(v) {
fasGraph.setNode(v, { v: v, "in": 0, out: 0 });
});
// Aggregate weights on nodes, but also sum the weights across multi-edges
// into a single edge for the fasGraph.
_.forEach(g.edges(), function(e) {
var prevWeight = fasGraph.edge(e.v, e.w) || 0,
weight = weightFn(e),
edgeWeight = prevWeight + weight;
fasGraph.setEdge(e.v, e.w, edgeWeight);
maxOut = Math.max(maxOut, fasGraph.node(e.v).out += weight);
maxIn = Math.max(maxIn, fasGraph.node(e.w)["in"] += weight);
});
var buckets = _.range(maxOut + maxIn + 3).map(function() { return new List(); });
var zeroIdx = maxIn + 1;
_.forEach(fasGraph.nodes(), function(v) {
assignBucket(buckets, zeroIdx, fasGraph.node(v));
});
return { graph: fasGraph, buckets: buckets, zeroIdx: zeroIdx };
}
function assignBucket(buckets, zeroIdx, entry) {
if (!entry.out) {
buckets[0].enqueue(entry);
} else if (!entry["in"]) {
buckets[buckets.length - 1].enqueue(entry);
} else {
buckets[entry.out - entry["in"] + zeroIdx].enqueue(entry);
}
}
},{"./data/list":5,"./graphlib":7,"./lodash":10}],9:[function(require,module,exports){
"use strict";
var _ = require("./lodash"),
acyclic = require("./acyclic"),
normalize = require("./normalize"),
rank = require("./rank"),
normalizeRanks = require("./util").normalizeRanks,
parentDummyChains = require("./parent-dummy-chains"),
removeEmptyRanks = require("./util").removeEmptyRanks,
nestingGraph = require("./nesting-graph"),
addBorderSegments = require("./add-border-segments"),
coordinateSystem = require("./coordinate-system"),
order = require("./order"),
position = require("./position"),
util = require("./util"),
Graph = require("./graphlib").Graph;
module.exports = layout;
function layout(g, opts) {
var time = opts && opts.debugTiming ? util.time : util.notime;
time("layout", function() {
var layoutGraph = time(" buildLayoutGraph",
function() { return buildLayoutGraph(g); });
time(" runLayout", function() { runLayout(layoutGraph, time); });
time(" updateInputGraph", function() { updateInputGraph(g, layoutGraph); });
});
}
function runLayout(g, time) {
time(" makeSpaceForEdgeLabels", function() { makeSpaceForEdgeLabels(g); });
time(" removeSelfEdges", function() { removeSelfEdges(g); });
time(" acyclic", function() { acyclic.run(g); });
time(" nestingGraph.run", function() { nestingGraph.run(g); });
time(" rank", function() { rank(util.asNonCompoundGraph(g)); });
time(" injectEdgeLabelProxies", function() { injectEdgeLabelProxies(g); });
time(" removeEmptyRanks", function() { removeEmptyRanks(g); });
time(" nestingGraph.cleanup", function() { nestingGraph.cleanup(g); });
time(" normalizeRanks", function() { normalizeRanks(g); });
time(" assignRankMinMax", function() { assignRankMinMax(g); });
time(" removeEdgeLabelProxies", function() { removeEdgeLabelProxies(g); });
time(" normalize.run", function() { normalize.run(g); });
time(" parentDummyChains", function() { parentDummyChains(g); });
time(" addBorderSegments", function() { addBorderSegments(g); });
time(" order", function() { order(g); });
time(" insertSelfEdges", function() { insertSelfEdges(g); });
time(" adjustCoordinateSystem", function() { coordinateSystem.adjust(g); });
time(" position", function() { position(g); });
time(" positionSelfEdges", function() { positionSelfEdges(g); });
time(" removeBorderNodes", function() { removeBorderNodes(g); });
time(" normalize.undo", function() { normalize.undo(g); });
time(" fixupEdgeLabelCoords", function() { fixupEdgeLabelCoords(g); });
time(" undoCoordinateSystem", function() { coordinateSystem.undo(g); });
time(" translateGraph", function() { translateGraph(g); });
time(" assignNodeIntersects", function() { assignNodeIntersects(g); });
time(" reversePoints", function() { reversePointsForReversedEdges(g); });
time(" acyclic.undo", function() { acyclic.undo(g); });
}
/*
* Copies final layout information from the layout graph back to the input
* graph. This process only copies whitelisted attributes from the layout graph
* to the input graph, so it serves as a good place to determine what
* attributes can influence layout.
*/
function updateInputGraph(inputGraph, layoutGraph) {
_.forEach(inputGraph.nodes(), function(v) {
var inputLabel = inputGraph.node(v),
layoutLabel = layoutGraph.node(v);
if (inputLabel) {
inputLabel.x = layoutLabel.x;
inputLabel.y = layoutLabel.y;
if (layoutGraph.children(v).length) {
inputLabel.width = layoutLabel.width;
inputLabel.height = layoutLabel.height;
}
}
});
_.forEach(inputGraph.edges(), function(e) {
var inputLabel = inputGraph.edge(e),
layoutLabel = layoutGraph.edge(e);
inputLabel.points = layoutLabel.points;
if (_.has(layoutLabel, "x")) {
inputLabel.x = layoutLabel.x;
inputLabel.y = layoutLabel.y;
}
});
inputGraph.graph().width = layoutGraph.graph().width;
inputGraph.graph().height = layoutGraph.graph().height;
}
var graphNumAttrs = ["nodesep", "edgesep", "ranksep", "marginx", "marginy"],
graphDefaults = { ranksep: 50, edgesep: 20, nodesep: 50, rankdir: "tb" },
graphAttrs = ["acyclicer", "ranker", "rankdir", "align"],
nodeNumAttrs = ["width", "height"],
nodeDefaults = { width: 0, height: 0 },
edgeNumAttrs = ["minlen", "weight", "width", "height", "labeloffset"],
edgeDefaults = {
minlen: 1, weight: 1, width: 0, height: 0,
labeloffset: 10, labelpos: "r"
},
edgeAttrs = ["labelpos"];
/*
* Constructs a new graph from the input graph, which can be used for layout.
* This process copies only whitelisted attributes from the input graph to the
* layout graph. Thus this function serves as a good place to determine what
* attributes can influence layout.
*/
function buildLayoutGraph(inputGraph) {
var g = new Graph({ multigraph: true, compound: true }),
graph = canonicalize(inputGraph.graph());
g.setGraph(_.merge({},
graphDefaults,
selectNumberAttrs(graph, graphNumAttrs),
_.pick(graph, graphAttrs)));
_.forEach(inputGraph.nodes(), function(v) {
var node = canonicalize(inputGraph.node(v));
g.setNode(v, _.defaults(selectNumberAttrs(node, nodeNumAttrs), nodeDefaults));
g.setParent(v, inputGraph.parent(v));
});
_.forEach(inputGraph.edges(), function(e) {
var edge = canonicalize(inputGraph.edge(e));
g.setEdge(e, _.merge({},
edgeDefaults,
selectNumberAttrs(edge, edgeNumAttrs),
_.pick(edge, edgeAttrs)));
});
return g;
}
/*
* This idea comes from the Gansner paper: to account for edge labels in our
* layout we split each rank in half by doubling minlen and halving ranksep.
* Then we can place labels at these mid-points between nodes.
*
* We also add some minimal padding to the width to push the label for the edge
* away from the edge itself a bit.
*/
function makeSpaceForEdgeLabels(g) {
var graph = g.graph();
graph.ranksep /= 2;
_.forEach(g.edges(), function(e) {
var edge = g.edge(e);
edge.minlen *= 2;
if (edge.labelpos.toLowerCase() !== "c") {
if (graph.rankdir === "TB" || graph.rankdir === "BT") {
edge.width += edge.labeloffset;
} else {
edge.height += edge.labeloffset;
}
}
});
}
/*
* Creates temporary dummy nodes that capture the rank in which each edge's
* label is going to, if it has one of non-zero width and height. We do this
* so that we can safely remove empty ranks while preserving balance for the
* label's position.
*/
function injectEdgeLabelProxies(g) {
_.forEach(g.edges(), function(e) {
var edge = g.edge(e);
if (edge.width && edge.height) {
var v = g.node(e.v),
w = g.node(e.w),
label = { rank: (w.rank - v.rank) / 2 + v.rank, e: e };
util.addDummyNode(g, "edge-proxy", label, "_ep");
}
});
}
function assignRankMinMax(g) {
var maxRank = 0;
_.forEach(g.nodes(), function(v) {
var node = g.node(v);
if (node.borderTop) {
node.minRank = g.node(node.borderTop).rank;
node.maxRank = g.node(node.borderBottom).rank;
maxRank = _.max(maxRank, node.maxRank);
}
});
g.graph().maxRank = maxRank;
}
function removeEdgeLabelProxies(g) {
_.forEach(g.nodes(), function(v) {
var node = g.node(v);
if (node.dummy === "edge-proxy") {
g.edge(node.e).labelRank = node.rank;
g.removeNode(v);
}
});
}
function translateGraph(g) {
var minX = Number.POSITIVE_INFINITY,
maxX = 0,
minY = Number.POSITIVE_INFINITY,
maxY = 0,
graphLabel = g.graph(),
marginX = graphLabel.marginx || 0,
marginY = graphLabel.marginy || 0;
function getExtremes(attrs) {
var x = attrs.x,
y = attrs.y,
w = attrs.width,
h = attrs.height;
minX = Math.min(minX, x - w / 2);
maxX = Math.max(maxX, x + w / 2);
minY = Math.min(minY, y - h / 2);
maxY = Math.max(maxY, y + h / 2);
}
_.forEach(g.nodes(), function(v) { getExtremes(g.node(v)); });
_.forEach(g.edges(), function(e) {
var edge = g.edge(e);
if (_.has(edge, "x")) {
getExtremes(edge);
}
});
minX -= marginX;
minY -= marginY;
_.forEach(g.nodes(), function(v) {
var node = g.node(v);
node.x -= minX;
node.y -= minY;
});
_.forEach(g.edges(), function(e) {
var edge = g.edge(e);
_.forEach(edge.points, function(p) {
p.x -= minX;
p.y -= minY;
});
if (_.has(edge, "x")) { edge.x -= minX; }
if (_.has(edge, "y")) { edge.y -= minY; }
});
graphLabel.width = maxX - minX + marginX;
graphLabel.height = maxY - minY + marginY;
}
function assignNodeIntersects(g) {
_.forEach(g.edges(), function(e) {
var edge = g.edge(e),
nodeV = g.node(e.v),
nodeW = g.node(e.w),
p1, p2;
if (!edge.points) {
edge.points = [];
p1 = nodeW;
p2 = nodeV;
} else {
p1 = edge.points[0];
p2 = edge.points[edge.points.length - 1];
}
edge.points.unshift(util.intersectRect(nodeV, p1));
edge.points.push(util.intersectRect(nodeW, p2));
});
}
function fixupEdgeLabelCoords(g) {
_.forEach(g.edges(), function(e) {
var edge = g.edge(e);
if (_.has(edge, "x")) {
if (edge.labelpos === "l" || edge.labelpos === "r") {
edge.width -= edge.labeloffset;
}
switch (edge.labelpos) {
case "l": edge.x -= edge.width / 2 + edge.labeloffset; break;
case "r": edge.x += edge.width / 2 + edge.labeloffset; break;
}
}
});
}
function reversePointsForReversedEdges(g) {
_.forEach(g.edges(), function(e) {
var edge = g.edge(e);
if (edge.reversed) {
edge.points.reverse();
}
});
}
function removeBorderNodes(g) {
_.forEach(g.nodes(), function(v) {
if (g.children(v).length) {
var node = g.node(v),
t = g.node(node.borderTop),
b = g.node(node.borderBottom),
l = g.node(_.last(node.borderLeft)),
r = g.node(_.last(node.borderRight));
node.width = Math.abs(r.x - l.x);
node.height = Math.abs(b.y - t.y);
node.x = l.x + node.width / 2;
node.y = t.y + node.height / 2;
}
});
_.forEach(g.nodes(), function(v) {
if (g.node(v).dummy === "border") {
g.removeNode(v);
}
});
}
function removeSelfEdges(g) {
_.forEach(g.edges(), function(e) {
if (e.v === e.w) {
var node = g.node(e.v);
if (!node.selfEdges) {
node.selfEdges = [];
}
node.selfEdges.push({ e: e, label: g.edge(e) });
g.removeEdge(e);
}
});
}
function insertSelfEdges(g) {
var layers = util.buildLayerMatrix(g);
_.forEach(layers, function(layer) {
var orderShift = 0;
_.forEach(layer, function(v, i) {
var node = g.node(v);
node.order = i + orderShift;
_.forEach(node.selfEdges, function(selfEdge) {
util.addDummyNode(g, "selfedge", {
width: selfEdge.label.width,
height: selfEdge.label.height,
rank: node.rank,
order: i + (++orderShift),
e: selfEdge.e,
label: selfEdge.label
}, "_se");
});
delete node.selfEdges;
});
});
}
function positionSelfEdges(g) {
_.forEach(g.nodes(), function(v) {
var node = g.node(v);
if (node.dummy === "selfedge") {
var selfNode = g.node(node.e.v),
x = selfNode.x + selfNode.width / 2,
y = selfNode.y,
dx = node.x - x,
dy = selfNode.height / 2;
g.setEdge(node.e, node.label);
g.removeNode(v);
node.label.points = [
{ x: x + 2 * dx / 3, y: y - dy },
{ x: x + 5 * dx / 6, y: y - dy },
{ x: x + dx , y: y },
{ x: x + 5 * dx / 6, y: y + dy },
{ x: x + 2 * dx / 3, y: y + dy }
];
node.label.x = node.x;
node.label.y = node.y;
}
});
}
function selectNumberAttrs(obj, attrs) {
return _.mapValues(_.pick(obj, attrs), Number);
}
function canonicalize(attrs) {
var newAttrs = {};
_.forEach(attrs, function(v, k) {
newAttrs[k.toLowerCase()] = v;
});
return newAttrs;
}
},{"./acyclic":2,"./add-border-segments":3,"./coordinate-system":4,"./graphlib":7,"./lodash":10,"./nesting-graph":11,"./normalize":12,"./order":17,"./parent-dummy-chains":22,"./position":24,"./rank":26,"./util":29}],10:[function(require,module,exports){
/* global window */
var lodash;
if (typeof require === "function") {
try {
lodash = {
cloneDeep: require("lodash/cloneDeep"),
constant: require("lodash/constant"),
defaults: require("lodash/defaults"),
each: require("lodash/each"),
filter: require("lodash/filter"),
find: require("lodash/find"),
flatten: require("lodash/flatten"),
forEach: require("lodash/forEach"),
forIn: require("lodash/forIn"),
has: require("lodash/has"),
isUndefined: require("lodash/isUndefined"),
last: require("lodash/last"),
map: require("lodash/map"),
mapValues: require("lodash/mapValues"),
max: require("lodash/max"),
merge: require("lodash/merge"),
min: require("lodash/min"),
minBy: require("lodash/minBy"),
now: require("lodash/now"),
pick: require("lodash/pick"),
range: require("lodash/range"),
reduce: require("lodash/reduce"),
sortBy: require("lodash/sortBy"),
uniqueId: require("lodash/uniqueId"),
values: require("lodash/values"),
zipObject: require("lodash/zipObject"),
};
} catch (e) {}
}
if (!lodash) {
lodash = window._;
}
module.exports = lodash;
},{"lodash/cloneDeep":227,"lodash/constant":228,"lodash/defaults":229,"lodash/each":230,"lodash/filter":232,"lodash/find":233,"lodash/flatten":235,"lodash/forEach":236,"lodash/forIn":237,"lodash/has":239,"lodash/isUndefined":258,"lodash/last":261,"lodash/map":262,"lodash/mapValues":263,"lodash/max":264,"lodash/merge":266,"lodash/min":267,"lodash/minBy":268,"lodash/now":270,"lodash/pick":271,"lodash/range":273,"lodash/reduce":274,"lodash/sortBy":276,"lodash/uniqueId":286,"lodash/values":287,"lodash/zipObject":288}],11:[function(require,module,exports){
var _ = require("./lodash"),
util = require("./util");
module.exports = {
run: run,
cleanup: cleanup
};
/*
* A nesting graph creates dummy nodes for the tops and bottoms of subgraphs,
* adds appropriate edges to ensure that all cluster nodes are placed between
* these boundries, and ensures that the graph is connected.
*
* In addition we ensure, through the use of the minlen property, that nodes
* and subgraph border nodes to not end up on the same rank.
*
* Preconditions:
*
* 1. Input graph is a DAG
* 2. Nodes in the input graph has a minlen attribute
*
* Postconditions:
*
* 1. Input graph is connected.
* 2. Dummy nodes are added for the tops and bottoms of subgraphs.
* 3. The minlen attribute for nodes is adjusted to ensure nodes do not
* get placed on the same rank as subgraph border nodes.
*
* The nesting graph idea comes from Sander, "Layout of Compound Directed
* Graphs."
*/
function run(g) {
var root = util.addDummyNode(g, "root", {}, "_root");
var depths = treeDepths(g);
var height = _.max(_.values(depths)) - 1; // Note: depths is an Object not an array
var nodeSep = 2 * height + 1;
g.graph().nestingRoot = root;
// Multiply minlen by nodeSep to align nodes on non-border ranks.
_.forEach(g.edges(), function(e) { g.edge(e).minlen *= nodeSep; });
// Calculate a weight that is sufficient to keep subgraphs vertically compact
var weight = sumWeights(g) + 1;
// Create border nodes and link them up
_.forEach(g.children(), function(child) {
dfs(g, root, nodeSep, weight, height, depths, child);
});
// Save the multiplier for node layers for later removal of empty border
// layers.
g.graph().nodeRankFactor = nodeSep;
}
function dfs(g, root, nodeSep, weight, height, depths, v) {
var children = g.children(v);
if (!children.length) {
if (v !== root) {
g.setEdge(root, v, { weight: 0, minlen: nodeSep });
}
return;
}
var top = util.addBorderNode(g, "_bt"),
bottom = util.addBorderNode(g, "_bb"),
label = g.node(v);
g.setParent(top, v);
label.borderTop = top;
g.setParent(bottom, v);
label.borderBottom = bottom;
_.forEach(children, function(child) {
dfs(g, root, nodeSep, weight, height, depths, child);
var childNode = g.node(child),
childTop = childNode.borderTop ? childNode.borderTop : child,
childBottom = childNode.borderBottom ? childNode.borderBottom : child,
thisWeight = childNode.borderTop ? weight : 2 * weight,
minlen = childTop !== childBottom ? 1 : height - depths[v] + 1;
g.setEdge(top, childTop, {
weight: thisWeight,
minlen: minlen,
nestingEdge: true
});
g.setEdge(childBottom, bottom, {
weight: thisWeight,
minlen: minlen,
nestingEdge: true
});
});
if (!g.parent(v)) {
g.setEdge(root, top, { weight: 0, minlen: height + depths[v] });
}
}
function treeDepths(g) {
var depths = {};
function dfs(v, depth) {
var children = g.children(v);
if (children && children.length) {
_.forEach(children, function(child) {
dfs(child, depth + 1);
});
}
depths[v] = depth;
}
_.forEach(g.children(), function(v) { dfs(v, 1); });