dagre.js 96 KB

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