dagre.js 102 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444
  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.hasChildren(v)) {
  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. for (const child of g.children(v)) {
  580. dfs(child, depth + 1);
  581. }
  582. depths[v] = depth;
  583. };
  584. for (const v of g.children()) {
  585. dfs(v, 1);
  586. }
  587. return depths;
  588. };
  589. const dfs = (g, root, nodeSep, weight, height, depths, v) => {
  590. const children = Array.from(g.children(v));
  591. if (!children.length) {
  592. if (v !== root) {
  593. g.setEdge(root, v, { weight: 0, minlen: nodeSep });
  594. }
  595. return;
  596. }
  597. const top = addDummyNode(g, 'border', { width: 0, height: 0 }, '_bt');
  598. const bottom = addDummyNode(g, 'border', { width: 0, height: 0 }, '_bb');
  599. const label = g.node(v).label;
  600. g.hasBorder = true;
  601. g.setParent(top, v);
  602. label.borderTop = top;
  603. g.setParent(bottom, v);
  604. label.borderBottom = bottom;
  605. for (const child of children) {
  606. dfs(g, root, nodeSep, weight, height, depths, child);
  607. const childNode = g.node(child).label;
  608. const childTop = childNode.borderTop ? childNode.borderTop : child;
  609. const childBottom = childNode.borderBottom ? childNode.borderBottom : child;
  610. const thisWeight = childNode.borderTop ? weight : 2 * weight;
  611. const minlen = childTop === childBottom ? height - depths[v] + 1 : 1;
  612. g.setEdge(top, childTop, { weight: thisWeight, minlen, nestingEdge: true });
  613. g.setEdge(childBottom, bottom, { weight: thisWeight, minlen, nestingEdge: true });
  614. }
  615. if (!g.parent(v)) {
  616. g.setEdge(root, top, { weight: 0, minlen: height + depths[v] });
  617. }
  618. };
  619. const depths = treeDepths(g);
  620. const height = Math.max(...Object.values(depths)) - 1; // Note: depths is an Object not an array
  621. const nodeSep = 2 * height + 1;
  622. state.nestingRoot = root;
  623. // Multiply minlen by nodeSep to align nodes on non-border ranks.
  624. for (const e of g.edges.values()) {
  625. e.label.minlen *= nodeSep;
  626. }
  627. // Calculate a weight that is sufficient to keep subgraphs vertically compact
  628. const weight = Array.from(g.edges.values()).reduce((acc, e) => acc + e.label.weight, 0) + 1;
  629. // Create border nodes and link them up
  630. for (const child of g.children()) {
  631. dfs(g, root, nodeSep, weight, height, depths, child);
  632. }
  633. // Save the multiplier for node layers for later removal of empty border layers.
  634. state.nodeRankFactor = nodeSep;
  635. };
  636. const nestingGraph_cleanup = (g, state) => {
  637. g.removeNode(state.nestingRoot);
  638. delete state.nestingRoot;
  639. for (const e of g.edges.values()) {
  640. if (e.label.nestingEdge) {
  641. g.removeEdge(e);
  642. }
  643. }
  644. };
  645. const assignRankMinMax = (g, state) => {
  646. // 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.
  647. let min = Number.POSITIVE_INFINITY;
  648. for (const node of g.nodes.values()) {
  649. const rank = node.label.rank;
  650. if (rank !== undefined && rank < min) {
  651. min = rank;
  652. }
  653. }
  654. for (const node of g.nodes.values()) {
  655. const label = node.label;
  656. if (label.rank !== undefined) {
  657. label.rank -= min;
  658. }
  659. }
  660. let maxRank = 0;
  661. if (g.hasBorder) {
  662. for (const node of g.nodes.values()) {
  663. const label = node.label;
  664. if (label.borderTop) {
  665. label.minRank = g.node(label.borderTop).label.rank;
  666. label.maxRank = g.node(label.borderBottom).label.rank;
  667. maxRank = Math.max(maxRank, label.maxRank);
  668. }
  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 = Array.from(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. for (const v of children) {
  851. queue.push(v);
  852. }
  853. }
  854. };
  855. // Applies heuristics to minimize edge crossings in the graph and sets the best order solution as an order attribute on each node.
  856. //
  857. // Pre-conditions:
  858. // 1. Graph must be DAG
  859. // 2. Graph nodes must have the 'rank' attribute
  860. // 3. Graph edges must have the 'weight' attribute
  861. //
  862. // Post-conditions:
  863. // 1. Graph nodes will have an 'order' attribute based on the results of the algorithm.
  864. const order = (g) => {
  865. const sortSubgraph = (g, v, cg, biasRight) => {
  866. // 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.
  867. // 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.
  868. // 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.
  869. //
  870. // Pre-conditions:
  871. // 1. Each entry has the form {v, barycenter, weight}, or if the node has no barycenter, then {v}.
  872. //
  873. // Returns:
  874. // A new list of entries of the form {vs, i, barycenter, weight}.
  875. // 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.
  876. // The property `i` is the lowest original index of any of the elements in `vs`.
  877. const resolveConflicts = (entries, cg) => {
  878. const mappedEntries = new Map();
  879. for (let i = 0; i < entries.length; i++) {
  880. const entry = entries[i];
  881. const tmp = { indegree: 0, 'in': [], out: [], vs: [entry.v], i };
  882. if (entry.barycenter !== undefined) {
  883. tmp.barycenter = entry.barycenter;
  884. tmp.weight = entry.weight;
  885. }
  886. mappedEntries.set(entry.v, tmp);
  887. }
  888. for (const e of cg.edges.values()) {
  889. const entryV = mappedEntries.get(e.v);
  890. const entryW = mappedEntries.get(e.w);
  891. if (entryV && entryW) {
  892. entryW.indegree++;
  893. entryV.out.push(entryW);
  894. }
  895. }
  896. const sourceSet = Array.from(mappedEntries.values()).filter((entry) => !entry.indegree);
  897. const results = [];
  898. const handleIn = function(vEntry) {
  899. return function(uEntry) {
  900. if (uEntry.merged) {
  901. return;
  902. }
  903. if (uEntry.barycenter === undefined || vEntry.barycenter === undefined || uEntry.barycenter >= vEntry.barycenter) {
  904. let sum = 0;
  905. let weight = 0;
  906. if (vEntry.weight) {
  907. sum += vEntry.barycenter * vEntry.weight;
  908. weight += vEntry.weight;
  909. }
  910. if (uEntry.weight) {
  911. sum += uEntry.barycenter * uEntry.weight;
  912. weight += uEntry.weight;
  913. }
  914. vEntry.vs = uEntry.vs.concat(vEntry.vs);
  915. vEntry.barycenter = sum / weight;
  916. vEntry.weight = weight;
  917. vEntry.i = Math.min(uEntry.i, vEntry.i);
  918. uEntry.merged = true;
  919. }
  920. };
  921. };
  922. const handleOut = (vEntry) => {
  923. return function(wEntry) {
  924. wEntry.in.push(vEntry);
  925. if (--wEntry.indegree === 0) {
  926. sourceSet.push(wEntry);
  927. }
  928. };
  929. };
  930. while (sourceSet.length) {
  931. const entry = sourceSet.pop();
  932. results.push(entry);
  933. entry.in.reverse().forEach(handleIn(entry));
  934. entry.out.forEach(handleOut(entry));
  935. }
  936. return results.filter((entry) => !entry.merged).map((entry) => {
  937. const value = {
  938. vs: entry.vs,
  939. i: entry.i
  940. };
  941. if (entry.barycenter !== undefined) {
  942. value.barycenter = entry.barycenter;
  943. }
  944. if (entry.weight !== undefined) {
  945. value.weight = entry.weight;
  946. }
  947. return value;
  948. });
  949. };
  950. const barycenter = (g, movable) => {
  951. return Array.from(movable).map((v) => {
  952. const inV = g.node(v).in;
  953. if (!inV.length) {
  954. return { v };
  955. }
  956. const result = inV.reduce((acc, e) => {
  957. const edge = e.label;
  958. const nodeU = e.vNode.label;
  959. return {
  960. sum: acc.sum + (edge.weight * nodeU.order),
  961. weight: acc.weight + edge.weight
  962. };
  963. }, { sum: 0, weight: 0 });
  964. return {
  965. v,
  966. barycenter: result.sum / result.weight,
  967. weight: result.weight
  968. };
  969. });
  970. };
  971. const sort = (entries, biasRight) => {
  972. const consumeUnsortable = (vs, unsortable, index) => {
  973. let last = null;
  974. while (unsortable.length && (last = unsortable[unsortable.length - 1]).i <= index) {
  975. unsortable.pop();
  976. vs.push(last.vs);
  977. index++;
  978. }
  979. return index;
  980. };
  981. const compareWithBias = (bias) => {
  982. return function(entryV, entryW) {
  983. if (entryV.barycenter < entryW.barycenter) {
  984. return -1;
  985. } else if (entryV.barycenter > entryW.barycenter) {
  986. return 1;
  987. }
  988. return bias ? entryW.i - entryV.i : entryV.i - entryW.i;
  989. };
  990. };
  991. // partition
  992. const parts = { lhs: [], rhs: [] };
  993. for (const value of entries) {
  994. if ('barycenter' in value) {
  995. parts.lhs.push(value);
  996. } else {
  997. parts.rhs.push(value);
  998. }
  999. }
  1000. const sortable = parts.lhs;
  1001. const unsortable = parts.rhs.sort((a, b) => -a.i + b.i);
  1002. const vs = [];
  1003. let sum = 0;
  1004. let weight = 0;
  1005. let vsIndex = 0;
  1006. sortable.sort(compareWithBias(Boolean(biasRight)));
  1007. vsIndex = consumeUnsortable(vs, unsortable, vsIndex);
  1008. for (const entry of sortable) {
  1009. vsIndex += entry.vs.length;
  1010. vs.push(entry.vs);
  1011. sum += entry.barycenter * entry.weight;
  1012. weight += entry.weight;
  1013. vsIndex = consumeUnsortable(vs, unsortable, vsIndex);
  1014. }
  1015. const result = { vs: flat(vs) };
  1016. if (weight) {
  1017. result.barycenter = sum / weight;
  1018. result.weight = weight;
  1019. }
  1020. return result;
  1021. };
  1022. const node = g.node(v);
  1023. const bl = node && node.label ? node.label.borderLeft : undefined;
  1024. const br = node && node.label ? node.label.borderRight : undefined;
  1025. const subgraphs = {};
  1026. const movable = bl ? Array.from(g.children(v)).filter((w) => w !== bl && w !== br) : g.children(v);
  1027. const barycenters = barycenter(g, movable);
  1028. for (const entry of barycenters) {
  1029. if (g.hasChildren(entry.v)) {
  1030. const result = sortSubgraph(g, entry.v, cg, biasRight);
  1031. subgraphs[entry.v] = result;
  1032. if ('barycenter' in result) {
  1033. if (entry.barycenter === undefined) {
  1034. entry.barycenter = result.barycenter;
  1035. entry.weight = result.weight;
  1036. } else {
  1037. entry.barycenter = (entry.barycenter * entry.weight + result.barycenter * result.weight) / (entry.weight + result.weight);
  1038. entry.weight += result.weight;
  1039. }
  1040. }
  1041. }
  1042. }
  1043. const entries = resolveConflicts(barycenters, cg);
  1044. // expand subgraphs
  1045. for (const entry of entries) {
  1046. entry.vs = flat(entry.vs.map((v) => subgraphs[v] ? subgraphs[v].vs : v));
  1047. }
  1048. const result = sort(entries, biasRight);
  1049. if (bl) {
  1050. result.vs = flat([bl, result.vs, br]);
  1051. const predecessors = g.predecessors(bl);
  1052. if (predecessors.size > 0) {
  1053. const blPred = g.node(predecessors.keys().next().value).label;
  1054. const brPred = g.node(g.predecessors(br).keys().next().value).label;
  1055. if (!('barycenter' in result)) {
  1056. result.barycenter = 0;
  1057. result.weight = 0;
  1058. }
  1059. result.barycenter = (result.barycenter * result.weight + blPred.order + brPred.order) / (result.weight + 2);
  1060. result.weight += 2;
  1061. }
  1062. }
  1063. return result;
  1064. };
  1065. const sweepLayerGraphs = (layerGraphs, biasRight) => {
  1066. const cg = new dagre.Graph(true, false);
  1067. for (const lg of layerGraphs) {
  1068. const root = lg.root;
  1069. const sorted = sortSubgraph(lg, root, cg, biasRight);
  1070. const vs = sorted.vs;
  1071. const length = vs.length;
  1072. for (let i = 0; i < length; i++) {
  1073. lg.node(vs[i]).label.order = i;
  1074. }
  1075. // add subgraph constraints
  1076. const prev = {};
  1077. let rootPrev = '';
  1078. let exit = false;
  1079. for (const v of vs) {
  1080. let child = lg.parent(v);
  1081. let prevChild = null;
  1082. while (child) {
  1083. const parent = lg.parent(child);
  1084. if (parent) {
  1085. prevChild = prev[parent];
  1086. prev[parent] = child;
  1087. } else {
  1088. prevChild = rootPrev;
  1089. rootPrev = child;
  1090. }
  1091. if (prevChild && prevChild !== child) {
  1092. cg.setEdge(prevChild, child, null);
  1093. exit = true;
  1094. break;
  1095. }
  1096. child = parent;
  1097. }
  1098. if (exit) {
  1099. break;
  1100. }
  1101. }
  1102. }
  1103. };
  1104. // A function that takes a layering (an array of layers, each with an array of
  1105. // ordererd nodes) and a graph and returns a weighted crossing count.
  1106. //
  1107. // Pre-conditions:
  1108. // 1. Input graph must be simple (not a multigraph), directed, and include
  1109. // only simple edges.
  1110. // 2. Edges in the input graph must have assigned weights.
  1111. //
  1112. // Post-conditions:
  1113. // 1. The graph and layering matrix are left unchanged.
  1114. //
  1115. // This algorithm is derived from Barth, et al., 'Bilayer Cross Counting.'
  1116. const crossCount = (g, layering, bestCC) => {
  1117. let count = 0;
  1118. for (let i = 1; i < layering.length; i++) {
  1119. const northLayer = layering[i - 1];
  1120. const southLayer = layering[i];
  1121. // Sort all of the edges between the north and south layers by their position in the north layer and then the south.
  1122. // Map these edges to the position of their head in the south layer.
  1123. const southPos = new Map();
  1124. for (let i = 0; i < southLayer.length; i++) {
  1125. southPos.set(southLayer[i], i);
  1126. }
  1127. const southEntries = [];
  1128. for (const v of northLayer) {
  1129. const entries = [];
  1130. for (const e of g.node(v).out) {
  1131. entries.push({
  1132. pos: southPos.get(e.w),
  1133. weight: e.label.weight
  1134. });
  1135. }
  1136. entries.sort((a, b) => a.pos - b.pos);
  1137. for (const entry of entries) {
  1138. southEntries.push(entry);
  1139. }
  1140. }
  1141. // Build the accumulator tree
  1142. let firstIndex = 1;
  1143. while (firstIndex < southLayer.length) {
  1144. firstIndex <<= 1;
  1145. }
  1146. const treeSize = 2 * firstIndex - 1;
  1147. firstIndex -= 1;
  1148. const tree = Array.from(new Array(treeSize), () => 0);
  1149. // Calculate the weighted crossings
  1150. for (const entry of southEntries) {
  1151. let index = entry.pos + firstIndex;
  1152. tree[index] += entry.weight;
  1153. let weightSum = 0;
  1154. while (index > 0) {
  1155. if (index % 2) {
  1156. weightSum += tree[index + 1];
  1157. }
  1158. index = (index - 1) >> 1;
  1159. tree[index] += entry.weight;
  1160. }
  1161. count += entry.weight * weightSum;
  1162. }
  1163. if (count > bestCC) {
  1164. break;
  1165. }
  1166. }
  1167. return count;
  1168. };
  1169. // Assigns an initial order value for each node by performing a DFS search
  1170. // starting from nodes in the first rank. Nodes are assigned an order in their
  1171. // rank as they are first visited.
  1172. //
  1173. // This approach comes from Gansner, et al., 'A Technique for Drawing Directed
  1174. // Graphs.'
  1175. //
  1176. // Returns a layering matrix with an array per layer and each layer sorted by
  1177. // the order of its nodes.
  1178. const initOrder = (g) => {
  1179. const visited = new Set();
  1180. const nodes = Array.from(g.nodes.values()).filter((node) => !g.hasChildren(node.v));
  1181. let maxRank = -1;
  1182. for (const node of nodes) {
  1183. const rank = node.label.rank;
  1184. if (maxRank === -1 || (rank !== undefined && rank > maxRank)) {
  1185. maxRank = rank;
  1186. }
  1187. }
  1188. if (maxRank !== -1) {
  1189. const layers = Array.from(new Array(maxRank + 1), () => []);
  1190. const queue = nodes.sort((a, b) => a.label.rank - b.label.rank).map((node) => node.v).reverse();
  1191. for (let i = 0; i < queue.length; i++) {
  1192. const v = queue[i];
  1193. if (!visited.has(v)) {
  1194. visited.add(v);
  1195. const rank = g.node(v).label.rank;
  1196. layers[rank].push(v);
  1197. queue.push(...g.successors(v).keys());
  1198. }
  1199. }
  1200. return layers;
  1201. }
  1202. return [];
  1203. };
  1204. // Constructs a graph that can be used to sort a layer of nodes.
  1205. // The graph will contain all base and subgraph nodes from the request layer in their original
  1206. // hierarchy and any edges that are incident on these nodes and are of the type requested by the 'relationship' parameter.
  1207. //
  1208. // Nodes from the requested rank that do not have parents are assigned a root node in the output graph,
  1209. // which is set in the root graph attribute.
  1210. // This makes it easy to walk the hierarchy of movable nodes during ordering.
  1211. //
  1212. // Pre-conditions:
  1213. // 1. Input graph is a DAG
  1214. // 2. Base nodes in the input graph have a rank attribute
  1215. // 3. Subgraph nodes in the input graph has minRank and maxRank attributes
  1216. // 4. Edges have an assigned weight
  1217. //
  1218. // Post-conditions:
  1219. // 1. Output graph has all nodes in the movable rank with preserved hierarchy.
  1220. // 2. Root nodes in the movable layer are made children of the node
  1221. // indicated by the root attribute of the graph.
  1222. // 3. Non-movable nodes incident on movable nodes, selected by the
  1223. // relationship parameter, are included in the graph (without hierarchy).
  1224. // 4. Edges incident on movable nodes, selected by the relationship parameter, are added to the output graph.
  1225. // 5. The weights for copied edges are aggregated as need, since the output graph is not a multi-graph.
  1226. const buildLayerGraph = (g, nodes, rankIndexes, rank, relationship) => {
  1227. let root = '';
  1228. while (g.hasNode((root = uniqueId('_root')))) {
  1229. // continue
  1230. }
  1231. const graph = new dagre.Graph(true, true);
  1232. graph.root = root;
  1233. graph.setDefaultNodeLabel((v) => {
  1234. const node = g.node(v);
  1235. return node ? node.label : undefined;
  1236. });
  1237. const length = nodes.length;
  1238. if (g.hasBorder) {
  1239. let i = 0;
  1240. while (i < length) {
  1241. const node = nodes[i++];
  1242. const label = node.label;
  1243. if (label.rank === rank || 'minRank' in label && 'maxRank' in label && label.minRank <= rank && rank <= label.maxRank) {
  1244. const v = node.v;
  1245. graph.setNode(v);
  1246. const parent = g.parent(v);
  1247. graph.setParent(v, parent || root);
  1248. // This assumes we have only short edges!
  1249. if (relationship) {
  1250. for (const e of node.in) {
  1251. graph.setEdge(e.v, v, { weight: e.label.weight });
  1252. }
  1253. } else {
  1254. for (const e of node.out) {
  1255. graph.setEdge(e.w, v, { weight: e.label.weight });
  1256. }
  1257. }
  1258. if ('minRank' in label) {
  1259. graph.setNode(v, {
  1260. borderLeft: label.borderLeft[rank],
  1261. borderRight: label.borderRight[rank]
  1262. });
  1263. }
  1264. }
  1265. }
  1266. } else {
  1267. // When label.borderTop isn't set, labels don't have minRank and maxRank properties so checking them can be skipped.
  1268. // And in that case, iterating nodes can be sped up by presorting nodes and using start indexes of each rank.
  1269. let i = rankIndexes.get(rank);
  1270. while (i < length) {
  1271. const node = nodes[i++];
  1272. const label = node.label;
  1273. if (label.rank !== rank) {
  1274. break;
  1275. }
  1276. const v = node.v;
  1277. graph.setNode(v);
  1278. const parent = g.parent(v);
  1279. graph.setParent(v, parent || root);
  1280. // This assumes we have only short edges!
  1281. if (relationship) {
  1282. for (const e of node.in) {
  1283. graph.setEdge(e.v, v, { weight: e.label.weight });
  1284. }
  1285. } else {
  1286. for (const e of node.out) {
  1287. graph.setEdge(e.w, v, { weight: e.label.weight });
  1288. }
  1289. }
  1290. }
  1291. }
  1292. return graph;
  1293. };
  1294. let layering = initOrder(g);
  1295. const assignOrder = (g, layering) => {
  1296. for (const layer of layering) {
  1297. for (let i = 0; i < layer.length; i++) {
  1298. g.node(layer[i]).label.order = i;
  1299. }
  1300. }
  1301. };
  1302. assignOrder(g, layering);
  1303. const rank = maxRank(g) || 0;
  1304. const downLayerGraphs = new Array(rank);
  1305. const upLayerGraphs = new Array(rank);
  1306. const nodes = Array.from(g.nodes.values());
  1307. let rankIndexes = null;
  1308. if (!g.hasBorder) {
  1309. nodes.sort((a, b) => {
  1310. return a.label.rank - b.label.rank;
  1311. });
  1312. rankIndexes = new Map();
  1313. for (let i = 0; i < nodes.length; ++i) {
  1314. const node = nodes[i];
  1315. const rank = node.label.rank;
  1316. if (!rankIndexes.has(rank)) {
  1317. rankIndexes.set(rank, i);
  1318. }
  1319. }
  1320. }
  1321. for (let i = 0; i < rank; i++) {
  1322. downLayerGraphs[i] = buildLayerGraph(g, nodes, rankIndexes, i + 1, true);
  1323. upLayerGraphs[i] = buildLayerGraph(g, nodes, rankIndexes, rank - i - 1, false);
  1324. }
  1325. let bestCC = Number.POSITIVE_INFINITY;
  1326. let best = [];
  1327. for (let i = 0, lastBest = 0; lastBest < 4; ++i, ++lastBest) {
  1328. sweepLayerGraphs(i % 2 ? downLayerGraphs : upLayerGraphs, i % 4 >= 2);
  1329. layering = buildLayerMatrix(g);
  1330. const cc = crossCount(g, layering, bestCC);
  1331. if (cc < bestCC) {
  1332. lastBest = 0;
  1333. const length = layering.length;
  1334. best = new Array(length);
  1335. for (let j = 0; j < length; j++) {
  1336. best[j] = layering[j].slice();
  1337. }
  1338. bestCC = cc;
  1339. }
  1340. }
  1341. // Reduce crossings
  1342. const calcDir = (idx0, idx1) => (idx0 < idx1) ? 1 : 2;
  1343. for (let i = 4; i < best.length; i += 2) {
  1344. const layer = best[i];
  1345. for (let j = 0; j < layer.length; ++j) {
  1346. const node = g.nodes.get(layer[j]);
  1347. if (node.in && node.in.length === 2) {
  1348. let n0 = node.in[0].vNode.in[0].vNode;
  1349. let n1 = node.in[1].vNode.in[0].vNode;
  1350. const indexes = [];
  1351. let dirTotal = 0;
  1352. for (let k = i - 2; k >= 0; k -= 2) {
  1353. const layer0 = best[k];
  1354. const idx0 = layer0.indexOf(n0.v);
  1355. const idx1 = layer0.indexOf(n1.v);
  1356. const dir = calcDir(idx0, idx1);
  1357. dirTotal |= dir;
  1358. if (idx0 === idx1
  1359. || Math.abs(idx0 - idx1) !== 1
  1360. || n0.in.length !== 1
  1361. || n1.in.length !== 1
  1362. || n0.out.length !== 1
  1363. || n1.out.length !== 1
  1364. ) {
  1365. if (dirTotal === 3) {
  1366. const topDir = dir;
  1367. let l = k + 2;
  1368. while (indexes.length !== 0) {
  1369. const idx1 = indexes.pop();
  1370. const idx0 = indexes.pop();
  1371. const layer1 = best[l];
  1372. const layer2 = best[l - 1];
  1373. const idx2 = layer2.indexOf(g.node(layer1[idx0]).in[0].v);
  1374. const idx3 = layer2.indexOf(g.node(layer1[idx1]).in[0].v);
  1375. if (calcDir(idx0, idx1) !== topDir) {
  1376. [layer1[idx0], layer1[idx1]] = [layer1[idx1], layer1[idx0]];
  1377. }
  1378. if (calcDir(idx2, idx3) !== topDir) {
  1379. [layer2[idx2], layer2[idx3]] = [layer2[idx3], layer2[idx2]];
  1380. }
  1381. l += 2;
  1382. }
  1383. }
  1384. break;
  1385. }
  1386. indexes.push(idx0, idx1);
  1387. n0 = n0.in[0].vNode.in[0].vNode;
  1388. n1 = n1.in[0].vNode.in[0].vNode;
  1389. }
  1390. }
  1391. }
  1392. }
  1393. const exchange = (layer, node0, node1) => {
  1394. const index0 = layer.indexOf(node0.v);
  1395. const index1 = layer.indexOf(node1.v);
  1396. layer[index1] = node0.v;
  1397. layer[index0] = node1.v;
  1398. };
  1399. for (let i = 0; i < best.length - 2; i += 2) {
  1400. const layer0 = best[i];
  1401. const layer1 = best[i + 1];
  1402. const layer2 = best[i + 2];
  1403. for (let j = 0; j < layer0.length; ++j) {
  1404. const node0 = g.nodes.get(layer0[j]);
  1405. if (node0.out && node0.out.length >= 2) {
  1406. for (let k = 0; k < node0.out.length - 1; ++k) {
  1407. const node1d = node0.out[k].wNode;
  1408. const node2d = node0.out[k + 1].wNode;
  1409. const node1 = node1d.out[0].wNode;
  1410. const node2 = node2d.out[0].wNode;
  1411. if ((layer1.indexOf(node1d.v) < layer1.indexOf(node2d.v)) ^ (layer2.indexOf(node1.v) < layer2.indexOf(node2.v))) {
  1412. exchange(layer1, node1d, node2d);
  1413. }
  1414. }
  1415. }
  1416. }
  1417. for (let j = 0; j < layer2.length; ++j) {
  1418. const node0 = g.nodes.get(layer2[j]);
  1419. if (node0.in && node0.in.length >= 2) {
  1420. if (node0.in.length === 2) {
  1421. const node1d = node0.in[0].vNode;
  1422. const node2d = node0.in[1].vNode;
  1423. const node1 = node1d.in[0].vNode;
  1424. const node2 = node2d.in[0].vNode;
  1425. if ((layer1.indexOf(node1d.v) < layer1.indexOf(node2d.v)) ^ (layer0.indexOf(node1.v) < layer0.indexOf(node2.v))) {
  1426. exchange(layer1, node1d, node2d);
  1427. }
  1428. } else {
  1429. const indexes1 = [];
  1430. for (let k = 0; k < node0.in.length; ++k) {
  1431. const node1 = node0.in[k].vNode;
  1432. const node2 = node1.in[0].vNode;
  1433. const idx0 = layer0.indexOf(node2.v);
  1434. const idx1 = layer1.indexOf(node1.v);
  1435. node0.in[k].idx0 = idx0;
  1436. indexes1.push(idx1);
  1437. }
  1438. node0.in.sort((a, b) => a.idx0 - b.idx0);
  1439. indexes1.sort((a, b) => a - b);
  1440. for (let k = 0; k < indexes1.length; ++k) {
  1441. layer1[indexes1[k]] = node0.in[k].v;
  1442. }
  1443. }
  1444. }
  1445. }
  1446. }
  1447. for (let i = 0; i < best.length - 4; i += 2) {
  1448. const layer0 = best[i];
  1449. const layer2 = best[i + 2];
  1450. const layer4 = best[i + 4];
  1451. if (layer2.length >= 2 && layer4.length >= 2) {
  1452. const layer1 = best[i + 1];
  1453. const layer3 = best[i + 3];
  1454. for (let j = 0; j < layer0.length; ++j) {
  1455. const node0 = g.nodes.get(layer0[j]);
  1456. if (node0.in && node0.out && node0.out.length >= 2) {
  1457. for (let k = 0; k < node0.out.length - 1; ++k) {
  1458. const node1u = node0.out[k].wNode;
  1459. const node2u = node0.out[k + 1].wNode;
  1460. const node1 = node1u.out[0].wNode;
  1461. const node2 = node2u.out[0].wNode;
  1462. if (node1.out.length === 1 && node2.out.length === 1) {
  1463. const index1 = layer2.indexOf(node1.v);
  1464. const index2 = layer2.indexOf(node2.v);
  1465. if (index1 + 1 === index2) {
  1466. const node1d = node1.out[0].wNode;
  1467. const node2d = node2.out[0].wNode;
  1468. if (node1d.out.length === 1 && node2d.out.length === 1) {
  1469. const node3 = node1d.out[0].wNode;
  1470. const node4 = node2d.out[0].wNode;
  1471. const index3 = layer4.indexOf(node3.v);
  1472. const index4 = layer4.indexOf(node4.v);
  1473. if (index3 > index4) {
  1474. exchange(layer1, node1u, node2u);
  1475. exchange(layer2, node1, node2);
  1476. exchange(layer3, node1d, node2d);
  1477. ++k;
  1478. }
  1479. }
  1480. }
  1481. }
  1482. }
  1483. }
  1484. }
  1485. for (let j = 0; j < layer2.length - 1; ++j) {
  1486. const node0 = g.nodes.get(layer2[j]);
  1487. if (node0.in && node0.out && node0.in.length === 1 && node0.out.length === 1) {
  1488. const node1 = g.nodes.get(layer2[j + 1]);
  1489. if (node1.in && node1.out && node1.in.length === 1 && node1.out.length === 1) {
  1490. const node0u = node0.in[0].vNode;
  1491. const node1u = node1.in[0].vNode;
  1492. if (node0u.in.length === 1 && node1u.in.length === 1) {
  1493. const node2 = node0u.in[0].vNode;
  1494. const node3 = node1u.in[0].vNode;
  1495. let index0 = layer0.indexOf(node2.v);
  1496. let index1 = layer0.indexOf(node3.v);
  1497. if (index1 + 1 === index0) {
  1498. const node0d = node0.out[0].wNode;
  1499. const node1d = node1.out[0].wNode;
  1500. index0 = layer3.indexOf(node0d.v);
  1501. index1 = layer3.indexOf(node1d.v);
  1502. if (index0 + 1 === index1 && node0d.out[0].wNode === node1d.out[0].wNode) {
  1503. exchange(layer1, node0u, node1u);
  1504. exchange(layer2, node0, node1);
  1505. exchange(layer3, node0d, node1d);
  1506. j += 1;
  1507. }
  1508. }
  1509. }
  1510. }
  1511. }
  1512. }
  1513. }
  1514. }
  1515. assignOrder(g, best);
  1516. };
  1517. const insertSelfEdges = (g) => {
  1518. const layers = buildLayerMatrix(g);
  1519. for (const layer of layers) {
  1520. let orderShift = 0;
  1521. layer.forEach((v, i) => {
  1522. const label = g.node(v).label;
  1523. label.order = i + orderShift;
  1524. if (label.selfEdges) {
  1525. for (const selfEdge of label.selfEdges) {
  1526. addDummyNode(g, 'selfedge', {
  1527. width: selfEdge.label.width,
  1528. height: selfEdge.label.height,
  1529. rank: label.rank,
  1530. order: i + (++orderShift),
  1531. e: selfEdge.e,
  1532. label: selfEdge.label
  1533. }, '_se');
  1534. }
  1535. delete label.selfEdges;
  1536. }
  1537. });
  1538. }
  1539. };
  1540. const coordinateSystem_swapWidthHeight = (g) => {
  1541. for (const node of g.nodes.values()) {
  1542. const label = node.label;
  1543. const w = label.width;
  1544. label.width = label.height;
  1545. label.height = w;
  1546. }
  1547. for (const e of g.edges.values()) {
  1548. const label = e.label;
  1549. const w = label.width;
  1550. label.width = label.height;
  1551. label.height = w;
  1552. }
  1553. };
  1554. const coordinateSystem_adjust = (g, state, layout) => {
  1555. const rankDir = layout.rankdir.toLowerCase();
  1556. if (rankDir === 'lr' || rankDir === 'rl') {
  1557. coordinateSystem_swapWidthHeight(g);
  1558. }
  1559. };
  1560. const coordinateSystem_undo = (g, state, layout) => {
  1561. const rankDir = layout.rankdir.toLowerCase();
  1562. if (rankDir === 'bt' || rankDir === 'rl') {
  1563. for (const node of g.nodes.values()) {
  1564. node.label.y = -node.label.y;
  1565. }
  1566. for (const e of g.edges.values()) {
  1567. const edge = e.label;
  1568. for (const attr of edge.points) {
  1569. attr.y = -attr.y;
  1570. }
  1571. if ('y' in edge) {
  1572. edge.y = -edge.y;
  1573. }
  1574. }
  1575. }
  1576. if (rankDir === 'lr' || rankDir === 'rl') {
  1577. const swapXYOne = (attrs) => {
  1578. [attrs.x, attrs.y] = [attrs.y, attrs.x];
  1579. };
  1580. for (const node of g.nodes.values()) {
  1581. swapXYOne(node.label);
  1582. }
  1583. for (const e of g.edges.values()) {
  1584. const edge = e.label;
  1585. for (const e of edge.points) {
  1586. swapXYOne(e);
  1587. }
  1588. if (edge.x !== undefined) {
  1589. swapXYOne(edge);
  1590. }
  1591. }
  1592. coordinateSystem_swapWidthHeight(g);
  1593. }
  1594. };
  1595. const position = (g, state, layout) => {
  1596. const addConflict = (conflicts, v, w) => {
  1597. if (v > w) {
  1598. [v, w] = [w, v];
  1599. }
  1600. let conflictsV = conflicts.get(v);
  1601. if (!conflictsV) {
  1602. conflictsV = new Set();
  1603. conflicts.set(v, conflictsV);
  1604. }
  1605. conflictsV.add(w);
  1606. };
  1607. const hasConflict = (conflicts, v, w) => {
  1608. if (v > w) {
  1609. [v, w] = [w, v];
  1610. }
  1611. return conflicts.has(v) && conflicts.get(v).has(w);
  1612. };
  1613. const buildBlockGraph = (g, layout, layering, root, reverseSep) => {
  1614. const nodeSep = layout.nodesep;
  1615. const edgeSep = layout.edgesep;
  1616. const blockGraph = new dagre.Graph(true, false);
  1617. for (const layer of layering) {
  1618. let u = null;
  1619. for (const v of layer) {
  1620. const vRoot = root.get(v);
  1621. blockGraph.setNode(vRoot, {});
  1622. if (u) {
  1623. const uRoot = root.get(u);
  1624. const vLabel = g.node(v).label;
  1625. const wLabel = g.node(u).label;
  1626. let sum = 0;
  1627. let delta = 0;
  1628. sum += vLabel.width / 2;
  1629. if ('labelpos' in vLabel) {
  1630. switch (vLabel.labelpos) {
  1631. case 'l': delta = -vLabel.width / 2; break;
  1632. case 'r': delta = vLabel.width / 2; break;
  1633. default: throw new dagre.Error(`Unsupported label position '${vLabel.labelpos}'.`);
  1634. }
  1635. }
  1636. if (delta) {
  1637. sum += reverseSep ? delta : -delta;
  1638. }
  1639. delta = 0;
  1640. sum += (vLabel.dummy ? edgeSep : nodeSep) / 2;
  1641. sum += (wLabel.dummy ? edgeSep : nodeSep) / 2;
  1642. sum += wLabel.width / 2;
  1643. if ('labelpos' in wLabel) {
  1644. switch (wLabel.labelpos) {
  1645. case 'l': delta = wLabel.width / 2; break;
  1646. case 'r': delta = -wLabel.width / 2; break;
  1647. default: throw new dagre.Error(`Unsupported label position '${wLabel.labelpos}'.`);
  1648. }
  1649. }
  1650. if (delta) {
  1651. sum += reverseSep ? delta : -delta;
  1652. }
  1653. const edge = blockGraph.edge(uRoot, vRoot);
  1654. const max = Math.max(sum, edge ? edge.label : 0);
  1655. if (edge) {
  1656. edge.label = max;
  1657. } else {
  1658. blockGraph.setEdge(uRoot, vRoot, max);
  1659. }
  1660. }
  1661. u = v;
  1662. }
  1663. }
  1664. return blockGraph;
  1665. };
  1666. // Try to align nodes into vertical 'blocks' where possible.
  1667. // This algorithm attempts to align a node with one of its median neighbors.
  1668. // If the edge connecting a neighbor is a type-1 conflict then we ignore that possibility.
  1669. // If a previous node has already formed a block with a node after the node we're trying to form a block with,
  1670. // we also ignore that possibility - our blocks would be split in that scenario.
  1671. const verticalAlignment = (layering, conflicts, neighborFn) => {
  1672. const root = new Map();
  1673. const align = new Map();
  1674. const pos = new Map();
  1675. // We cache the position here based on the layering because the graph and layering may be out of sync.
  1676. // The layering matrix is manipulated to generate different extreme alignments.
  1677. for (const layer of layering) {
  1678. let order = 0;
  1679. for (const v of layer) {
  1680. root.set(v, v);
  1681. align.set(v, v);
  1682. pos.set(v, order);
  1683. order++;
  1684. }
  1685. }
  1686. for (const layer of layering) {
  1687. let prevIdx = -1;
  1688. for (const v of layer) {
  1689. let ws = neighborFn(v);
  1690. if (ws.size > 0) {
  1691. ws = Array.from(ws.keys());
  1692. ws = ws.sort((a, b) => pos.get(a) - pos.get(b));
  1693. const mp = (ws.length - 1) / 2.0000001;
  1694. const il = Math.ceil(mp);
  1695. for (let i = Math.floor(mp); i <= il; i++) {
  1696. const w = ws[i];
  1697. if (align.get(v) === v && prevIdx < pos.get(w) && !hasConflict(conflicts, v, w)) {
  1698. const x = root.get(w);
  1699. align.set(w, v);
  1700. align.set(v, x);
  1701. root.set(v, x);
  1702. prevIdx = pos.get(w);
  1703. }
  1704. }
  1705. }
  1706. }
  1707. }
  1708. return { root, align };
  1709. };
  1710. const horizontalCompaction = (g, layout, layering, root, align, reverseSep) => {
  1711. // This portion of the algorithm differs from BK due to a number of problems.
  1712. // Instead of their algorithm we construct a new block graph and do two sweeps.
  1713. const blockG = buildBlockGraph(g, layout, layering, root, reverseSep);
  1714. const borderType = reverseSep ? 'borderLeft' : 'borderRight';
  1715. const xs = new Map();
  1716. // First pass, places blocks with the smallest possible coordinates.
  1717. if (blockG.nodes.size > 0) {
  1718. const stack = Array.from(blockG.nodes.keys());
  1719. const visited = new Set();
  1720. while (stack.length > 0) {
  1721. const v = stack.pop();
  1722. if (visited.has(v)) {
  1723. let max = 0;
  1724. for (const e of blockG.node(v).in) {
  1725. max = Math.max(max, xs.get(e.v) + e.label);
  1726. }
  1727. xs.set(v, max);
  1728. } else {
  1729. visited.add(v);
  1730. stack.push(v);
  1731. stack.push(...blockG.predecessors(v).keys());
  1732. }
  1733. }
  1734. }
  1735. // Second pass, removes unused space by moving blocks to the greatest coordinates without violating separation.
  1736. if (blockG.nodes.size > 0) {
  1737. const stack = Array.from(blockG.nodes.keys());
  1738. const visited = new Set();
  1739. while (stack.length > 0) {
  1740. const v = stack.pop();
  1741. if (visited.has(v)) {
  1742. let min = Number.POSITIVE_INFINITY;
  1743. for (const e of blockG.node(v).out) {
  1744. min = Math.min(min, xs.get(e.w) - e.label);
  1745. }
  1746. const label = g.node(v).label;
  1747. if (label.dummy) {
  1748. continue;
  1749. }
  1750. if (min !== Number.POSITIVE_INFINITY && label.borderType !== borderType) {
  1751. xs.set(v, Math.max(xs.get(v), min));
  1752. }
  1753. } else {
  1754. visited.add(v);
  1755. stack.push(v);
  1756. stack.push(...blockG.successors(v).keys());
  1757. }
  1758. }
  1759. }
  1760. // Assign x coordinates to all nodes
  1761. for (const v of align.values()) {
  1762. xs.set(v, xs.get(root.get(v)));
  1763. }
  1764. return xs;
  1765. };
  1766. // Marks all edges in the graph with a type-1 conflict with the 'type1Conflict' property.
  1767. // A type-1 conflict is one where a non-inner segment crosses an inner segment.
  1768. // An inner segment is an edge with both incident nodes marked with the 'dummy' property.
  1769. //
  1770. // This algorithm scans layer by layer, starting with the second, for type-1
  1771. // conflicts between the current layer and the previous layer. For each layer
  1772. // it scans the nodes from left to right until it reaches one that is incident
  1773. // on an inner segment. It then scans predecessors to determine if they have
  1774. // edges that cross that inner segment. At the end a final scan is done for all
  1775. // nodes on the current rank to see if they cross the last visited inner segment.
  1776. //
  1777. // This algorithm (safely) assumes that a dummy node will only be incident on a
  1778. // single node in the layers being scanned.
  1779. const findType1Conflicts = (g, layering) => {
  1780. const conflicts = new Map();
  1781. if (layering.length > 0) {
  1782. let [prev] = layering;
  1783. for (let k = 1; k < layering.length; k++) {
  1784. const layer = layering[k];
  1785. // last visited node in the previous layer that is incident on an inner segment.
  1786. let k0 = 0;
  1787. // Tracks the last node in this layer scanned for crossings with a type-1 segment.
  1788. let scanPos = 0;
  1789. const prevLayerLength = prev.length;
  1790. const lastNode = layer[layer.length - 1];
  1791. for (let i = 0; i < layer.length; i++) {
  1792. const v = layer[i];
  1793. const w = g.node(v).label.dummy ? Array.from(g.predecessors(v).keys()).find((u) => g.node(u).label.dummy) : null;
  1794. if (w || v === lastNode) {
  1795. const k1 = w ? g.node(w).label.order : prevLayerLength;
  1796. for (const scanNode of layer.slice(scanPos, i + 1)) {
  1797. // for (const scanNode of layer.slice(scanPos, scanPos + 1)) {
  1798. const predecessors = g.predecessors(scanNode);
  1799. if (predecessors.size > 0) {
  1800. for (const u of g.predecessors(scanNode).keys()) {
  1801. const uLabel = g.node(u).label;
  1802. const uPos = uLabel.order;
  1803. if ((uPos < k0 || k1 < uPos) && !(uLabel.dummy && g.node(scanNode).label.dummy)) {
  1804. addConflict(conflicts, u, scanNode);
  1805. }
  1806. }
  1807. }
  1808. }
  1809. // scanPos += 1;
  1810. scanPos = i + 1;
  1811. k0 = k1;
  1812. }
  1813. }
  1814. prev = layer;
  1815. }
  1816. }
  1817. return conflicts;
  1818. };
  1819. const findType2Conflicts = (g, layering) => {
  1820. const conflicts = new Map();
  1821. const scan = (south, southPos, southEnd, prevNorthBorder, nextNorthBorder) => {
  1822. for (let i = southPos; i < southEnd; i++) {
  1823. const v = south[i];
  1824. if (g.node(v).labeldummy) {
  1825. for (const u of g.predecessors(v).keys()) {
  1826. const uNode = g.node(u).label;
  1827. if (uNode.dummy && (uNode.order < prevNorthBorder || uNode.order > nextNorthBorder)) {
  1828. addConflict(conflicts, u, v);
  1829. }
  1830. }
  1831. }
  1832. }
  1833. };
  1834. if (layering.length > 0) {
  1835. /* eslint-disable no-loop-func */
  1836. let [north] = layering;
  1837. for (let i = 1; i < layering.length; i++) {
  1838. const south = layering[i];
  1839. let prevNorthPos = -1;
  1840. let nextNorthPos = 0;
  1841. let southPos = 0;
  1842. south.forEach((v, southLookahead) => {
  1843. if (g.node(v).label.dummy === 'border') {
  1844. const predecessors = g.predecessors(v);
  1845. if (predecessors.size > 0) {
  1846. nextNorthPos = g.node(predecessors.keys().next().value).label.order;
  1847. scan(south, southPos, southLookahead, prevNorthPos, nextNorthPos);
  1848. southPos = southLookahead;
  1849. prevNorthPos = nextNorthPos;
  1850. }
  1851. }
  1852. scan(south, southPos, south.length, nextNorthPos, north.length);
  1853. });
  1854. north = south;
  1855. }
  1856. /* eslint-enable no-loop-func */
  1857. }
  1858. return conflicts;
  1859. };
  1860. g = asNonCompoundGraph(g);
  1861. const layering = buildLayerMatrix(g);
  1862. const ranksep = layout.ranksep;
  1863. // Assign y-coordinate based on rank
  1864. let y = 0;
  1865. for (const layer of layering) {
  1866. const maxHeight = layer.reduce((a, v) => Math.max(a, g.node(v).label.height), 0);
  1867. for (const v of layer) {
  1868. g.node(v).label.y = y + maxHeight / 2;
  1869. }
  1870. y += maxHeight + ranksep;
  1871. }
  1872. // Coordinate assignment based on Brandes and Köpf, 'Fast and Simple Horizontal Coordinate Assignment.'
  1873. const conflicts = new Map([...findType1Conflicts(g, layering).entries(), ...findType2Conflicts(g, layering).entries()]);
  1874. const xss = {};
  1875. for (const vertical of ['u', 'd']) {
  1876. let adjustedLayering = vertical === 'u' ? layering : Object.values(layering).reverse();
  1877. for (const horizontal of ['l', 'r']) {
  1878. if (horizontal === 'r') {
  1879. adjustedLayering = adjustedLayering.map((layer) => Object.values(layer).reverse());
  1880. }
  1881. const neighborFn = (vertical === 'u' ? g.predecessors : g.successors).bind(g);
  1882. const align = verticalAlignment(adjustedLayering, conflicts, neighborFn);
  1883. const xs = horizontalCompaction(g, layout, adjustedLayering, align.root, align.align, horizontal === 'r');
  1884. if (horizontal === 'r') {
  1885. for (const [key, value] of xs.entries(xs)) {
  1886. xs.set(key, -value);
  1887. }
  1888. }
  1889. xss[vertical + horizontal] = xs;
  1890. }
  1891. }
  1892. // Find smallest width alignment: Returns the alignment that has the smallest width of the given alignments.
  1893. let minWidth = Number.POSITIVE_INFINITY;
  1894. let minValue = null;
  1895. for (const xs of Object.values(xss)) {
  1896. let max = Number.NEGATIVE_INFINITY;
  1897. let min = Number.POSITIVE_INFINITY;
  1898. for (const [v, x] of xs.entries()) {
  1899. const halfWidth = g.node(v).label.width / 2;
  1900. max = Math.max(x + halfWidth, max);
  1901. min = Math.min(x - halfWidth, min);
  1902. }
  1903. const width = max - min;
  1904. if (width < minWidth) {
  1905. minWidth = width;
  1906. minValue = xs;
  1907. }
  1908. }
  1909. // Align the coordinates of each of the layout alignments such that
  1910. // left-biased alignments have their minimum coordinate at the same point as
  1911. // the minimum coordinate of the smallest width alignment and right-biased
  1912. // alignments have their maximum coordinate at the same point as the maximum
  1913. // coordinate of the smallest width alignment.
  1914. const alignTo = minValue;
  1915. const range = (values) => {
  1916. let min = Number.POSITIVE_INFINITY;
  1917. let max = Number.NEGATIVE_INFINITY;
  1918. for (const value of values) {
  1919. if (value < min) {
  1920. min = value;
  1921. }
  1922. if (value > max) {
  1923. max = value;
  1924. }
  1925. }
  1926. return [min, max];
  1927. };
  1928. const alignToRange = range(alignTo.values(alignTo));
  1929. for (const vertical of ['u', 'd']) {
  1930. for (const horizontal of ['l', 'r']) {
  1931. const alignment = vertical + horizontal;
  1932. const xs = xss[alignment];
  1933. if (xs !== alignTo) {
  1934. const vsValsRange = range(xs.values());
  1935. const delta = horizontal === 'l' ? alignToRange[0] - vsValsRange[0] : alignToRange[1] - vsValsRange[1];
  1936. if (delta) {
  1937. const list = new Map();
  1938. for (const [key, value] of xs.entries()) {
  1939. list.set(key, value + delta);
  1940. }
  1941. xss[alignment] = list;
  1942. }
  1943. }
  1944. }
  1945. }
  1946. // balance
  1947. const align = layout.align;
  1948. if (align) {
  1949. const xs = xss[align.toLowerCase()];
  1950. for (const v of xss.ul.keys()) {
  1951. g.node(v).label.x = xs.get(v);
  1952. }
  1953. } else {
  1954. for (const v of xss.ul.keys()) {
  1955. const xs = [xss.ul.get(v), xss.ur.get(v), xss.dl.get(v), xss.dr.get(v)].sort((a, b) => a - b);
  1956. g.node(v).label.x = (xs[1] + xs[2]) / 2;
  1957. }
  1958. }
  1959. };
  1960. const positionSelfEdges = (g) => {
  1961. for (const node of g.nodes.values()) {
  1962. const label = node.label;
  1963. if (label.dummy === 'selfedge') {
  1964. const v = node.v;
  1965. const selfNode = g.node(label.e.v).label;
  1966. const x = selfNode.x + selfNode.width / 2;
  1967. const y = selfNode.y;
  1968. const dx = label.x - x;
  1969. const dy = selfNode.height / 2;
  1970. g.setEdge(label.e.v, label.e.w, label.label);
  1971. g.removeNode(v);
  1972. label.label.points = [
  1973. { x: x + 2 * dx / 3, y: y - dy },
  1974. { x: x + 5 * dx / 6, y: y - dy },
  1975. { x: x + dx , y },
  1976. { x: x + 5 * dx / 6, y: y + dy },
  1977. { x: x + 2 * dx / 3, y: y + dy }
  1978. ];
  1979. label.label.x = label.x;
  1980. label.label.y = label.y;
  1981. }
  1982. }
  1983. };
  1984. const removeBorderNodes = (g) => {
  1985. for (const node of g.nodes.values()) {
  1986. const v = node.v;
  1987. if (g.hasChildren(v)) {
  1988. const label = node.label;
  1989. const t = g.node(label.borderTop).label;
  1990. const b = g.node(label.borderBottom).label;
  1991. const l = g.node(label.borderLeft[label.borderLeft.length - 1]).label;
  1992. const r = g.node(label.borderRight[label.borderRight.length - 1]).label;
  1993. label.width = Math.abs(r.x - l.x);
  1994. label.height = Math.abs(b.y - t.y);
  1995. label.x = l.x + label.width / 2;
  1996. label.y = t.y + label.height / 2;
  1997. }
  1998. }
  1999. for (const node of g.nodes.values()) {
  2000. if (node.label.dummy === 'border') {
  2001. g.removeNode(node.v);
  2002. }
  2003. }
  2004. };
  2005. const fixupEdgeLabelCoords = (g) => {
  2006. for (const e of g.edges.values()) {
  2007. const edge = e.label;
  2008. if ('x' in edge) {
  2009. if (edge.labelpos === 'l' || edge.labelpos === 'r') {
  2010. edge.width -= edge.labeloffset;
  2011. }
  2012. switch (edge.labelpos) {
  2013. case 'l': edge.x -= edge.width / 2 + edge.labeloffset; break;
  2014. case 'r': edge.x += edge.width / 2 + edge.labeloffset; break;
  2015. default: throw new dagre.Error(`Unsupported label position '${edge.labelpos}'.`);
  2016. }
  2017. }
  2018. }
  2019. };
  2020. const translateGraph = (g, state) => {
  2021. let minX = Number.POSITIVE_INFINITY;
  2022. let maxX = 0;
  2023. let minY = Number.POSITIVE_INFINITY;
  2024. let maxY = 0;
  2025. const getExtremes = (attrs) => {
  2026. const x = attrs.x;
  2027. const y = attrs.y;
  2028. const w = attrs.width;
  2029. const h = attrs.height;
  2030. minX = Math.min(minX, x - w / 2);
  2031. maxX = Math.max(maxX, x + w / 2);
  2032. minY = Math.min(minY, y - h / 2);
  2033. maxY = Math.max(maxY, y + h / 2);
  2034. };
  2035. for (const node of g.nodes.values()) {
  2036. getExtremes(node.label);
  2037. }
  2038. for (const e of g.edges.values()) {
  2039. const edge = e.label;
  2040. if ('x' in edge) {
  2041. getExtremes(edge);
  2042. }
  2043. }
  2044. for (const node of g.nodes.values()) {
  2045. node.label.x -= minX;
  2046. node.label.y -= minY;
  2047. }
  2048. for (const e of g.edges.values()) {
  2049. const edge = e.label;
  2050. for (const p of edge.points) {
  2051. p.x -= minX;
  2052. p.y -= minY;
  2053. }
  2054. if ('x' in edge) {
  2055. edge.x -= minX;
  2056. }
  2057. if ('y' in edge) {
  2058. edge.y -= minY;
  2059. }
  2060. }
  2061. state.width = maxX - minX;
  2062. state.height = maxY - minY;
  2063. };
  2064. const assignNodeIntersects = (g) => {
  2065. // Finds where a line starting at point ({x, y}) would intersect a rectangle
  2066. // ({x, y, width, height}) if it were pointing at the rectangle's center.
  2067. const intersectRect = (rect, point) => {
  2068. const x = rect.x;
  2069. const y = rect.y;
  2070. // Rectangle intersection algorithm from: http://math.stackexchange.com/questions/108113/find-edge-between-two-boxes
  2071. const dx = point.x - x;
  2072. const dy = point.y - y;
  2073. if (dx === 0 && dy === 0) {
  2074. throw new Error('Not possible to find intersection inside of the rectangle');
  2075. }
  2076. let w = rect.width / 2;
  2077. let h = rect.height / 2;
  2078. if (Math.abs(dy) * w > Math.abs(dx) * h) {
  2079. // Intersection is top or bottom of rect.
  2080. h = dy < 0 ? -h : h;
  2081. return { x: x + (h * dx / dy), y: y + h };
  2082. }
  2083. // Intersection is left or right of rect.
  2084. w = dx < 0 ? -w : w;
  2085. return { x: x + w, y: y + (w * dy / dx) };
  2086. };
  2087. for (const e of g.edges.values()) {
  2088. const edge = e.label;
  2089. const vNode = e.vNode.label;
  2090. const wNode = e.wNode.label;
  2091. let p1 = null;
  2092. let p2 = null;
  2093. if (edge.points) {
  2094. [p1] = edge.points;
  2095. p2 = edge.points[edge.points.length - 1];
  2096. } else {
  2097. edge.points = [];
  2098. p1 = wNode;
  2099. p2 = vNode;
  2100. }
  2101. edge.points.unshift(intersectRect(vNode, p1));
  2102. edge.points.push(intersectRect(wNode, p2));
  2103. }
  2104. };
  2105. // Build layout graph
  2106. const g = new dagre.Graph(true, true);
  2107. for (const node of nodes) {
  2108. g.setNode(node.v, {
  2109. width: node.width,
  2110. height: node.height
  2111. });
  2112. if (node.parent) {
  2113. g.setParent(node.v, node.parent);
  2114. }
  2115. }
  2116. for (const edge of edges) {
  2117. g.setEdge(edge.v, edge.w, {
  2118. minlen: edge.minlen || 1,
  2119. weight: edge.weight || 1,
  2120. width: edge.width || 0,
  2121. height: edge.height || 0,
  2122. labeloffset: edge.labeloffset || 10,
  2123. labelpos: edge.labelpos || 'r'
  2124. });
  2125. }
  2126. // Run layout
  2127. layout = { ranksep: 50, edgesep: 20, nodesep: 50, rankdir: 'tb', ...layout };
  2128. const tasks = [
  2129. makeSpaceForEdgeLabels,
  2130. removeSelfEdges,
  2131. acyclic_run,
  2132. nestingGraph_run,
  2133. rank,
  2134. injectEdgeLabelProxies,
  2135. removeEmptyRanks,
  2136. nestingGraph_cleanup,
  2137. assignRankMinMax,
  2138. removeEdgeLabelProxies,
  2139. normalize,
  2140. parentDummyChains,
  2141. addBorderSegments,
  2142. order,
  2143. insertSelfEdges,
  2144. coordinateSystem_adjust,
  2145. position,
  2146. positionSelfEdges,
  2147. removeBorderNodes,
  2148. denormalize,
  2149. fixupEdgeLabelCoords,
  2150. coordinateSystem_undo,
  2151. translateGraph,
  2152. assignNodeIntersects,
  2153. acyclic_undo
  2154. ];
  2155. while (tasks.length > 0) {
  2156. // const start = Date.now();
  2157. const task = tasks.shift();
  2158. task(g, state, layout);
  2159. // const duration = Date.now() - start;
  2160. // console.log(`${task.name}: ${duration}ms`);
  2161. }
  2162. // Update source graph
  2163. for (const node of nodes) {
  2164. const label = g.node(node.v).label;
  2165. node.x = label.x;
  2166. node.y = label.y;
  2167. if (g.hasChildren(node.v)) {
  2168. node.width = label.width;
  2169. node.height = label.height;
  2170. }
  2171. }
  2172. for (const edge of edges) {
  2173. const label = g.edge(edge.v, edge.w).label;
  2174. edge.points = label.points;
  2175. if ('x' in label) {
  2176. edge.x = label.x;
  2177. edge.y = label.y;
  2178. }
  2179. }
  2180. if (state.log) {
  2181. state.log = g.toString();
  2182. }
  2183. };
  2184. dagre.Graph = class {
  2185. constructor(directed, compound) {
  2186. this.directed = directed;
  2187. this.compound = compound;
  2188. this._defaultNodeLabelFn = () => {
  2189. return undefined;
  2190. };
  2191. this.nodes = new Map();
  2192. this.edges = new Map();
  2193. if (this.compound) {
  2194. this._parent = new Map();
  2195. this._children = new Map();
  2196. this._children.set('\x00', new Map());
  2197. }
  2198. }
  2199. setDefaultNodeLabel(newDefault) {
  2200. this._defaultNodeLabelFn = newDefault;
  2201. }
  2202. setNode(v, label) {
  2203. const node = this.nodes.get(v);
  2204. if (node) {
  2205. if (label) {
  2206. node.label = label;
  2207. }
  2208. } else {
  2209. const node = { label: label ? label : this._defaultNodeLabelFn(v), in: [], out: [], predecessors: new Map(), successors: new Map(), v };
  2210. this.nodes.set(v, node);
  2211. if (this.compound) {
  2212. this._parent.set(v, '\x00');
  2213. this._children.set(v, new Map());
  2214. this._children.get('\x00').set(v, true);
  2215. }
  2216. }
  2217. }
  2218. node(v) {
  2219. return this.nodes.get(v);
  2220. }
  2221. hasNode(v) {
  2222. return this.nodes.has(v);
  2223. }
  2224. removeNode(v) {
  2225. const node = this.nodes.get(v);
  2226. if (node) {
  2227. if (this.compound) {
  2228. this._children.get(this._parent.get(v)).delete(v);
  2229. this._parent.delete(v);
  2230. for (const child of this.children(v)) {
  2231. this.setParent(child);
  2232. }
  2233. this._children.delete(v);
  2234. }
  2235. for (const edge of node.in.concat()) {
  2236. this.removeEdge(edge);
  2237. }
  2238. for (const edge of node.out.concat()) {
  2239. this.removeEdge(edge);
  2240. }
  2241. this.nodes.delete(v);
  2242. }
  2243. }
  2244. setParent(v, parent) {
  2245. if (!this.compound) {
  2246. throw new Error('Cannot set parent in a non-compound graph');
  2247. }
  2248. if (parent) {
  2249. for (let ancestor = parent; ancestor !== undefined; ancestor = this.parent(ancestor)) {
  2250. if (ancestor === v) {
  2251. throw new Error(`Setting ${parent} as parent of ${v} would create a cycle.`);
  2252. }
  2253. }
  2254. this.setNode(parent);
  2255. } else {
  2256. parent = '\x00';
  2257. }
  2258. this._children.get(this._parent.get(v)).delete(v);
  2259. this._parent.set(v, parent);
  2260. this._children.get(parent).set(v, true);
  2261. }
  2262. parent(v) {
  2263. if (this.compound) {
  2264. const parent = this._parent.get(v);
  2265. if (parent !== '\x00') {
  2266. return parent;
  2267. }
  2268. }
  2269. return null;
  2270. }
  2271. children(v) {
  2272. if (this.compound) {
  2273. return this._children.get(v === undefined ? '\x00' : v).keys();
  2274. } else if (v === undefined) {
  2275. return this.nodes.keys();
  2276. } else if (this.hasNode(v)) {
  2277. return [];
  2278. }
  2279. return null;
  2280. }
  2281. hasChildren(v) {
  2282. if (this.compound) {
  2283. return this._children.get(v === undefined ? '\x00' : v).size > 0;
  2284. } else if (v === undefined) {
  2285. return this.nodes.size > 0;
  2286. }
  2287. return false;
  2288. }
  2289. predecessors(v) {
  2290. return this.nodes.get(v).predecessors;
  2291. }
  2292. successors(v) {
  2293. return this.nodes.get(v).successors;
  2294. }
  2295. neighbors(v) {
  2296. const n = this.nodes.get(v);
  2297. const p = n.predecessors.keys();
  2298. const s = n.successors.keys();
  2299. const set = new Set();
  2300. for (const k of p) {
  2301. set.add(k);
  2302. }
  2303. for (const k of s) {
  2304. set.add(k);
  2305. }
  2306. return set;
  2307. }
  2308. edge(v, w) {
  2309. return this.edges.get(this._edgeKey(this.directed, v, w));
  2310. }
  2311. setEdge(v, w, label, name) {
  2312. const key = this._edgeKey(this.directed, v, w, name);
  2313. const edge = this.edges.get(key);
  2314. if (edge) {
  2315. edge.label = label;
  2316. } else {
  2317. if (!this.directed && v > w) {
  2318. [v, w] = [w, v];
  2319. }
  2320. const edge = { label, v, w, name, key, vNode: null, wNode: null };
  2321. this.edges.set(key, edge);
  2322. this.setNode(v);
  2323. this.setNode(w);
  2324. const wNode = this.nodes.get(w);
  2325. const vNode = this.nodes.get(v);
  2326. edge.wNode = wNode;
  2327. edge.vNode = vNode;
  2328. const incrementOrInitEntry = (map, k) => {
  2329. map.set(k, (map.get(k) ?? 0) + 1);
  2330. };
  2331. incrementOrInitEntry(wNode.predecessors, v);
  2332. incrementOrInitEntry(vNode.successors, w);
  2333. wNode.in.push(edge);
  2334. vNode.out.push(edge);
  2335. }
  2336. }
  2337. removeEdge(edge) {
  2338. const key = edge.key;
  2339. const v = edge.v;
  2340. const w = edge.w;
  2341. const wNode = edge.wNode;
  2342. const vNode = edge.vNode;
  2343. if (wNode.predecessors.has(v)) {
  2344. const value = wNode.predecessors.get(v);
  2345. if (value === 1) {
  2346. wNode.predecessors.delete(v);
  2347. } else {
  2348. wNode.predecessors.set(v, value - 1);
  2349. }
  2350. }
  2351. if (vNode.successors.has(w)) {
  2352. const value = vNode.successors.get(w);
  2353. if (value === 1) {
  2354. vNode.successors.delete(w);
  2355. } else {
  2356. vNode.successors.set(w, value - 1);
  2357. }
  2358. }
  2359. // Update arrays in-place
  2360. const idxIn = wNode.in.findIndex((e) => e.key === key);
  2361. if (idxIn !== -1) {
  2362. wNode.in.splice(idxIn, 1);
  2363. }
  2364. const idxOut = vNode.out.findIndex((e) => e.key === key);
  2365. if (idxOut !== -1) {
  2366. vNode.out.splice(idxOut, 1);
  2367. }
  2368. this.edges.delete(key);
  2369. }
  2370. _edgeKey(isDirected, v, w, name) {
  2371. if (!isDirected && v > w) {
  2372. return name ? `${w}:${v}:${name}` : `${w}:${v}:`;
  2373. }
  2374. return name ? `${v}:${w}:${name}` : `${v}:${w}:`;
  2375. }
  2376. toString() {
  2377. return [
  2378. '[nodes]', Array.from(this.nodes.values()).map((n) => JSON.stringify(n.label)).join('\n'),
  2379. '[edges]', Array.from(this.edges.values()).map((e) => JSON.stringify(e.label)).join('\n'),
  2380. '[parents]', JSON.stringify(this._parent, null, 2),
  2381. '[children]', JSON.stringify(this._children, null, 2)
  2382. ].join('\n');
  2383. }
  2384. };
  2385. export const { layout, Graph } = dagre;