dagre.js 100 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252
  1. var dagre = dagre || {};
  2. // Dagre graph layout
  3. // https://github.com/dagrejs/dagre
  4. // https://github.com/dagrejs/graphlib
  5. dagre.layout = (graph, options) => {
  6. options = options || {};
  7. // options.time = true;
  8. const time = (name, callback) => {
  9. const start = Date.now();
  10. const result = callback();
  11. const duration = Date.now() - start;
  12. if (options.time) {
  13. /* eslint-disable */
  14. console.log(name + ': ' + duration + 'ms');
  15. /* eslint-enable */
  16. }
  17. return result;
  18. };
  19. // Constructs a new graph from the input graph, which can be used for layout.
  20. // This process copies only whitelisted attributes from the input graph to the
  21. // layout graph. Thus this function serves as a good place to determine what
  22. // attributes can influence layout.
  23. const buildLayoutGraph = (graph) => {
  24. const g = new dagre.Graph({ compound: true });
  25. g.options = Object.assign({}, { ranksep: 50, edgesep: 20, nodesep: 50, rankdir: 'tb' }, graph.options);
  26. for (const node of graph.nodes.values()) {
  27. const v = node.v;
  28. const label = node.label;
  29. g.setNode(v, {
  30. width: label.width || 0,
  31. height: label.height || 0
  32. });
  33. g.setParent(v, graph.parent(v));
  34. }
  35. for (const e of graph.edges.values()) {
  36. const edge = e.label;
  37. g.setEdge(e.v, e.w, {
  38. minlen: edge.minlen || 1,
  39. weight: edge.weight || 1,
  40. width: edge.width || 0,
  41. height: edge.height || 0,
  42. labeloffset: edge.labeloffset || 10,
  43. labelpos: edge.labelpos || 'r'
  44. });
  45. }
  46. return g;
  47. };
  48. const runLayout = (g, time) => {
  49. let uniqueIdCounter = 0;
  50. const uniqueId = (prefix) => {
  51. const id = ++uniqueIdCounter;
  52. return prefix + id;
  53. };
  54. const flat = (list) => {
  55. if (Array.isArray(list) && list.every((item) => !Array.isArray(item))) {
  56. return list;
  57. }
  58. const target = [];
  59. for (const item of list) {
  60. if (!Array.isArray(item)) {
  61. target.push(item);
  62. continue;
  63. }
  64. for (const entry of item) {
  65. target.push(entry);
  66. }
  67. }
  68. return target;
  69. };
  70. // Adds a dummy node to the graph and return v.
  71. const addDummyNode = (g, type, label, name) => {
  72. let v;
  73. do {
  74. v = uniqueId(name);
  75. } while (g.hasNode(v));
  76. label.dummy = type;
  77. g.setNode(v, label);
  78. return v;
  79. };
  80. const asNonCompoundGraph = (g) => {
  81. const graph = new dagre.Graph({});
  82. graph.options = g.options;
  83. for (const node of g.nodes.values()) {
  84. const v = node.v;
  85. if (g.children(v).length === 0) {
  86. graph.setNode(v, node.label);
  87. }
  88. }
  89. for (const e of g.edges.values()) {
  90. graph.setEdge(e.v, e.w, e.label);
  91. }
  92. return graph;
  93. };
  94. const maxRank = (g) => {
  95. let rank = Number.NEGATIVE_INFINITY;
  96. for (const node of g.nodes.values()) {
  97. const x = node.label.rank;
  98. if (x !== undefined && x > rank) {
  99. rank = x;
  100. }
  101. }
  102. return rank === Number.NEGATIVE_INFINITY ? undefined : rank;
  103. };
  104. // Given a DAG with each node assigned 'rank' and 'order' properties, this function will produce a matrix with the ids of each node.
  105. const buildLayerMatrix = (g) => {
  106. const rank = maxRank(g);
  107. const length = rank === undefined ? 0 : rank + 1;
  108. const layering = Array.from(new Array(length), () => []);
  109. for (const node of g.nodes.values()) {
  110. const label = node.label;
  111. const rank = label.rank;
  112. if (rank !== undefined) {
  113. layering[rank][label.order] = node.v;
  114. }
  115. }
  116. return layering;
  117. };
  118. // 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.
  119. // Then we can place labels at these mid-points between nodes.
  120. // We also add some minimal padding to the width to push the label for the edge away from the edge itself a bit.
  121. const makeSpaceForEdgeLabels = (g) => {
  122. const graph = g.options;
  123. graph.ranksep /= 2;
  124. for (const e of g.edges.values()) {
  125. const edge = e.label;
  126. edge.minlen *= 2;
  127. if (edge.labelpos.toLowerCase() !== 'c') {
  128. if (graph.rankdir === 'TB' || graph.rankdir === 'BT') {
  129. edge.width += edge.labeloffset;
  130. }
  131. else {
  132. edge.height += edge.labeloffset;
  133. }
  134. }
  135. }
  136. };
  137. const removeSelfEdges = (g) => {
  138. for (const e of g.edges.values()) {
  139. if (e.v === e.w) {
  140. const label = e.vNode.label;
  141. if (!label.selfEdges) {
  142. label.selfEdges = [];
  143. }
  144. label.selfEdges.push({ e: e, label: e.label });
  145. g.removeEdge(e);
  146. }
  147. }
  148. };
  149. const acyclic_run = (g) => {
  150. const edges = [];
  151. const visited = new Set();
  152. const path = new Set();
  153. const stack = Array.from(g.nodes.keys()).reverse();
  154. while (stack.length > 0) {
  155. const v = stack.pop();
  156. if (!Array.isArray(v)) {
  157. if (!visited.has(v)) {
  158. visited.add(v);
  159. path.add(v);
  160. stack.push([ v ]);
  161. const out = g.node(v).out;
  162. for (let i = out.length - 1; i >= 0; i--) {
  163. const e = out[i];
  164. if (path.has(e.w)) {
  165. edges.push(e);
  166. }
  167. stack.push(e.w);
  168. }
  169. }
  170. }
  171. else {
  172. path.delete(v[0]);
  173. }
  174. }
  175. for (const e of edges) {
  176. const label = e.label;
  177. g.removeEdge(e);
  178. label.forwardName = e.name;
  179. label.reversed = true;
  180. g.setEdge(e.w, e.v, label, uniqueId('rev'));
  181. }
  182. };
  183. const acyclic_undo = (g) => {
  184. for (const e of g.edges.values()) {
  185. const edge = e.label;
  186. if (edge.reversed) {
  187. edge.points.reverse();
  188. g.removeEdge(e);
  189. const forwardName = edge.forwardName;
  190. delete edge.reversed;
  191. delete edge.forwardName;
  192. g.setEdge(e.w, e.v, edge, forwardName);
  193. }
  194. }
  195. };
  196. // Returns the amount of slack for the given edge.
  197. // The slack is defined as the difference between the length of the edge and its minimum length.
  198. const slack = (g, e) => {
  199. return e.wNode.label.rank - e.vNode.label.rank - e.label.minlen;
  200. };
  201. // Assigns a rank to each node in the input graph that respects the 'minlen' constraint specified on edges between nodes.
  202. // This basic structure is derived from Gansner, et al., 'A Technique for Drawing Directed Graphs.'
  203. //
  204. // Pre-conditions:
  205. // 1. Graph must be a connected DAG
  206. // 2. Graph nodes must be objects
  207. // 3. Graph edges must have 'weight' and 'minlen' attributes
  208. //
  209. // Post-conditions:
  210. // 1. Graph nodes will have a 'rank' attribute based on the results of the
  211. // algorithm. Ranks can start at any index (including negative), we'll
  212. // fix them up later.
  213. const rank = (g) => {
  214. // Constructs a spanning tree with tight edges and adjusted the input node's ranks to achieve this.
  215. // A tight edge is one that is has a length that matches its 'minlen' attribute.
  216. // The basic structure for this function is derived from Gansner, et al., 'A Technique for Drawing Directed Graphs.'
  217. //
  218. // Pre-conditions:
  219. // 1. Graph must be a DAG.
  220. // 2. Graph must be connected.
  221. // 3. Graph must have at least one node.
  222. // 5. Graph nodes must have been previously assigned a 'rank' property that respects the 'minlen' property of incident edges.
  223. // 6. Graph edges must have a 'minlen' property.
  224. //
  225. // Post-conditions:
  226. // - Graph nodes will have their rank adjusted to ensure that all edges are tight.
  227. //
  228. // Returns a tree (undirected graph) that is constructed using only 'tight' edges.
  229. const feasibleTree = (g) => {
  230. const t = new dagre.Graph({ directed: false });
  231. // Choose arbitrary node from which to start our tree
  232. const start = g.nodes.keys().next().value;
  233. const size = g.nodes.size;
  234. t.setNode(start, {});
  235. // Finds a maximal tree of tight edges and returns the number of nodes in the tree.
  236. const tightTree = (t, g) => {
  237. const stack = Array.from(t.nodes.keys()).reverse();
  238. while (stack.length > 0) {
  239. const v = stack.pop();
  240. const node = g.node(v);
  241. for (const e of node.in.concat(node.out)) {
  242. const edgeV = e.v;
  243. const w = (v === edgeV) ? e.w : edgeV;
  244. if (!t.hasNode(w) && !slack(g, e)) {
  245. t.setNode(w, {});
  246. t.setEdge(v, w, {});
  247. stack.push(w);
  248. }
  249. }
  250. }
  251. return t.nodes.size;
  252. };
  253. while (tightTree(t, g) < size) {
  254. // Finds the edge with the smallest slack that is incident on tree and returns it.
  255. let minKey = Number.MAX_SAFE_INTEGER;
  256. let edge = undefined;
  257. for (const e of g.edges.values()) {
  258. if (t.hasNode(e.v) !== t.hasNode(e.w)) {
  259. const key = slack(g, e);
  260. if (key < minKey) {
  261. minKey = key;
  262. edge = e;
  263. }
  264. }
  265. }
  266. const delta = t.hasNode(edge.v) ? slack(g, edge) : -slack(g, edge);
  267. for (const v of t.nodes.keys()) {
  268. g.node(v).label.rank += delta;
  269. }
  270. }
  271. return t;
  272. };
  273. // Initializes ranks for the input graph using the longest path algorithm. This
  274. // algorithm scales well and is fast in practice, it yields rather poor
  275. // solutions. Nodes are pushed to the lowest layer possible, leaving the bottom
  276. // ranks wide and leaving edges longer than necessary. However, due to its
  277. // speed, this algorithm is good for getting an initial ranking that can be fed
  278. // into other algorithms.
  279. //
  280. // This algorithm does not normalize layers because it will be used by other
  281. // algorithms in most cases. If using this algorithm directly, be sure to
  282. // run normalize at the end.
  283. //
  284. // Pre-conditions:
  285. // 1. Input graph is a DAG.
  286. // 2. Input graph node labels can be assigned properties.
  287. //
  288. // Post-conditions:
  289. // 1. Each node will be assign an (unnormalized) 'rank' property.
  290. const longestPath = (g) => {
  291. const visited = new Set();
  292. const dfs = (v) => {
  293. const node = g.node(v);
  294. if (visited.has(v)) {
  295. return node.label.rank;
  296. }
  297. visited.add(v);
  298. let rank = Number.MAX_SAFE_INTEGER;
  299. for (const e of node.out) {
  300. rank = Math.min(rank, dfs(e.w) - e.label.minlen);
  301. }
  302. if (rank === Number.MAX_SAFE_INTEGER) {
  303. rank = 0;
  304. }
  305. node.label.rank = rank;
  306. return rank;
  307. };
  308. for (const node of g.nodes.values()) {
  309. if (node.in.length === 0) {
  310. dfs(node.v);
  311. }
  312. }
  313. };
  314. // The network simplex algorithm assigns ranks to each node in the input graph
  315. // and iteratively improves the ranking to reduce the length of edges.
  316. //
  317. // Preconditions:
  318. // 1. The input graph must be a DAG.
  319. // 2. All nodes in the graph must have an object value.
  320. // 3. All edges in the graph must have 'minlen' and 'weight' attributes.
  321. //
  322. // Postconditions:
  323. // 1. All nodes in the graph will have an assigned 'rank' attribute that has
  324. // been optimized by the network simplex algorithm. Ranks start at 0.
  325. //
  326. // A rough sketch of the algorithm is as follows:
  327. // 1. Assign initial ranks to each node. We use the longest path algorithm,
  328. // which assigns ranks to the lowest position possible. In general this
  329. // leads to very wide bottom ranks and unnecessarily long edges.
  330. // 2. Construct a feasible tight tree. A tight tree is one such that all
  331. // edges in the tree have no slack (difference between length of edge
  332. // and minlen for the edge). This by itself greatly improves the assigned
  333. // rankings by shorting edges.
  334. // 3. Iteratively find edges that have negative cut values. Generally a
  335. // negative cut value indicates that the edge could be removed and a new
  336. // tree edge could be added to produce a more compact graph.
  337. //
  338. // Much of the algorithms here are derived from Gansner, et al., 'A Technique
  339. // for Drawing Directed Graphs.' The structure of the file roughly follows the
  340. // structure of the overall algorithm.
  341. const networkSimplex = (g) => {
  342. // Returns a new graph with only simple edges. Handles aggregation of data associated with multi-edges.
  343. const simplify = (g) => {
  344. const graph = new dagre.Graph();
  345. graph.options = g.options;
  346. for (const node of g.nodes.values()) {
  347. graph.setNode(node.v, node.label);
  348. }
  349. for (const e of g.edges.values()) {
  350. const simpleEdge = graph.edge(e.v, e.w);
  351. const simpleLabel = simpleEdge ? simpleEdge.label : { weight: 0, minlen: 1 };
  352. const label = e.label;
  353. graph.setEdge(e.v, e.w, {
  354. weight: simpleLabel.weight + label.weight,
  355. minlen: Math.max(simpleLabel.minlen, label.minlen)
  356. });
  357. }
  358. return graph;
  359. };
  360. const initLowLimValues = (tree, root) => {
  361. const dfs = (tree, visited, nextLim, v, parent) => {
  362. const low = nextLim;
  363. const label = tree.node(v).label;
  364. visited.add(v);
  365. for (const w of tree.neighbors(v)) {
  366. if (!visited.has(w)) {
  367. nextLim = dfs(tree, visited, nextLim, w, v);
  368. }
  369. }
  370. label.low = low;
  371. label.lim = nextLim++;
  372. if (parent) {
  373. label.parent = parent;
  374. }
  375. else {
  376. // TODO should be able to remove this when we incrementally update low lim
  377. delete label.parent;
  378. }
  379. return nextLim;
  380. };
  381. root = tree.nodes.keys().next().value;
  382. const visited = new Set();
  383. dfs(tree, visited, 1, root);
  384. };
  385. // Initializes cut values for all edges in the tree.
  386. const initCutValues = (t, g) => {
  387. const vs = [];
  388. const visited = new Set();
  389. const stack = [ Array.from(t.nodes.keys()).reverse() ];
  390. while (stack.length > 0) {
  391. const current = stack[stack.length - 1];
  392. if (Array.isArray(current)) {
  393. const v = current.pop();
  394. if (current.length === 0) {
  395. stack.pop();
  396. }
  397. if (!visited.has(v)) {
  398. visited.add(v);
  399. const children = t.neighbors(v);
  400. if (children.length > 0) {
  401. stack.push(v);
  402. stack.push(children.reverse());
  403. }
  404. else {
  405. vs.push(v);
  406. }
  407. }
  408. }
  409. else {
  410. vs.push(stack.pop());
  411. }
  412. }
  413. for (const v of vs.slice(0, vs.length - 1)) {
  414. // Given the tight tree, its graph, and a child in the graph calculate and
  415. // return the cut value for the edge between the child and its parent.
  416. const childLabel = t.node(v).label;
  417. const parent = childLabel.parent;
  418. // The graph's view of the tree edge we're inspecting
  419. const edge = g.edge(v, parent);
  420. // True if the child is on the tail end of the edge in the directed graph
  421. const childIsTail = edge ? true : false;
  422. // The accumulated cut value for the edge between this node and its parent
  423. const graphEdge = edge ? edge.label : g.edge(parent, v).label;
  424. let cutValue = graphEdge.weight;
  425. const node = g.node(v);
  426. for (const e of node.in.concat(node.out)) {
  427. const isOutEdge = e.v === v;
  428. const other = isOutEdge ? e.w : e.v;
  429. if (other !== parent) {
  430. const pointsToHead = isOutEdge === childIsTail;
  431. cutValue += pointsToHead ? e.label.weight : -e.label.weight;
  432. const edge = t.edge(v, other);
  433. if (edge) {
  434. const otherCutValue = edge.label.cutvalue;
  435. cutValue += pointsToHead ? -otherCutValue : otherCutValue;
  436. }
  437. }
  438. }
  439. t.edge(v, parent).label.cutvalue = cutValue;
  440. }
  441. };
  442. const leaveEdge = (tree) => {
  443. return Array.from(tree.edges.values()).find((e) => e.label.cutvalue < 0);
  444. };
  445. const enterEdge = (t, g, edge) => {
  446. let v = edge.v;
  447. let w = edge.w;
  448. // For the rest of this function we assume that v is the tail and w is the
  449. // head, so if we don't have this edge in the graph we should flip it to
  450. // match the correct orientation.
  451. if (!g.edge(v, w)) {
  452. v = edge.w;
  453. w = edge.v;
  454. }
  455. const vLabel = t.node(v).label;
  456. const wLabel = t.node(w).label;
  457. let tailLabel = vLabel;
  458. let flip = false;
  459. // If the root is in the tail of the edge then we need to flip the logic that
  460. // checks for the head and tail nodes in the candidates function below.
  461. if (vLabel.lim > wLabel.lim) {
  462. tailLabel = wLabel;
  463. flip = true;
  464. }
  465. // Returns true if the specified node is descendant of the root node per the assigned low and lim attributes in the tree.
  466. const isDescendant = (vLabel, rootLabel) => {
  467. return rootLabel.low <= vLabel.lim && vLabel.lim <= rootLabel.lim;
  468. };
  469. let minKey = Number.POSITIVE_INFINITY;
  470. let minValue = undefined;
  471. for (const edge of g.edges.values()) {
  472. if (flip === isDescendant(t.node(edge.v).label, tailLabel) &&
  473. flip !== isDescendant(t.node(edge.w).label, tailLabel)) {
  474. const key = slack(g, edge);
  475. if (key < minKey) {
  476. minKey = key;
  477. minValue = edge;
  478. }
  479. }
  480. }
  481. return minValue;
  482. };
  483. const exchangeEdges = (t, g, e, f) => {
  484. t.removeEdge(e);
  485. t.setEdge(f.v, f.w, {});
  486. initLowLimValues(t);
  487. initCutValues(t, g);
  488. // update ranks
  489. const root = Array.from(t.nodes.keys()).find((v) => !g.node(v).label.parent);
  490. const stack = [ root ];
  491. const visited = new Set();
  492. while (stack.length > 0) {
  493. const v = stack.pop();
  494. if (!visited.has(v)) {
  495. visited.add(v);
  496. const neighbors = t.neighbors(v);
  497. for (let i = neighbors.length - 1; i >= 0; i--) {
  498. stack.push(neighbors[i]);
  499. }
  500. }
  501. }
  502. const vs = Array.from(visited);
  503. for (const v of vs.slice(1)) {
  504. const parent = t.node(v).label.parent;
  505. let edge = g.edge(v, parent);
  506. let flipped = false;
  507. if (!edge) {
  508. edge = g.edge(parent, v);
  509. flipped = true;
  510. }
  511. g.node(v).label.rank = g.node(parent).label.rank + (flipped ? edge.label.minlen : -edge.label.minlen);
  512. }
  513. };
  514. g = simplify(g);
  515. longestPath(g);
  516. const t = feasibleTree(g);
  517. initLowLimValues(t);
  518. initCutValues(t, g);
  519. let e;
  520. let f;
  521. while ((e = leaveEdge(t))) {
  522. f = enterEdge(t, g, e);
  523. exchangeEdges(t, g, e, f);
  524. }
  525. };
  526. switch(g.options.ranker) {
  527. case 'tight-tree':
  528. longestPath(g);
  529. feasibleTree(g);
  530. break;
  531. case 'longest-path':
  532. longestPath(g);
  533. break;
  534. default:
  535. networkSimplex(g);
  536. break;
  537. }
  538. };
  539. // 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.
  540. // We do this so that we can safely remove empty ranks while preserving balance for the label's position.
  541. const injectEdgeLabelProxies = (g) => {
  542. for (const e of g.edges.values()) {
  543. const edge = e.label;
  544. if (edge.width && edge.height) {
  545. const v = e.vNode.label;
  546. const w = e.wNode.label;
  547. addDummyNode(g, 'edge-proxy', { rank: (w.rank - v.rank) / 2 + v.rank, e: e }, '_ep');
  548. }
  549. }
  550. };
  551. const removeEmptyRanks = (g) => {
  552. // Ranks may not start at 0, so we need to offset them
  553. if (g.nodes.size > 0) {
  554. let minRank = Number.MAX_SAFE_INTEGER;
  555. let maxRank = Number.MIN_SAFE_INTEGER;
  556. const nodes = Array.from(g.nodes.values());
  557. for (const node of nodes) {
  558. const label = node.label;
  559. if (label.rank !== undefined) {
  560. minRank = Math.min(minRank, label.rank);
  561. maxRank = Math.max(maxRank, label.rank);
  562. }
  563. }
  564. const size = maxRank - minRank;
  565. if (size > 0) {
  566. const layers = new Array(size);
  567. for (const node of nodes) {
  568. const label = node.label;
  569. if (label.rank !== undefined) {
  570. const rank = label.rank - minRank;
  571. if (!layers[rank]) {
  572. layers[rank] = [];
  573. }
  574. layers[rank].push(node.v);
  575. }
  576. }
  577. let delta = 0;
  578. const nodeRankFactor = g.options.nodeRankFactor;
  579. for (let i = 0; i < layers.length; i++) {
  580. const vs = layers[i];
  581. if (vs === undefined && i % nodeRankFactor !== 0) {
  582. delta--;
  583. }
  584. else if (delta && vs) {
  585. for (const v of vs) {
  586. g.node(v).label.rank += delta;
  587. }
  588. }
  589. }
  590. }
  591. }
  592. };
  593. // A nesting graph creates dummy nodes for the tops and bottoms of subgraphs,
  594. // adds appropriate edges to ensure that all cluster nodes are placed between
  595. // these boundries, and ensures that the graph is connected.
  596. // In addition we ensure, through the use of the minlen property, that nodes
  597. // and subgraph border nodes do not end up on the same rank.
  598. //
  599. // Preconditions:
  600. // 1. Input graph is a DAG
  601. // 2. Nodes in the input graph has a minlen attribute
  602. //
  603. // Postconditions:
  604. // 1. Input graph is connected.
  605. // 2. Dummy nodes are added for the tops and bottoms of subgraphs.
  606. // 3. The minlen attribute for nodes is adjusted to ensure nodes do not
  607. // get placed on the same rank as subgraph border nodes.
  608. //
  609. // The nesting graph idea comes from Sander, 'Layout of Compound Directed Graphs.'
  610. const nestingGraph_run = (g) => {
  611. const root = addDummyNode(g, 'root', {}, '_root');
  612. const treeDepths = (g) => {
  613. const depths = {};
  614. const dfs = (v, depth) => {
  615. const children = g.children(v);
  616. if (children && children.length > 0) {
  617. for (const child of children) {
  618. dfs(child, depth + 1);
  619. }
  620. }
  621. depths[v] = depth;
  622. };
  623. for (const v of g.children()) {
  624. dfs(v, 1);
  625. }
  626. return depths;
  627. };
  628. const dfs = (g, root, nodeSep, weight, height, depths, v) => {
  629. const children = g.children(v);
  630. if (!children.length) {
  631. if (v !== root) {
  632. g.setEdge(root, v, { weight: 0, minlen: nodeSep });
  633. }
  634. return;
  635. }
  636. const top = addDummyNode(g, 'border', { width: 0, height: 0 }, '_bt');
  637. const bottom = addDummyNode(g, 'border', { width: 0, height: 0 }, '_bb');
  638. const label = g.node(v).label;
  639. g.setParent(top, v);
  640. label.borderTop = top;
  641. g.setParent(bottom, v);
  642. label.borderBottom = bottom;
  643. for (const child of children) {
  644. dfs(g, root, nodeSep, weight, height, depths, child);
  645. const childNode = g.node(child).label;
  646. const childTop = childNode.borderTop ? childNode.borderTop : child;
  647. const childBottom = childNode.borderBottom ? childNode.borderBottom : child;
  648. const thisWeight = childNode.borderTop ? weight : 2 * weight;
  649. const minlen = childTop !== childBottom ? 1 : height - depths[v] + 1;
  650. g.setEdge(top, childTop, { weight: thisWeight, minlen: minlen, nestingEdge: true });
  651. g.setEdge(childBottom, bottom, { weight: thisWeight, minlen: minlen, nestingEdge: true });
  652. }
  653. if (!g.parent(v)) {
  654. g.setEdge(root, top, { weight: 0, minlen: height + depths[v] });
  655. }
  656. };
  657. const depths = treeDepths(g);
  658. const height = Math.max(...Object.values(depths)) - 1; // Note: depths is an Object not an array
  659. const nodeSep = 2 * height + 1;
  660. g.options.nestingRoot = root;
  661. // Multiply minlen by nodeSep to align nodes on non-border ranks.
  662. for (const e of g.edges.values()) {
  663. e.label.minlen *= nodeSep;
  664. }
  665. // Calculate a weight that is sufficient to keep subgraphs vertically compact
  666. const weight = Array.from(g.edges.values()).reduce((acc, e) => acc + e.label.weight, 0) + 1;
  667. // Create border nodes and link them up
  668. for (const child of g.children()) {
  669. dfs(g, root, nodeSep, weight, height, depths, child);
  670. }
  671. // Save the multiplier for node layers for later removal of empty border layers.
  672. g.options.nodeRankFactor = nodeSep;
  673. };
  674. const nestingGraph_cleanup = (g) => {
  675. const graphLabel = g.options;
  676. g.removeNode(graphLabel.nestingRoot);
  677. delete graphLabel.nestingRoot;
  678. for (const e of g.edges.values()) {
  679. if (e.label.nestingEdge) {
  680. g.removeEdge(e);
  681. }
  682. }
  683. };
  684. const assignRankMinMax = (g) => {
  685. // Adjusts the ranks for all nodes in the graph such that all nodes v have rank(v) >= 0 and at least one node w has rank(w) = 0.
  686. let min = Number.POSITIVE_INFINITY;
  687. for (const node of g.nodes.values()) {
  688. const rank = node.label.rank;
  689. if (rank !== undefined && rank < min) {
  690. min = rank;
  691. }
  692. }
  693. for (const node of g.nodes.values()) {
  694. const label = node.label;
  695. if (label.rank !== undefined) {
  696. label.rank -= min;
  697. }
  698. }
  699. let maxRank = 0;
  700. for (const node of g.nodes.values()) {
  701. const label = node.label;
  702. if (label.borderTop) {
  703. label.minRank = g.node(label.borderTop).label.rank;
  704. label.maxRank = g.node(label.borderBottom).label.rank;
  705. maxRank = Math.max(maxRank, label.maxRank);
  706. }
  707. }
  708. g.options.maxRank = maxRank;
  709. };
  710. // Breaks any long edges in the graph into short segments that span 1 layer each.
  711. // This operation is undoable with the denormalize function.
  712. //
  713. // Pre-conditions:
  714. // 1. The input graph is a DAG.
  715. // 2. Each node in the graph has a 'rank' property.
  716. //
  717. // Post-condition:
  718. // 1. All edges in the graph have a length of 1.
  719. // 2. Dummy nodes are added where edges have been split into segments.
  720. // 3. The graph is augmented with a 'dummyChains' attribute which contains
  721. // the first dummy in each chain of dummy nodes produced.
  722. const normalize = (g) => {
  723. g.options.dummyChains = [];
  724. for (const e of g.edges.values()) {
  725. let v = e.v;
  726. const w = e.w;
  727. const name = e.name;
  728. const edgeLabel = e.label;
  729. const labelRank = edgeLabel.labelRank;
  730. let vRank = g.node(v).label.rank;
  731. const wRank = g.node(w).label.rank;
  732. if (wRank !== vRank + 1) {
  733. g.removeEdge(e);
  734. let first = true;
  735. vRank++;
  736. while (vRank < wRank) {
  737. edgeLabel.points = [];
  738. delete e.key;
  739. const attrs = {
  740. width: 0, height: 0,
  741. edgeLabel: edgeLabel,
  742. edgeObj: e,
  743. rank: vRank
  744. };
  745. const dummy = addDummyNode(g, 'edge', attrs, '_d');
  746. if (vRank === labelRank) {
  747. attrs.width = edgeLabel.width;
  748. attrs.height = edgeLabel.height;
  749. attrs.dummy = 'edge-label';
  750. attrs.labelpos = edgeLabel.labelpos;
  751. }
  752. g.setEdge(v, dummy, { weight: edgeLabel.weight }, name);
  753. if (first) {
  754. g.options.dummyChains.push(dummy);
  755. first = false;
  756. }
  757. v = dummy;
  758. vRank++;
  759. }
  760. g.setEdge(v, w, { weight: edgeLabel.weight }, name);
  761. }
  762. }
  763. };
  764. const denormalize = (g) => {
  765. for (let v of g.options.dummyChains) {
  766. let label = g.node(v).label;
  767. const edgeLabel = label.edgeLabel;
  768. const e = label.edgeObj;
  769. g.setEdge(e.v, e.w, edgeLabel, e.name);
  770. while (label.dummy) {
  771. const w = g.successors(v)[0];
  772. g.removeNode(v);
  773. edgeLabel.points.push({ x: label.x, y: label.y });
  774. if (label.dummy === 'edge-label') {
  775. edgeLabel.x = label.x;
  776. edgeLabel.y = label.y;
  777. edgeLabel.width = label.width;
  778. edgeLabel.height = label.height;
  779. }
  780. v = w;
  781. label = g.node(v).label;
  782. }
  783. }
  784. };
  785. const removeEdgeLabelProxies = (g) => {
  786. for (const node of g.nodes.values()) {
  787. const label = node.label;
  788. if (label.dummy === 'edge-proxy') {
  789. label.e.label.labelRank = label.rank;
  790. g.removeNode(node.v);
  791. }
  792. }
  793. };
  794. const parentDummyChains = (g) => {
  795. // Find a path from v to w through the lowest common ancestor (LCA). Return the full path and the LCA.
  796. const findPath = (g, postorderNums, v, w) => {
  797. const low = Math.min(postorderNums[v].low, postorderNums[w].low);
  798. const lim = Math.max(postorderNums[v].lim, postorderNums[w].lim);
  799. // Traverse up from v to find the LCA
  800. let parent = v;
  801. const vPath = [];
  802. do {
  803. parent = g.parent(parent);
  804. vPath.push(parent);
  805. }
  806. while (parent && (postorderNums[parent].low > low || lim > postorderNums[parent].lim));
  807. const lca = parent;
  808. // Traverse from w to LCA
  809. parent = w;
  810. const wPath = [];
  811. while ((parent = g.parent(parent)) !== lca) {
  812. wPath.push(parent);
  813. }
  814. return { path: vPath.concat(wPath.reverse()), lca: lca };
  815. };
  816. const postorder = (g) => {
  817. const result = {};
  818. let lim = 0;
  819. const dfs = (v) => {
  820. const low = lim;
  821. for (const u of g.children(v)) {
  822. dfs(u);
  823. }
  824. result[v] = { low: low, lim: lim++ };
  825. };
  826. for (const v of g.children()) {
  827. dfs(v);
  828. }
  829. return result;
  830. };
  831. const postorderNums = postorder(g);
  832. for (let v of g.options.dummyChains || []) {
  833. const node = g.node(v).label;
  834. const edgeObj = node.edgeObj;
  835. const pathData = findPath(g, postorderNums, edgeObj.v, edgeObj.w);
  836. const path = pathData.path;
  837. const lca = pathData.lca;
  838. let pathIdx = 0;
  839. let pathV = path[pathIdx];
  840. let ascending = true;
  841. while (v !== edgeObj.w) {
  842. const node = g.node(v).label;
  843. if (ascending) {
  844. while ((pathV = path[pathIdx]) !== lca && g.node(pathV).label.maxRank < node.rank) {
  845. pathIdx++;
  846. }
  847. if (pathV === lca) {
  848. ascending = false;
  849. }
  850. }
  851. if (!ascending) {
  852. while (pathIdx < path.length - 1 && g.node(pathV = path[pathIdx + 1]).label.minRank <= node.rank) {
  853. pathIdx++;
  854. }
  855. pathV = path[pathIdx];
  856. }
  857. g.setParent(v, pathV);
  858. v = g.successors(v)[0];
  859. }
  860. }
  861. };
  862. const addBorderSegments = (g) => {
  863. const addBorderNode = (g, prop, prefix, sg, sgNode, rank) => {
  864. const label = { width: 0, height: 0, rank: rank, borderType: prop };
  865. const prev = sgNode[prop][rank - 1];
  866. const curr = addDummyNode(g, 'border', label, prefix);
  867. sgNode[prop][rank] = curr;
  868. g.setParent(curr, sg);
  869. if (prev) {
  870. g.setEdge(prev, curr, { weight: 1 });
  871. }
  872. };
  873. const queue = g.children();
  874. while (queue.length > 0) {
  875. const v = queue.shift();
  876. const node = g.node(v).label;
  877. if ('minRank' in node) {
  878. node.borderLeft = [];
  879. node.borderRight = [];
  880. const maxRank = node.maxRank + 1;
  881. for (let rank = node.minRank; rank < maxRank; rank++) {
  882. addBorderNode(g, 'borderLeft', '_bl', v, node, rank);
  883. addBorderNode(g, 'borderRight', '_br', v, node, rank);
  884. }
  885. }
  886. const children = g.children(v);
  887. if (children.length) {
  888. for (const v of children) {
  889. queue.push(v);
  890. }
  891. }
  892. }
  893. };
  894. // Applies heuristics to minimize edge crossings in the graph and sets the best order solution as an order attribute on each node.
  895. //
  896. // Pre-conditions:
  897. // 1. Graph must be DAG
  898. // 2. Graph nodes must have the 'rank' attribute
  899. // 3. Graph edges must have the 'weight' attribute
  900. //
  901. // Post-conditions:
  902. // 1. Graph nodes will have an 'order' attribute based on the results of the algorithm.
  903. const order = (g) => {
  904. const sortSubgraph = (g, v, cg, biasRight) => {
  905. // Given a list of entries of the form {v, barycenter, weight} and a constraint graph this function will resolve any conflicts between the constraint graph and the barycenters for the entries.
  906. // If the barycenters for an entry would violate a constraint in the constraint graph then we coalesce the nodes in the conflict into a new node that respects the contraint and aggregates barycenter and weight information.
  907. // This implementation is based on the description in Forster, 'A Fast and Simple Hueristic for Constrained Two-Level Crossing Reduction,' thought it differs in some specific details.
  908. //
  909. // Pre-conditions:
  910. // 1. Each entry has the form {v, barycenter, weight}, or if the node has no barycenter, then {v}.
  911. //
  912. // Returns:
  913. // A new list of entries of the form {vs, i, barycenter, weight}.
  914. // The list `vs` may either be a singleton or it may be an aggregation of nodes ordered such that they do not violate constraints from the constraint graph.
  915. // The property `i` is the lowest original index of any of the elements in `vs`.
  916. const resolveConflicts = (entries, cg) => {
  917. const mappedEntries = new Map();
  918. for (let i = 0; i < entries.length; i++) {
  919. const entry = entries[i];
  920. const tmp = { indegree: 0, 'in': [], out: [], vs: [ entry.v ], i: i };
  921. if (entry.barycenter !== undefined) {
  922. tmp.barycenter = entry.barycenter;
  923. tmp.weight = entry.weight;
  924. }
  925. mappedEntries.set(entry.v, tmp);
  926. }
  927. for (const e of cg.edges.values()) {
  928. const entryV = mappedEntries.get(e.v);
  929. const entryW = mappedEntries.get(e.w);
  930. if (entryV && entryW) {
  931. entryW.indegree++;
  932. entryV.out.push(entryW);
  933. }
  934. }
  935. const sourceSet = Array.from(mappedEntries.values()).filter((entry) => !entry.indegree);
  936. const results = [];
  937. function handleIn(vEntry) {
  938. return function(uEntry) {
  939. if (uEntry.merged) {
  940. return;
  941. }
  942. if (uEntry.barycenter === undefined || vEntry.barycenter === undefined || uEntry.barycenter >= vEntry.barycenter) {
  943. let sum = 0;
  944. let weight = 0;
  945. if (vEntry.weight) {
  946. sum += vEntry.barycenter * vEntry.weight;
  947. weight += vEntry.weight;
  948. }
  949. if (uEntry.weight) {
  950. sum += uEntry.barycenter * uEntry.weight;
  951. weight += uEntry.weight;
  952. }
  953. vEntry.vs = uEntry.vs.concat(vEntry.vs);
  954. vEntry.barycenter = sum / weight;
  955. vEntry.weight = weight;
  956. vEntry.i = Math.min(uEntry.i, vEntry.i);
  957. uEntry.merged = true;
  958. }
  959. };
  960. }
  961. function handleOut(vEntry) {
  962. return function(wEntry) {
  963. wEntry.in.push(vEntry);
  964. if (--wEntry.indegree === 0) {
  965. sourceSet.push(wEntry);
  966. }
  967. };
  968. }
  969. while (sourceSet.length) {
  970. const entry = sourceSet.pop();
  971. results.push(entry);
  972. entry.in.reverse().forEach(handleIn(entry));
  973. entry.out.forEach(handleOut(entry));
  974. }
  975. return results.filter((entry) => !entry.merged).map((entry) => {
  976. const value = {
  977. vs: entry.vs,
  978. i: entry.i
  979. };
  980. if (entry.barycenter !== undefined) {
  981. value.barycenter = entry.barycenter;
  982. }
  983. if (entry.weight !== undefined) {
  984. value.weight = entry.weight;
  985. }
  986. return value;
  987. });
  988. };
  989. const barycenter = (g, movable) => {
  990. return (movable || []).map((v) => {
  991. const inV = g.node(v).in;
  992. if (!inV.length) {
  993. return { v: v };
  994. }
  995. const result = inV.reduce((acc, e) => {
  996. const edge = e.label;
  997. const nodeU = e.vNode.label;
  998. return {
  999. sum: acc.sum + (edge.weight * nodeU.order),
  1000. weight: acc.weight + edge.weight
  1001. };
  1002. }, { sum: 0, weight: 0 });
  1003. return {
  1004. v: v,
  1005. barycenter: result.sum / result.weight,
  1006. weight: result.weight
  1007. };
  1008. });
  1009. };
  1010. const sort = (entries, biasRight) => {
  1011. const consumeUnsortable = (vs, unsortable, index) => {
  1012. let last;
  1013. while (unsortable.length && (last = unsortable[unsortable.length - 1]).i <= index) {
  1014. unsortable.pop();
  1015. vs.push(last.vs);
  1016. index++;
  1017. }
  1018. return index;
  1019. };
  1020. const compareWithBias = (bias) => {
  1021. return function(entryV, entryW) {
  1022. if (entryV.barycenter < entryW.barycenter) {
  1023. return -1;
  1024. }
  1025. else if (entryV.barycenter > entryW.barycenter) {
  1026. return 1;
  1027. }
  1028. return !bias ? entryV.i - entryW.i : entryW.i - entryV.i;
  1029. };
  1030. };
  1031. // partition
  1032. const parts = { lhs: [], rhs: [] };
  1033. for (const value of entries) {
  1034. if ('barycenter' in value) {
  1035. parts.lhs.push(value);
  1036. }
  1037. else {
  1038. parts.rhs.push(value);
  1039. }
  1040. }
  1041. const sortable = parts.lhs;
  1042. const unsortable = parts.rhs.sort((a, b) => -a.i + b.i);
  1043. const vs = [];
  1044. let sum = 0;
  1045. let weight = 0;
  1046. let vsIndex = 0;
  1047. sortable.sort(compareWithBias(!!biasRight));
  1048. vsIndex = consumeUnsortable(vs, unsortable, vsIndex);
  1049. for (const entry of sortable) {
  1050. vsIndex += entry.vs.length;
  1051. vs.push(entry.vs);
  1052. sum += entry.barycenter * entry.weight;
  1053. weight += entry.weight;
  1054. vsIndex = consumeUnsortable(vs, unsortable, vsIndex);
  1055. }
  1056. const result = { vs: flat(vs) };
  1057. if (weight) {
  1058. result.barycenter = sum / weight;
  1059. result.weight = weight;
  1060. }
  1061. return result;
  1062. };
  1063. const node = g.node(v);
  1064. const bl = node && node.label ? node.label.borderLeft : undefined;
  1065. const br = node && node.label ? node.label.borderRight: undefined;
  1066. const subgraphs = {};
  1067. const movable = bl ? g.children(v).filter((w) => w !== bl && w !== br) : g.children(v);
  1068. const barycenters = barycenter(g, movable);
  1069. for (const entry of barycenters) {
  1070. if (g.children(entry.v).length) {
  1071. const result = sortSubgraph(g, entry.v, cg, biasRight);
  1072. subgraphs[entry.v] = result;
  1073. if ('barycenter' in result) {
  1074. if (entry.barycenter !== undefined) {
  1075. entry.barycenter = (entry.barycenter * entry.weight + result.barycenter * result.weight) / (entry.weight + result.weight);
  1076. entry.weight += result.weight;
  1077. }
  1078. else {
  1079. entry.barycenter = result.barycenter;
  1080. entry.weight = result.weight;
  1081. }
  1082. }
  1083. }
  1084. }
  1085. const entries = resolveConflicts(barycenters, cg);
  1086. // expand subgraphs
  1087. for (const entry of entries) {
  1088. entry.vs = flat(entry.vs.map((v) => subgraphs[v] ? subgraphs[v].vs : v));
  1089. }
  1090. const result = sort(entries, biasRight);
  1091. if (bl) {
  1092. result.vs = flat([bl, result.vs, br]);
  1093. if (g.predecessors(bl).length) {
  1094. const blPred = g.node(g.predecessors(bl)[0]).label;
  1095. const brPred = g.node(g.predecessors(br)[0]).label;
  1096. if (!('barycenter' in result)) {
  1097. result.barycenter = 0;
  1098. result.weight = 0;
  1099. }
  1100. result.barycenter = (result.barycenter * result.weight + blPred.order + brPred.order) / (result.weight + 2);
  1101. result.weight += 2;
  1102. }
  1103. }
  1104. return result;
  1105. };
  1106. const sweepLayerGraphs = (layerGraphs, biasRight) => {
  1107. const cg = new dagre.Graph();
  1108. for (const lg of layerGraphs) {
  1109. const root = lg.options.root;
  1110. const sorted = sortSubgraph(lg, root, cg, biasRight);
  1111. const vs = sorted.vs;
  1112. const length = vs.length;
  1113. for (let i = 0; i < length; i++) {
  1114. lg.node(vs[i]).label.order = i;
  1115. }
  1116. // add subgraph constraints
  1117. const prev = {};
  1118. let rootPrev;
  1119. let exit = false;
  1120. for (const v of vs) {
  1121. let child = lg.parent(v);
  1122. let prevChild;
  1123. while (child) {
  1124. const parent = lg.parent(child);
  1125. if (parent) {
  1126. prevChild = prev[parent];
  1127. prev[parent] = child;
  1128. }
  1129. else {
  1130. prevChild = rootPrev;
  1131. rootPrev = child;
  1132. }
  1133. if (prevChild && prevChild !== child) {
  1134. cg.setEdge(prevChild, child, null);
  1135. exit = true;
  1136. break;
  1137. }
  1138. child = parent;
  1139. }
  1140. if (exit) {
  1141. break;
  1142. }
  1143. }
  1144. }
  1145. };
  1146. // A function that takes a layering (an array of layers, each with an array of
  1147. // ordererd nodes) and a graph and returns a weighted crossing count.
  1148. //
  1149. // Pre-conditions:
  1150. // 1. Input graph must be simple (not a multigraph), directed, and include
  1151. // only simple edges.
  1152. // 2. Edges in the input graph must have assigned weights.
  1153. //
  1154. // Post-conditions:
  1155. // 1. The graph and layering matrix are left unchanged.
  1156. //
  1157. // This algorithm is derived from Barth, et al., 'Bilayer Cross Counting.'
  1158. const crossCount = (g, layering) => {
  1159. let count = 0;
  1160. for (let i = 1; i < layering.length; i++) {
  1161. const northLayer = layering[i - 1];
  1162. const southLayer = layering[i];
  1163. // Sort all of the edges between the north and south layers by their position in the north layer and then the south.
  1164. // Map these edges to the position of their head in the south layer.
  1165. const southPos = {};
  1166. for (let i = 0; i < southLayer.length; i++) {
  1167. southPos[southLayer[i]] = i;
  1168. }
  1169. const southEntries = [];
  1170. for (const v of northLayer) {
  1171. const entries = [];
  1172. for (const e of g.node(v).out) {
  1173. entries.push({
  1174. pos: southPos[e.w],
  1175. weight: e.label.weight
  1176. });
  1177. }
  1178. entries.sort((a, b) => a.pos - b.pos);
  1179. for (const entry of entries) {
  1180. southEntries.push(entry);
  1181. }
  1182. }
  1183. // Build the accumulator tree
  1184. let firstIndex = 1;
  1185. while (firstIndex < southLayer.length) {
  1186. firstIndex <<= 1;
  1187. }
  1188. const treeSize = 2 * firstIndex - 1;
  1189. firstIndex -= 1;
  1190. const tree = Array.from(new Array(treeSize), () => 0);
  1191. // Calculate the weighted crossings
  1192. for (const entry of southEntries) {
  1193. let index = entry.pos + firstIndex;
  1194. tree[index] += entry.weight;
  1195. let weightSum = 0;
  1196. while (index > 0) {
  1197. if (index % 2) {
  1198. weightSum += tree[index + 1];
  1199. }
  1200. index = (index - 1) >> 1;
  1201. tree[index] += entry.weight;
  1202. }
  1203. count += entry.weight * weightSum;
  1204. }
  1205. }
  1206. return count;
  1207. };
  1208. // Assigns an initial order value for each node by performing a DFS search
  1209. // starting from nodes in the first rank. Nodes are assigned an order in their
  1210. // rank as they are first visited.
  1211. //
  1212. // This approach comes from Gansner, et al., 'A Technique for Drawing Directed
  1213. // Graphs.'
  1214. //
  1215. // Returns a layering matrix with an array per layer and each layer sorted by
  1216. // the order of its nodes.
  1217. const initOrder = (g) => {
  1218. const visited = new Set();
  1219. const nodes = Array.from(g.nodes.values()).filter((node) => g.children(node.v).length === 0);
  1220. let maxRank = undefined;
  1221. for (const node of nodes) {
  1222. const rank = node.label.rank;
  1223. if (maxRank === undefined || (rank !== undefined && rank > maxRank)) {
  1224. maxRank = rank;
  1225. }
  1226. }
  1227. if (maxRank !== undefined) {
  1228. const layers = Array.from(new Array(maxRank + 1), () => []);
  1229. const queue = nodes.sort((a, b) => a.label.rank - b.label.rank).map((node) => node.v).reverse();
  1230. while (queue.length > 0) {
  1231. const v = queue.shift();
  1232. if (!visited.has(v)) {
  1233. visited.add(v);
  1234. const rank = g.node(v).label.rank;
  1235. layers[rank].push(v);
  1236. for (const w of g.successors(v)) {
  1237. queue.push(w);
  1238. }
  1239. }
  1240. }
  1241. return layers;
  1242. }
  1243. return [];
  1244. };
  1245. // Constructs a graph that can be used to sort a layer of nodes.
  1246. // The graph will contain all base and subgraph nodes from the request layer in their original
  1247. // hierarchy and any edges that are incident on these nodes and are of the type requested by the 'relationship' parameter.
  1248. //
  1249. // Nodes from the requested rank that do not have parents are assigned a root node in the output graph,
  1250. // which is set in the root graph attribute.
  1251. // This makes it easy to walk the hierarchy of movable nodes during ordering.
  1252. //
  1253. // Pre-conditions:
  1254. // 1. Input graph is a DAG
  1255. // 2. Base nodes in the input graph have a rank attribute
  1256. // 3. Subgraph nodes in the input graph has minRank and maxRank attributes
  1257. // 4. Edges have an assigned weight
  1258. //
  1259. // Post-conditions:
  1260. // 1. Output graph has all nodes in the movable rank with preserved hierarchy.
  1261. // 2. Root nodes in the movable layer are made children of the node
  1262. // indicated by the root attribute of the graph.
  1263. // 3. Non-movable nodes incident on movable nodes, selected by the
  1264. // relationship parameter, are included in the graph (without hierarchy).
  1265. // 4. Edges incident on movable nodes, selected by the relationship parameter, are added to the output graph.
  1266. // 5. The weights for copied edges are aggregated as need, since the output graph is not a multi-graph.
  1267. const buildLayerGraph = (g, nodes, rank, relationship) => {
  1268. let root;
  1269. while (g.hasNode((root = uniqueId('_root')))) {
  1270. // continue
  1271. }
  1272. const graph = new dagre.Graph({ compound: true });
  1273. graph.options = { root: root };
  1274. graph.setDefaultNodeLabel((v) => { const node = g.node(v); return node ? node.label : undefined; });
  1275. const length = nodes.length;
  1276. let i = 0;
  1277. while (i < length) {
  1278. const node = nodes[i++];
  1279. const label = node.label;
  1280. if (label.rank === rank || 'minRank' in label && 'maxRank' in label && label.minRank <= rank && rank <= label.maxRank) {
  1281. const v = node.v;
  1282. graph.setNode(v);
  1283. const parent = g.parent(v);
  1284. graph.setParent(v, parent || root);
  1285. // This assumes we have only short edges!
  1286. if (relationship) {
  1287. for (const e of node.in) {
  1288. graph.setEdge(e.v, v, { weight: e.label.weight });
  1289. }
  1290. }
  1291. else {
  1292. for (const e of node.out) {
  1293. graph.setEdge(e.w, v, { weight: e.label.weight });
  1294. }
  1295. }
  1296. if ('minRank' in label) {
  1297. graph.setNode(v, {
  1298. borderLeft: label.borderLeft[rank],
  1299. borderRight: label.borderRight[rank]
  1300. });
  1301. }
  1302. }
  1303. }
  1304. return graph;
  1305. };
  1306. let layering = initOrder(g);
  1307. const assignOrder = (g, layering) => {
  1308. for (const layer of layering) {
  1309. for (let i = 0; i < layer.length; i++) {
  1310. g.node(layer[i]).label.order = i;
  1311. }
  1312. }
  1313. };
  1314. assignOrder(g, layering);
  1315. const rank = maxRank(g) || 0;
  1316. const downLayerGraphs = new Array(rank);
  1317. const upLayerGraphs = new Array(rank);
  1318. const nodes = Array.from(g.nodes.values());
  1319. for (let i = 0; i < rank; i++) {
  1320. downLayerGraphs[i] = buildLayerGraph(g, nodes, i + 1, true);
  1321. upLayerGraphs[i] = buildLayerGraph(g, nodes, rank - i - 1, false);
  1322. }
  1323. let bestCC = Number.POSITIVE_INFINITY;
  1324. let best;
  1325. for (let i = 0, lastBest = 0; lastBest < 4; ++i, ++lastBest) {
  1326. sweepLayerGraphs(i % 2 ? downLayerGraphs : upLayerGraphs, i % 4 >= 2);
  1327. layering = buildLayerMatrix(g);
  1328. const cc = crossCount(g, layering);
  1329. if (cc < bestCC) {
  1330. lastBest = 0;
  1331. const length = layering.length;
  1332. best = new Array(length);
  1333. for (let j = 0; j < length; j++) {
  1334. best[j] = layering[j].slice();
  1335. }
  1336. bestCC = cc;
  1337. }
  1338. }
  1339. assignOrder(g, best);
  1340. };
  1341. const insertSelfEdges = (g) => {
  1342. const layers = buildLayerMatrix(g);
  1343. for (const layer of layers) {
  1344. let orderShift = 0;
  1345. layer.forEach(function(v, i) {
  1346. const label = g.node(v).label;
  1347. label.order = i + orderShift;
  1348. if (label.selfEdges) {
  1349. for (const selfEdge of label.selfEdges) {
  1350. addDummyNode(g, 'selfedge', {
  1351. width: selfEdge.label.width,
  1352. height: selfEdge.label.height,
  1353. rank: label.rank,
  1354. order: i + (++orderShift),
  1355. e: selfEdge.e,
  1356. label: selfEdge.label
  1357. }, '_se');
  1358. }
  1359. delete label.selfEdges;
  1360. }
  1361. });
  1362. }
  1363. };
  1364. const coordinateSystem_swapWidthHeight = (g) => {
  1365. for (const node of g.nodes.values()) {
  1366. const label = node.label;
  1367. const w = label.width;
  1368. label.width = label.height;
  1369. label.height = w;
  1370. }
  1371. for (const e of g.edges.values()) {
  1372. const label = e.label;
  1373. const w = label.width;
  1374. label.width = label.height;
  1375. label.height = w;
  1376. }
  1377. };
  1378. const coordinateSystem_adjust = (g) => {
  1379. const rankDir = g.options.rankdir.toLowerCase();
  1380. if (rankDir === 'lr' || rankDir === 'rl') {
  1381. coordinateSystem_swapWidthHeight(g);
  1382. }
  1383. };
  1384. const coordinateSystem_undo = (g) => {
  1385. const rankDir = g.options.rankdir.toLowerCase();
  1386. if (rankDir === 'bt' || rankDir === 'rl') {
  1387. for (const node of g.nodes.values()) {
  1388. node.label.y = -node.label.y;
  1389. }
  1390. for (const e of g.edges.values()) {
  1391. const edge = e.label;
  1392. for (const attr of edge.points) {
  1393. attr.y = -attr.y;
  1394. }
  1395. if ('y' in edge) {
  1396. edge.y = -edge.y;
  1397. }
  1398. }
  1399. }
  1400. if (rankDir === 'lr' || rankDir === 'rl') {
  1401. const swapXYOne = (attrs) => {
  1402. const x = attrs.x;
  1403. attrs.x = attrs.y;
  1404. attrs.y = x;
  1405. };
  1406. for (const node of g.nodes.values()) {
  1407. swapXYOne(node.label);
  1408. }
  1409. for (const e of g.edges.values()) {
  1410. const edge = e.label;
  1411. for (const e of edge.points) {
  1412. swapXYOne(e);
  1413. }
  1414. if (edge.x !== undefined) {
  1415. swapXYOne(edge);
  1416. }
  1417. }
  1418. coordinateSystem_swapWidthHeight(g);
  1419. }
  1420. };
  1421. const position = (g) => {
  1422. const addConflict = (conflicts, v, w) => {
  1423. if (v > w) {
  1424. const tmp = v;
  1425. v = w;
  1426. w = tmp;
  1427. }
  1428. let conflictsV = conflicts[v];
  1429. if (!conflictsV) {
  1430. conflicts[v] = conflictsV = {};
  1431. }
  1432. conflictsV[w] = true;
  1433. };
  1434. const hasConflict = (conflicts, v, w) => {
  1435. if (v > w) {
  1436. const tmp = v;
  1437. v = w;
  1438. w = tmp;
  1439. }
  1440. return conflicts[v] && w in conflicts[v];
  1441. };
  1442. const buildBlockGraph = (g, layering, root, reverseSep) => {
  1443. const nodeSep = g.options.nodesep;
  1444. const edgeSep = g.options.edgesep;
  1445. const blockGraph = new dagre.Graph();
  1446. for (const layer of layering) {
  1447. let u;
  1448. for (const v of layer) {
  1449. const vRoot = root[v];
  1450. blockGraph.setNode(vRoot, {});
  1451. if (u) {
  1452. const uRoot = root[u];
  1453. const vLabel = g.node(v).label;
  1454. const wLabel = g.node(u).label;
  1455. let sum = 0;
  1456. let delta;
  1457. sum += vLabel.width / 2;
  1458. if ('labelpos' in vLabel) {
  1459. switch (vLabel.labelpos) {
  1460. case 'l': delta = -vLabel.width / 2; break;
  1461. case 'r': delta = vLabel.width / 2; break;
  1462. default: throw new dagre.Error("Unsupported label position '" + vLabel.labelpos + "'.");
  1463. }
  1464. }
  1465. if (delta) {
  1466. sum += reverseSep ? delta : -delta;
  1467. }
  1468. delta = 0;
  1469. sum += (vLabel.dummy ? edgeSep : nodeSep) / 2;
  1470. sum += (wLabel.dummy ? edgeSep : nodeSep) / 2;
  1471. sum += wLabel.width / 2;
  1472. if ('labelpos' in wLabel) {
  1473. switch (wLabel.labelpos) {
  1474. case 'l': delta = wLabel.width / 2; break;
  1475. case 'r': delta = -wLabel.width / 2; break;
  1476. default: throw new dagre.Error("Unsupported label position '" + wLabel.labelpos + "'.");
  1477. }
  1478. }
  1479. if (delta) {
  1480. sum += reverseSep ? delta : -delta;
  1481. }
  1482. const edge = blockGraph.edge(uRoot, vRoot);
  1483. const max = Math.max(sum, edge ? edge.label : 0);
  1484. if (edge) {
  1485. edge.label = max;
  1486. }
  1487. else {
  1488. blockGraph.setEdge(uRoot, vRoot, max);
  1489. }
  1490. }
  1491. u = v;
  1492. }
  1493. }
  1494. return blockGraph;
  1495. };
  1496. // Try to align nodes into vertical 'blocks' where possible.
  1497. // This algorithm attempts to align a node with one of its median neighbors.
  1498. // If the edge connecting a neighbor is a type-1 conflict then we ignore that possibility.
  1499. // If a previous node has already formed a block with a node after the node we're trying to form a block with,
  1500. // we also ignore that possibility - our blocks would be split in that scenario.
  1501. const verticalAlignment = (layering, conflicts, neighborFn) => {
  1502. const root = {};
  1503. const align = {};
  1504. const pos = {};
  1505. // We cache the position here based on the layering because the graph and layering may be out of sync.
  1506. // The layering matrix is manipulated to generate different extreme alignments.
  1507. for (const layer of layering) {
  1508. let order = 0;
  1509. for (const v of layer) {
  1510. root[v] = v;
  1511. align[v] = v;
  1512. pos[v] = order;
  1513. order++;
  1514. }
  1515. }
  1516. for (const layer of layering) {
  1517. let prevIdx = -1;
  1518. for (const v of layer) {
  1519. let ws = neighborFn(v);
  1520. if (ws.length > 0) {
  1521. ws = ws.sort((a, b) => pos[a] - pos[b]);
  1522. const mp = (ws.length - 1) / 2.0;
  1523. const il = Math.ceil(mp);
  1524. for (let i = Math.floor(mp); i <= il; i++) {
  1525. const w = ws[i];
  1526. if (align[v] === v && prevIdx < pos[w] && !hasConflict(conflicts, v, w)) {
  1527. align[w] = v;
  1528. align[v] = root[v] = root[w];
  1529. prevIdx = pos[w];
  1530. }
  1531. }
  1532. }
  1533. }
  1534. }
  1535. return { root: root, align: align };
  1536. };
  1537. const horizontalCompaction = (g, layering, root, align, reverseSep) => {
  1538. // This portion of the algorithm differs from BK due to a number of problems.
  1539. // Instead of their algorithm we construct a new block graph and do two sweeps.
  1540. const blockG = buildBlockGraph(g, layering, root, reverseSep);
  1541. const borderType = reverseSep ? 'borderLeft' : 'borderRight';
  1542. const xs = {};
  1543. // First pass, places blocks with the smallest possible coordinates.
  1544. if (blockG.nodes.size > 0) {
  1545. const stack = Array.from(blockG.nodes.keys());
  1546. const visited = new Set();
  1547. while (stack.length > 0) {
  1548. const v = stack.pop();
  1549. if (visited.has(v)) {
  1550. let max = 0;
  1551. for (const e of blockG.node(v).in) {
  1552. max = Math.max(max, xs[e.v] + e.label);
  1553. }
  1554. xs[v] = max;
  1555. }
  1556. else {
  1557. visited.add(v);
  1558. stack.push(v);
  1559. for (const w of blockG.predecessors(v)) {
  1560. stack.push(w);
  1561. }
  1562. }
  1563. }
  1564. }
  1565. // Second pass, removes unused space by moving blocks to the greatest coordinates without violating separation.
  1566. if (blockG.nodes.size > 0) {
  1567. const stack = Array.from(blockG.nodes.keys());
  1568. const visited = new Set();
  1569. while (stack.length > 0) {
  1570. const v = stack.pop();
  1571. if (visited.has(v)) {
  1572. let min = Number.POSITIVE_INFINITY;
  1573. for (const e of blockG.node(v).out) {
  1574. min = Math.min(min, xs[e.w] - e.label);
  1575. }
  1576. const label = g.node(v).label;
  1577. if (min !== Number.POSITIVE_INFINITY && label.borderType !== borderType) {
  1578. xs[v] = Math.max(xs[v], min);
  1579. }
  1580. }
  1581. else {
  1582. visited.add(v);
  1583. stack.push(v);
  1584. for (const w of blockG.successors(v)) {
  1585. stack.push(w);
  1586. }
  1587. }
  1588. }
  1589. }
  1590. // Assign x coordinates to all nodes
  1591. for (const v of Object.values(align)) {
  1592. xs[v] = xs[root[v]];
  1593. }
  1594. return xs;
  1595. };
  1596. // Marks all edges in the graph with a type-1 conflict with the 'type1Conflict' property.
  1597. // A type-1 conflict is one where a non-inner segment crosses an inner segment.
  1598. // An inner segment is an edge with both incident nodes marked with the 'dummy' property.
  1599. //
  1600. // This algorithm scans layer by layer, starting with the second, for type-1
  1601. // conflicts between the current layer and the previous layer. For each layer
  1602. // it scans the nodes from left to right until it reaches one that is incident
  1603. // on an inner segment. It then scans predecessors to determine if they have
  1604. // edges that cross that inner segment. At the end a final scan is done for all
  1605. // nodes on the current rank to see if they cross the last visited inner segment.
  1606. //
  1607. // This algorithm (safely) assumes that a dummy node will only be incident on a
  1608. // single node in the layers being scanned.
  1609. const findType1Conflicts = (g, layering) => {
  1610. const conflicts = {};
  1611. if (layering.length > 0) {
  1612. let prev = layering[0];
  1613. for (let k = 1; k < layering.length; k++) {
  1614. const layer = layering[k];
  1615. // last visited node in the previous layer that is incident on an inner segment.
  1616. let k0 = 0;
  1617. // Tracks the last node in this layer scanned for crossings with a type-1 segment.
  1618. let scanPos = 0;
  1619. const prevLayerLength = prev.length;
  1620. const lastNode = layer[layer.length - 1];
  1621. for (let i = 0; i < layer.length; i++) {
  1622. const v = layer[i];
  1623. const w = g.node(v).label.dummy ? g.predecessors(v).find((u) => g.node(u).label.dummy) : null;
  1624. if (w || v === lastNode) {
  1625. const k1 = w ? g.node(w).label.order : prevLayerLength;
  1626. for (const scanNode of layer.slice(scanPos, i + 1)) {
  1627. // for (const scanNode of layer.slice(scanPos, scanPos + 1)) {
  1628. for (const u of g.predecessors(scanNode)) {
  1629. const uLabel = g.node(u).label;
  1630. const uPos = uLabel.order;
  1631. if ((uPos < k0 || k1 < uPos) && !(uLabel.dummy && g.node(scanNode).label.dummy)) {
  1632. addConflict(conflicts, u, scanNode);
  1633. }
  1634. }
  1635. }
  1636. // scanPos += 1;
  1637. scanPos = i + 1;
  1638. k0 = k1;
  1639. }
  1640. }
  1641. prev = layer;
  1642. }
  1643. }
  1644. return conflicts;
  1645. };
  1646. const findType2Conflicts = (g, layering) => {
  1647. const conflicts = {};
  1648. const scan = (south, southPos, southEnd, prevNorthBorder, nextNorthBorder) => {
  1649. let v;
  1650. for (let i = southPos; i < southEnd; i++) {
  1651. v = south[i];
  1652. if (g.node(v).labeldummy) {
  1653. for (const u of g.predecessors(v)) {
  1654. const uNode = g.node(u).label;
  1655. if (uNode.dummy && (uNode.order < prevNorthBorder || uNode.order > nextNorthBorder)) {
  1656. addConflict(conflicts, u, v);
  1657. }
  1658. }
  1659. }
  1660. }
  1661. };
  1662. if (layering.length > 0) {
  1663. let north = layering[0];
  1664. for (let i = 1; i < layering.length; i++) {
  1665. const south = layering[i];
  1666. let prevNorthPos = -1;
  1667. let nextNorthPos;
  1668. let southPos = 0;
  1669. south.forEach(function(v, southLookahead) {
  1670. if (g.node(v).label.dummy === 'border') {
  1671. const predecessors = g.predecessors(v);
  1672. if (predecessors.length) {
  1673. nextNorthPos = g.node(predecessors[0]).label.order;
  1674. scan(south, southPos, southLookahead, prevNorthPos, nextNorthPos);
  1675. southPos = southLookahead;
  1676. prevNorthPos = nextNorthPos;
  1677. }
  1678. }
  1679. scan(south, southPos, south.length, nextNorthPos, north.length);
  1680. });
  1681. north = south;
  1682. }
  1683. }
  1684. return conflicts;
  1685. };
  1686. g = asNonCompoundGraph(g);
  1687. const layering = buildLayerMatrix(g);
  1688. const ranksep = g.options.ranksep;
  1689. // Assign y-coordinate based on rank
  1690. let y = 0;
  1691. for (const layer of layering) {
  1692. const maxHeight = layer.reduce((a, v) => Math.max(a, g.node(v).label.height), 0);
  1693. for (const v of layer) {
  1694. g.node(v).label.y = y + maxHeight / 2;
  1695. }
  1696. y += maxHeight + ranksep;
  1697. }
  1698. // Coordinate assignment based on Brandes and Köpf, 'Fast and Simple Horizontal Coordinate Assignment.'
  1699. const conflicts = Object.assign(findType1Conflicts(g, layering), findType2Conflicts(g, layering));
  1700. const xss = {};
  1701. for (const vertical of ['u', 'd']) {
  1702. let adjustedLayering = vertical === 'u' ? layering : Object.values(layering).reverse();
  1703. for (const horizontal of ['l', 'r']) {
  1704. if (horizontal === 'r') {
  1705. adjustedLayering = adjustedLayering.map((layer) => Object.values(layer).reverse());
  1706. }
  1707. const neighborFn = (vertical === 'u' ? g.predecessors : g.successors).bind(g);
  1708. const align = verticalAlignment(adjustedLayering, conflicts, neighborFn);
  1709. const xs = horizontalCompaction(g, adjustedLayering, align.root, align.align, horizontal === 'r');
  1710. if (horizontal === 'r') {
  1711. for (const entry of Object.entries(xs)) {
  1712. xs[entry[0]] = -entry[1];
  1713. }
  1714. }
  1715. xss[vertical + horizontal] = xs;
  1716. }
  1717. }
  1718. // Find smallest width alignment: Returns the alignment that has the smallest width of the given alignments.
  1719. let minWidth = Number.POSITIVE_INFINITY;
  1720. let minValue = undefined;
  1721. for (const xs of Object.values(xss)) {
  1722. let max = Number.NEGATIVE_INFINITY;
  1723. let min = Number.POSITIVE_INFINITY;
  1724. for (const entry of Object.entries(xs)) {
  1725. const v = entry[0];
  1726. const x = entry[1];
  1727. const halfWidth = g.node(v).label.width / 2;
  1728. max = Math.max(x + halfWidth, max);
  1729. min = Math.min(x - halfWidth, min);
  1730. }
  1731. const width = max - min;
  1732. if (width < minWidth) {
  1733. minWidth = width;
  1734. minValue = xs;
  1735. }
  1736. }
  1737. // Align the coordinates of each of the layout alignments such that
  1738. // left-biased alignments have their minimum coordinate at the same point as
  1739. // the minimum coordinate of the smallest width alignment and right-biased
  1740. // alignments have their maximum coordinate at the same point as the maximum
  1741. // coordinate of the smallest width alignment.
  1742. const alignTo = minValue;
  1743. const range = (values) => {
  1744. let min = Number.POSITIVE_INFINITY;
  1745. let max = Number.NEGATIVE_INFINITY;
  1746. for (const value of values) {
  1747. if (value < min) {
  1748. min = value;
  1749. }
  1750. if (value > max) {
  1751. max = value;
  1752. }
  1753. }
  1754. return [ min, max ];
  1755. };
  1756. const alignToRange = range(Object.values(alignTo));
  1757. for (const vertical of ['u', 'd']) {
  1758. for (const horizontal of ['l', 'r']) {
  1759. const alignment = vertical + horizontal;
  1760. const xs = xss[alignment];
  1761. let delta;
  1762. if (xs !== alignTo) {
  1763. const vsValsRange = range(Object.values(xs));
  1764. delta = horizontal === 'l' ? alignToRange[0] - vsValsRange[0] : alignToRange[1] - vsValsRange[1];
  1765. if (delta) {
  1766. const list = {};
  1767. for (const key of Object.keys(xs)) {
  1768. list[key] = xs[key] + delta;
  1769. }
  1770. xss[alignment] = list;
  1771. }
  1772. }
  1773. }
  1774. }
  1775. // balance
  1776. const align = g.options.align;
  1777. if (align) {
  1778. const xs = xss[align.toLowerCase()];
  1779. for (const v of Object.keys(xss.ul)) {
  1780. g.node(v).label.x = xs[v];
  1781. }
  1782. }
  1783. else {
  1784. for (const v of Object.keys(xss.ul)) {
  1785. const xs = [ xss.ul[v], xss.ur[v], xss.dl[v], xss.dr[v] ].sort((a, b) => a - b);
  1786. g.node(v).label.x = (xs[1] + xs[2]) / 2;
  1787. }
  1788. }
  1789. };
  1790. const positionSelfEdges = (g) => {
  1791. for (const node of g.nodes.values()) {
  1792. const label = node.label;
  1793. if (label.dummy === 'selfedge') {
  1794. const v = node.v;
  1795. const selfNode = g.node(label.e.v).label;
  1796. const x = selfNode.x + selfNode.width / 2;
  1797. const y = selfNode.y;
  1798. const dx = label.x - x;
  1799. const dy = selfNode.height / 2;
  1800. g.setEdge(label.e.v, label.e.w, label.label);
  1801. g.removeNode(v);
  1802. label.label.points = [
  1803. { x: x + 2 * dx / 3, y: y - dy },
  1804. { x: x + 5 * dx / 6, y: y - dy },
  1805. { x: x + dx , y: y },
  1806. { x: x + 5 * dx / 6, y: y + dy },
  1807. { x: x + 2 * dx / 3, y: y + dy }
  1808. ];
  1809. label.label.x = label.x;
  1810. label.label.y = label.y;
  1811. }
  1812. }
  1813. };
  1814. const removeBorderNodes = (g) => {
  1815. for (const node of g.nodes.values()) {
  1816. const v = node.v;
  1817. if (g.children(v).length) {
  1818. const label = node.label;
  1819. const t = g.node(label.borderTop).label;
  1820. const b = g.node(label.borderBottom).label;
  1821. const l = g.node(label.borderLeft[label.borderLeft.length - 1]).label;
  1822. const r = g.node(label.borderRight[label.borderRight.length - 1]).label;
  1823. label.width = Math.abs(r.x - l.x);
  1824. label.height = Math.abs(b.y - t.y);
  1825. label.x = l.x + label.width / 2;
  1826. label.y = t.y + label.height / 2;
  1827. }
  1828. }
  1829. for (const node of g.nodes.values()) {
  1830. if (node.label.dummy === 'border') {
  1831. g.removeNode(node.v);
  1832. }
  1833. }
  1834. };
  1835. const fixupEdgeLabelCoords = (g) => {
  1836. for (const e of g.edges.values()) {
  1837. const edge = e.label;
  1838. if ('x' in edge) {
  1839. if (edge.labelpos === 'l' || edge.labelpos === 'r') {
  1840. edge.width -= edge.labeloffset;
  1841. }
  1842. switch (edge.labelpos) {
  1843. case 'l': edge.x -= edge.width / 2 + edge.labeloffset; break;
  1844. case 'r': edge.x += edge.width / 2 + edge.labeloffset; break;
  1845. default: throw new dagre.Error("Unsupported label position '" + edge.labelpos + "'.");
  1846. }
  1847. }
  1848. }
  1849. };
  1850. const translateGraph = (g) => {
  1851. let minX = Number.POSITIVE_INFINITY;
  1852. let maxX = 0;
  1853. let minY = Number.POSITIVE_INFINITY;
  1854. let maxY = 0;
  1855. const getExtremes = (attrs) => {
  1856. const x = attrs.x;
  1857. const y = attrs.y;
  1858. const w = attrs.width;
  1859. const h = attrs.height;
  1860. minX = Math.min(minX, x - w / 2);
  1861. maxX = Math.max(maxX, x + w / 2);
  1862. minY = Math.min(minY, y - h / 2);
  1863. maxY = Math.max(maxY, y + h / 2);
  1864. };
  1865. for (const node of g.nodes.values()) {
  1866. getExtremes(node.label);
  1867. }
  1868. for (const e of g.edges.values()) {
  1869. const edge = e.label;
  1870. if ('x' in edge) {
  1871. getExtremes(edge);
  1872. }
  1873. }
  1874. for (const node of g.nodes.values()) {
  1875. node.label.x -= minX;
  1876. node.label.y -= minY;
  1877. }
  1878. for (const e of g.edges.values()) {
  1879. const edge = e.label;
  1880. for (const p of edge.points) {
  1881. p.x -= minX;
  1882. p.y -= minY;
  1883. }
  1884. if ('x' in edge) {
  1885. edge.x -= minX;
  1886. }
  1887. if ('y' in edge) {
  1888. edge.y -= minY;
  1889. }
  1890. }
  1891. const graphLabel = g.options;
  1892. graphLabel.width = maxX - minX;
  1893. graphLabel.height = maxY - minY;
  1894. };
  1895. const assignNodeIntersects = (g) => {
  1896. // Finds where a line starting at point ({x, y}) would intersect a rectangle
  1897. // ({x, y, width, height}) if it were pointing at the rectangle's center.
  1898. const intersectRect = (rect, point) => {
  1899. const x = rect.x;
  1900. const y = rect.y;
  1901. // Rectangle intersection algorithm from: http://math.stackexchange.com/questions/108113/find-edge-between-two-boxes
  1902. const dx = point.x - x;
  1903. const dy = point.y - y;
  1904. if (dx === 0 && dy === 0) {
  1905. throw new Error('Not possible to find intersection inside of the rectangle');
  1906. }
  1907. let w = rect.width / 2;
  1908. let h = rect.height / 2;
  1909. if (Math.abs(dy) * w > Math.abs(dx) * h) {
  1910. // Intersection is top or bottom of rect.
  1911. h = dy < 0 ? -h : h;
  1912. return { x: x + (h * dx / dy), y: y + h };
  1913. }
  1914. // Intersection is left or right of rect.
  1915. w = dx < 0 ? -w : w;
  1916. return { x: x + w, y: y + (w * dy / dx) };
  1917. };
  1918. for (const e of g.edges.values()) {
  1919. const edge = e.label;
  1920. const vNode = e.vNode.label;
  1921. const wNode = e.wNode.label;
  1922. let p1;
  1923. let p2;
  1924. if (!edge.points) {
  1925. edge.points = [];
  1926. p1 = wNode;
  1927. p2 = vNode;
  1928. }
  1929. else {
  1930. p1 = edge.points[0];
  1931. p2 = edge.points[edge.points.length - 1];
  1932. }
  1933. edge.points.unshift(intersectRect(vNode, p1));
  1934. edge.points.push(intersectRect(wNode, p2));
  1935. }
  1936. };
  1937. time(' makeSpaceForEdgeLabels', () => { makeSpaceForEdgeLabels(g); });
  1938. time(' removeSelfEdges', () => { removeSelfEdges(g); });
  1939. time(' acyclic_run', () => { acyclic_run(g); });
  1940. time(' nestingGraph_run', () => { nestingGraph_run(g); });
  1941. time(' rank', () => { rank(asNonCompoundGraph(g)); });
  1942. time(' injectEdgeLabelProxies', () => { injectEdgeLabelProxies(g); });
  1943. time(' removeEmptyRanks', () => { removeEmptyRanks(g); });
  1944. time(' nestingGraph_cleanup', () => { nestingGraph_cleanup(g); });
  1945. time(' assignRankMinMax', () => { assignRankMinMax(g); });
  1946. time(' removeEdgeLabelProxies', () => { removeEdgeLabelProxies(g); });
  1947. time(' normalize', () => { normalize(g); });
  1948. time(' parentDummyChains', () => { parentDummyChains(g); });
  1949. time(' addBorderSegments', () => { addBorderSegments(g); });
  1950. time(' order', () => { order(g); });
  1951. time(' insertSelfEdges', () => { insertSelfEdges(g); });
  1952. time(' coordinateSystem_adjust', () => { coordinateSystem_adjust(g); });
  1953. time(' position', () => { position(g); });
  1954. time(' positionSelfEdges', () => { positionSelfEdges(g); });
  1955. time(' removeBorderNodes', () => { removeBorderNodes(g); });
  1956. time(' denormalize', () => { denormalize(g); });
  1957. time(' fixupEdgeLabelCoords', () => { fixupEdgeLabelCoords(g); });
  1958. time(' coordinateSystem_undo', () => { coordinateSystem_undo(g); });
  1959. time(' translateGraph', () => { translateGraph(g); });
  1960. time(' assignNodeIntersects', () => { assignNodeIntersects(g); });
  1961. time(' acyclic_undo', () => { acyclic_undo(g); });
  1962. };
  1963. // Copies final layout information from the layout graph back to the input graph.
  1964. // This process only copies whitelisted attributes from the layout graph to the input graph,
  1965. // so it serves as a good place to determine what attributes can influence layout.
  1966. const updateSourceGraph = (graph, g) => {
  1967. for (const node of graph.nodes.values()) {
  1968. const label = node.label;
  1969. if (label) {
  1970. const v = node.v;
  1971. const layoutLabel = g.node(v).label;
  1972. label.x = layoutLabel.x;
  1973. label.y = layoutLabel.y;
  1974. if (g.children(v).length) {
  1975. label.width = layoutLabel.width;
  1976. label.height = layoutLabel.height;
  1977. }
  1978. }
  1979. }
  1980. for (const e of graph.edges.values()) {
  1981. const label = g.edge(e.v, e.w).label;
  1982. e.label.points = label.points;
  1983. if ('x' in label) {
  1984. e.label.x = label.x;
  1985. e.label.y = label.y;
  1986. }
  1987. }
  1988. graph.options.width = g.options.width;
  1989. graph.options.height = g.options.height;
  1990. };
  1991. time('layout', () => {
  1992. const layoutGraph =
  1993. time(' buildLayoutGraph', () => { return buildLayoutGraph(graph); });
  1994. time(' runLayout', () => { runLayout(layoutGraph, time); });
  1995. time(' updateSourceGraph', () => { updateSourceGraph(graph, layoutGraph); });
  1996. });
  1997. };
  1998. dagre.Graph = class {
  1999. constructor(options) {
  2000. options = options || {};
  2001. this._directed = 'directed' in options ? options.directed : true;
  2002. this._compound = 'compound' in options ? options.compound : false;
  2003. this._label = undefined;
  2004. this._defaultNodeLabelFn = () => {
  2005. return undefined;
  2006. };
  2007. this.nodes = new Map();
  2008. this.edges = new Map();
  2009. if (this._compound) {
  2010. this._parent = {};
  2011. this._children = {};
  2012. this._children['\x00'] = {};
  2013. }
  2014. }
  2015. set options(value) {
  2016. this._label = value;
  2017. }
  2018. get options() {
  2019. return this._label;
  2020. }
  2021. isDirected() {
  2022. return this._directed;
  2023. }
  2024. isCompound() {
  2025. return this._compound;
  2026. }
  2027. setDefaultNodeLabel(newDefault) {
  2028. this._defaultNodeLabelFn = newDefault;
  2029. }
  2030. setNode(v, label) {
  2031. const node = this.nodes.get(v);
  2032. if (node) {
  2033. if (label) {
  2034. node.label = label;
  2035. }
  2036. }
  2037. else {
  2038. const node = { label: label ? label : this._defaultNodeLabelFn(v), in: [], out: [], predecessors: {}, successors: {}, v: v };
  2039. this.nodes.set(v, node);
  2040. if (this._compound) {
  2041. this._parent[v] = '\x00';
  2042. this._children[v] = {};
  2043. this._children['\x00'][v] = true;
  2044. }
  2045. }
  2046. }
  2047. node(v) {
  2048. return this.nodes.get(v);
  2049. }
  2050. hasNode(v) {
  2051. return this.nodes.has(v);
  2052. }
  2053. removeNode(v) {
  2054. const node = this.nodes.get(v);
  2055. if (node) {
  2056. if (this._compound) {
  2057. delete this._children[this._parent[v]][v];
  2058. delete this._parent[v];
  2059. for (const child of this.children(v)) {
  2060. this.setParent(child);
  2061. }
  2062. delete this._children[v];
  2063. }
  2064. for (const edge of node.in) {
  2065. this.removeEdge(edge);
  2066. }
  2067. for (const edge of node.out) {
  2068. this.removeEdge(edge);
  2069. }
  2070. this.nodes.delete(v);
  2071. }
  2072. }
  2073. setParent(v, parent) {
  2074. if (!this._compound) {
  2075. throw new Error('Cannot set parent in a non-compound graph');
  2076. }
  2077. if (parent) {
  2078. for (let ancestor = parent; ancestor !== undefined; ancestor = this.parent(ancestor)) {
  2079. if (ancestor === v) {
  2080. throw new Error('Setting ' + parent + ' as parent of ' + v + ' would create a cycle.');
  2081. }
  2082. }
  2083. this.setNode(parent);
  2084. }
  2085. else {
  2086. parent = '\x00';
  2087. }
  2088. delete this._children[this._parent[v]][v];
  2089. this._parent[v] = parent;
  2090. this._children[parent][v] = true;
  2091. }
  2092. parent(v) {
  2093. if (this._compound) {
  2094. const parent = this._parent[v];
  2095. if (parent !== '\x00') {
  2096. return parent;
  2097. }
  2098. }
  2099. return null;
  2100. }
  2101. children(v) {
  2102. if (this._compound) {
  2103. return Object.keys(this._children[v === undefined ? '\x00' : v]);
  2104. }
  2105. else if (v === undefined) {
  2106. return this.nodes.keys();
  2107. }
  2108. else if (this.hasNode(v)) {
  2109. return [];
  2110. }
  2111. return null;
  2112. }
  2113. predecessors(v) {
  2114. return Object.keys(this.nodes.get(v).predecessors);
  2115. }
  2116. successors(v) {
  2117. return Object.keys(this.nodes.get(v).successors);
  2118. }
  2119. neighbors(v) {
  2120. return Array.from(new Set(this.predecessors(v).concat(this.successors(v))));
  2121. }
  2122. edge(v, w) {
  2123. return this.edges.get(this._edgeKey(this._directed, v, w));
  2124. }
  2125. setEdge(v, w, label, name) {
  2126. const key = this._edgeKey(this._directed, v, w, name);
  2127. const edge = this.edges.get(key);
  2128. if (edge) {
  2129. edge.label = label;
  2130. }
  2131. else {
  2132. if (!this._directed && v > w) {
  2133. const tmp = v;
  2134. v = w;
  2135. w = tmp;
  2136. }
  2137. const edge = { label: label, v: v, w: w, name: name, key: key, vNode: null, wNode: null };
  2138. this.edges.set(key, edge);
  2139. this.setNode(v);
  2140. this.setNode(w);
  2141. const wNode = this.nodes.get(w);
  2142. const vNode = this.nodes.get(v);
  2143. edge.wNode = wNode;
  2144. edge.vNode = vNode;
  2145. const incrementOrInitEntry = (map, k) => {
  2146. if (map[k]) {
  2147. map[k]++;
  2148. }
  2149. else {
  2150. map[k] = 1;
  2151. }
  2152. };
  2153. incrementOrInitEntry(wNode.predecessors, v);
  2154. incrementOrInitEntry(vNode.successors, w);
  2155. wNode.in.push(edge);
  2156. vNode.out.push(edge);
  2157. }
  2158. }
  2159. removeEdge(edge) {
  2160. const key = edge.key;
  2161. const v = edge.v;
  2162. const w = edge.w;
  2163. const decrementOrRemoveEntry = (map, k) => {
  2164. if (!--map[k]) {
  2165. delete map[k];
  2166. }
  2167. };
  2168. const wNode = edge.wNode;
  2169. const vNode = edge.vNode;
  2170. decrementOrRemoveEntry(wNode.predecessors, v);
  2171. decrementOrRemoveEntry(vNode.successors, w);
  2172. wNode.in = wNode.in.filter((edge) => edge.key !== key);
  2173. vNode.out = vNode.out.filter((edge) => edge.key !== key);
  2174. this.edges.delete(key);
  2175. }
  2176. _edgeKey(isDirected, v, w, name) {
  2177. if (!isDirected && v > w) {
  2178. return name ? w + ':' + v + ':' + name : w + ':' + v + ':';
  2179. }
  2180. return name ? v + ':' + w + ':' + name : v + ':' + w + ':';
  2181. }
  2182. toString() {
  2183. return [
  2184. '[nodes]', Array.from(this.nodes.values()).map(n => JSON.stringify(n.label)).join('\n'),
  2185. '[edges]', Array.from(this.edges.values()).map(e => JSON.stringify(e.label)).join('\n'),
  2186. '[parents]', JSON.stringify(this._parent, null, 2),
  2187. '[children]', JSON.stringify(this._children, null, 2)
  2188. ].join('\n');
  2189. }
  2190. };
  2191. if (typeof module !== 'undefined' && typeof module.exports === 'object') {
  2192. module.exports = dagre;
  2193. }