2
0

dagre.js 100 KB

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