vis.js is a dynamic, browser-based visualization library
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1708 lines
54 KiB

9 years ago
9 years ago
9 years ago
  1. 'use strict';
  2. /**
  3. * There's a mix-up with terms in the code. Following are the formal definitions:
  4. *
  5. * tree - a strict hierarchical network, i.e. every node has at most one parent
  6. * forest - a collection of trees. These distinct trees are thus not connected.
  7. *
  8. * So:
  9. * - in a network that is not a tree, there exist nodes with multiple parents.
  10. * - a network consisting of unconnected sub-networks, of which at least one
  11. * is not a tree, is not a forest.
  12. *
  13. * In the code, the definitions are:
  14. *
  15. * tree - any disconnected sub-network, strict hierarchical or not.
  16. * forest - a bunch of these sub-networks
  17. *
  18. * The difference between tree and not-tree is important in the code, notably within
  19. * to the block-shifting algorithm. The algorithm assumes formal trees and fails
  20. * for not-trees, often in a spectacular manner (search for 'exploding network' in the issues).
  21. *
  22. * In order to distinguish the definitions in the following code, the adjective 'formal' is
  23. * used. If 'formal' is absent, you must assume the non-formal definition.
  24. *
  25. * ----------------------------------------------------------------------------------
  26. * NOTES
  27. * =====
  28. *
  29. * A hierarchical layout is a different thing from a hierarchical network.
  30. * The layout is a way to arrange the nodes in the view; this can be done
  31. * on non-hierarchical networks as well. The converse is also possible.
  32. */
  33. let util = require('../../util');
  34. var NetworkUtil = require('../NetworkUtil').default;
  35. /**
  36. * Container for derived data on current network, relating to hierarchy.
  37. *
  38. * Local, private class.
  39. */
  40. class HierarchicalStatus {
  41. constructor() {
  42. this.childrenReference = {}; // child id's per node id
  43. this.parentReference = {}; // parent id's per node id
  44. this.trees = {}; // tree id per node id; i.e. to which tree does given node id belong
  45. this.distributionOrdering = {}; // The nodes per level, in the display order
  46. this.levels = {}; // hierarchy level per node id
  47. this.distributionIndex = {}; // The position of the node in the level sorting order, per node id.
  48. this.isTree = false; // True if current network is a formal tree
  49. this.treeIndex = -1; // Highest tree id in current network.
  50. }
  51. /**
  52. * Add the relation between given nodes to the current state.
  53. */
  54. addRelation(parentNodeId, childNodeId) {
  55. if (this.childrenReference[parentNodeId] === undefined) {
  56. this.childrenReference[parentNodeId] = [];
  57. }
  58. this.childrenReference[parentNodeId].push(childNodeId);
  59. if (this.parentReference[childNodeId] === undefined) {
  60. this.parentReference[childNodeId] = [];
  61. }
  62. this.parentReference[childNodeId].push(parentNodeId);
  63. }
  64. /**
  65. * Check if the current state is for a formal tree or formal forest.
  66. *
  67. * This is the case if every node has at most one parent.
  68. *
  69. * Pre: parentReference init'ed properly for current network
  70. */
  71. checkIfTree() {
  72. for (let i in this.parentReference) {
  73. if (this.parentReference[i].length > 1) {
  74. this.isTree = false;
  75. return;
  76. }
  77. }
  78. this.isTree = true;
  79. }
  80. /**
  81. * Return the number of separate trees in the current network.
  82. */
  83. numTrees() {
  84. return (this.treeIndex + 1); // This assumes the indexes are assigned consecitively
  85. }
  86. /**
  87. * Assign a tree id to a node
  88. */
  89. setTreeIndex(node, treeId) {
  90. if (this.trees[node.id] === undefined) {
  91. this.trees[node.id] = treeId;
  92. this.treeIndex = Math.max(treeId, this.treeIndex);
  93. }
  94. }
  95. /**
  96. * Ensure level for given id is defined.
  97. *
  98. * Sets level to zero for given node id if not already present
  99. */
  100. ensureLevel(nodeId) {
  101. if (this.levels[nodeId] === undefined) {
  102. this.levels[nodeId] = 0;
  103. }
  104. }
  105. /**
  106. * get the maximum level of a branch.
  107. *
  108. * TODO: Never entered; find a test case to test this!
  109. */
  110. getMaxLevel(nodeId) {
  111. let accumulator = {};
  112. let _getMaxLevel = (nodeId) => {
  113. if (accumulator[nodeId] !== undefined) {
  114. return accumulator[nodeId];
  115. }
  116. let level = this.levels[nodeId];
  117. if (this.childrenReference[nodeId]) {
  118. let children = this.childrenReference[nodeId];
  119. if (children.length > 0) {
  120. for (let i = 0; i < children.length; i++) {
  121. level = Math.max(level,_getMaxLevel(children[i]));
  122. }
  123. }
  124. }
  125. accumulator[nodeId] = level;
  126. return level;
  127. };
  128. return _getMaxLevel(nodeId);
  129. }
  130. levelDownstream(nodeA, nodeB) {
  131. if (this.levels[nodeB.id] === undefined) {
  132. // set initial level
  133. if (this.levels[nodeA.id] === undefined) {
  134. this.levels[nodeA.id] = 0;
  135. }
  136. // set level
  137. this.levels[nodeB.id] = this.levels[nodeA.id] + 1;
  138. }
  139. }
  140. /**
  141. * Small util method to set the minimum levels of the nodes to zero.
  142. */
  143. setMinLevelToZero(nodes) {
  144. let minLevel = 1e9;
  145. // get the minimum level
  146. for (let nodeId in nodes) {
  147. if (nodes.hasOwnProperty(nodeId)) {
  148. if (this.levels[nodeId] !== undefined) {
  149. minLevel = Math.min(this.levels[nodeId], minLevel);
  150. }
  151. }
  152. }
  153. // subtract the minimum from the set so we have a range starting from 0
  154. for (let nodeId in nodes) {
  155. if (nodes.hasOwnProperty(nodeId)) {
  156. if (this.levels[nodeId] !== undefined) {
  157. this.levels[nodeId] -= minLevel;
  158. }
  159. }
  160. }
  161. }
  162. /**
  163. * Get the min and max xy-coordinates of a given tree
  164. */
  165. getTreeSize(nodes, index) {
  166. let min_x = 1e9;
  167. let max_x = -1e9;
  168. let min_y = 1e9;
  169. let max_y = -1e9;
  170. for (let nodeId in this.trees) {
  171. if (this.trees.hasOwnProperty(nodeId)) {
  172. if (this.trees[nodeId] === index) {
  173. let node = nodes[nodeId];
  174. min_x = Math.min(node.x, min_x);
  175. max_x = Math.max(node.x, max_x);
  176. min_y = Math.min(node.y, min_y);
  177. max_y = Math.max(node.y, max_y);
  178. }
  179. }
  180. }
  181. return {
  182. min_x: min_x,
  183. max_x: max_x,
  184. min_y: min_y,
  185. max_y: max_y
  186. };
  187. }
  188. /**
  189. * Check if two nodes have the same parent(s)
  190. *
  191. * @return true if the two nodes have a same ancestor node, false otherwise
  192. */
  193. hasSameParent(node1, node2) {
  194. let parents1 = this.parentReference[node1.id];
  195. let parents2 = this.parentReference[node2.id];
  196. if (parents1 === undefined || parents2 === undefined) {
  197. return false;
  198. }
  199. for (let i = 0; i < parents1.length; i++) {
  200. for (let j = 0; j < parents2.length; j++) {
  201. if (parents1[i] == parents2[j]) {
  202. return true;
  203. }
  204. }
  205. }
  206. return false;
  207. }
  208. /**
  209. * Check if two nodes are in the same tree.
  210. *
  211. * @return true if this is so, false otherwise
  212. */
  213. inSameSubNetwork(node1, node2) {
  214. return (this.trees[node1.id] === this.trees[node2.id]);
  215. }
  216. /**
  217. * Get a list of the distinct levels in the current network
  218. */
  219. getLevels() {
  220. return Object.keys(this.distributionOrdering);
  221. }
  222. /**
  223. * Add a node to the ordering per level
  224. */
  225. addToOrdering(node, level) {
  226. if (this.distributionOrdering[level] === undefined) {
  227. this.distributionOrdering[level] = [];
  228. }
  229. var isPresent = false;
  230. var curLevel = this.distributionOrdering[level];
  231. for (var n in curLevel) {
  232. //if (curLevel[n].id === node.id) {
  233. if (curLevel[n] === node) {
  234. isPresent = true;
  235. break;
  236. }
  237. }
  238. if (!isPresent) {
  239. this.distributionOrdering[level].push(node);
  240. this.distributionIndex[node.id] = this.distributionOrdering[level].length - 1;
  241. }
  242. }
  243. }
  244. class LayoutEngine {
  245. constructor(body) {
  246. this.body = body;
  247. this.initialRandomSeed = Math.round(Math.random() * 1000000);
  248. this.randomSeed = this.initialRandomSeed;
  249. this.setPhysics = false;
  250. this.options = {};
  251. this.optionsBackup = {physics:{}};
  252. this.defaultOptions = {
  253. randomSeed: undefined,
  254. improvedLayout: true,
  255. hierarchical: {
  256. enabled:false,
  257. levelSeparation: 150,
  258. nodeSpacing: 100,
  259. treeSpacing: 200,
  260. blockShifting: true,
  261. edgeMinimization: true,
  262. parentCentralization: true,
  263. direction: 'UD', // UD, DU, LR, RL
  264. sortMethod: 'hubsize' // hubsize, directed
  265. }
  266. };
  267. util.extend(this.options, this.defaultOptions);
  268. this.bindEventListeners();
  269. }
  270. bindEventListeners() {
  271. this.body.emitter.on('_dataChanged', () => {
  272. this.setupHierarchicalLayout();
  273. });
  274. this.body.emitter.on('_dataLoaded', () => {
  275. this.layoutNetwork();
  276. });
  277. this.body.emitter.on('_resetHierarchicalLayout', () => {
  278. this.setupHierarchicalLayout();
  279. });
  280. this.body.emitter.on('_adjustEdgesForHierarchicalLayout', () => {
  281. if (this.options.hierarchical.enabled !== true) {
  282. return;
  283. }
  284. // get the type of static smooth curve in case it is required
  285. let type = this.getStaticType();
  286. // force all edges into static smooth curves.
  287. this.body.emitter.emit('_forceDisableDynamicCurves', type, false);
  288. });
  289. }
  290. setOptions(options, allOptions) {
  291. if (options !== undefined) {
  292. let hierarchical = this.options.hierarchical;
  293. let prevHierarchicalState = hierarchical.enabled;
  294. util.selectiveDeepExtend(["randomSeed", "improvedLayout"],this.options, options);
  295. util.mergeOptions(this.options, options, 'hierarchical');
  296. if (options.randomSeed !== undefined) {this.initialRandomSeed = options.randomSeed;}
  297. if (hierarchical.enabled === true) {
  298. if (prevHierarchicalState === true) {
  299. // refresh the overridden options for nodes and edges.
  300. this.body.emitter.emit('refresh', true);
  301. }
  302. // make sure the level separation is the right way up
  303. if (hierarchical.direction === 'RL' || hierarchical.direction === 'DU') {
  304. if (hierarchical.levelSeparation > 0) {
  305. hierarchical.levelSeparation *= -1;
  306. }
  307. }
  308. else {
  309. if (hierarchical.levelSeparation < 0) {
  310. hierarchical.levelSeparation *= -1;
  311. }
  312. }
  313. this.body.emitter.emit('_resetHierarchicalLayout');
  314. // because the hierarchical system needs it's own physics and smooth curve settings,
  315. // we adapt the other options if needed.
  316. return this.adaptAllOptionsForHierarchicalLayout(allOptions);
  317. }
  318. else {
  319. if (prevHierarchicalState === true) {
  320. // refresh the overridden options for nodes and edges.
  321. this.body.emitter.emit('refresh');
  322. return util.deepExtend(allOptions,this.optionsBackup);
  323. }
  324. }
  325. }
  326. return allOptions;
  327. }
  328. adaptAllOptionsForHierarchicalLayout(allOptions) {
  329. if (this.options.hierarchical.enabled === true) {
  330. let backupPhysics = this.optionsBackup.physics;
  331. // set the physics
  332. if (allOptions.physics === undefined || allOptions.physics === true) {
  333. allOptions.physics = {
  334. enabled: backupPhysics.enabled === undefined ? true : backupPhysics.enabled,
  335. solver :'hierarchicalRepulsion'
  336. };
  337. backupPhysics.enabled = backupPhysics.enabled === undefined ? true : backupPhysics.enabled;
  338. backupPhysics.solver = backupPhysics.solver || 'barnesHut';
  339. }
  340. else if (typeof allOptions.physics === 'object') {
  341. backupPhysics.enabled = allOptions.physics.enabled === undefined ? true : allOptions.physics.enabled;
  342. backupPhysics.solver = allOptions.physics.solver || 'barnesHut';
  343. allOptions.physics.solver = 'hierarchicalRepulsion';
  344. }
  345. else if (allOptions.physics !== false) {
  346. backupPhysics.solver ='barnesHut';
  347. allOptions.physics = {solver:'hierarchicalRepulsion'};
  348. }
  349. // get the type of static smooth curve in case it is required
  350. let type = this.getStaticType();
  351. // disable smooth curves if nothing is defined. If smooth curves have been turned on,
  352. // turn them into static smooth curves.
  353. if (allOptions.edges === undefined) {
  354. this.optionsBackup.edges = {smooth:{enabled:true, type:'dynamic'}};
  355. allOptions.edges = {smooth: false};
  356. }
  357. else if (allOptions.edges.smooth === undefined) {
  358. this.optionsBackup.edges = {smooth:{enabled:true, type:'dynamic'}};
  359. allOptions.edges.smooth = false;
  360. }
  361. else {
  362. if (typeof allOptions.edges.smooth === 'boolean') {
  363. this.optionsBackup.edges = {smooth:allOptions.edges.smooth};
  364. allOptions.edges.smooth = {enabled: allOptions.edges.smooth, type:type}
  365. }
  366. else {
  367. let smooth = allOptions.edges.smooth;
  368. // allow custom types except for dynamic
  369. if (smooth.type !== undefined && smooth.type !== 'dynamic') {
  370. type = smooth.type;
  371. }
  372. // TODO: this is options merging; see if the standard routines can be used here.
  373. this.optionsBackup.edges = {
  374. smooth : smooth.enabled === undefined ? true : smooth.enabled,
  375. type : smooth.type === undefined ? 'dynamic': smooth.type,
  376. roundness : smooth.roundness === undefined ? 0.5 : smooth.roundness,
  377. forceDirection: smooth.forceDirection === undefined ? false : smooth.forceDirection
  378. };
  379. // NOTE: Copying an object to self; this is basically setting defaults for undefined variables
  380. allOptions.edges.smooth = {
  381. enabled : smooth.enabled === undefined ? true : smooth.enabled,
  382. type : type,
  383. roundness : smooth.roundness === undefined ? 0.5 : smooth.roundness,
  384. forceDirection: smooth.forceDirection === undefined ? false: smooth.forceDirection
  385. }
  386. }
  387. }
  388. // Force all edges into static smooth curves.
  389. // Only applies to edges that do not use the global options for smooth.
  390. this.body.emitter.emit('_forceDisableDynamicCurves', type);
  391. }
  392. return allOptions;
  393. }
  394. seededRandom() {
  395. let x = Math.sin(this.randomSeed++) * 10000;
  396. return x - Math.floor(x);
  397. }
  398. positionInitially(nodesArray) {
  399. if (this.options.hierarchical.enabled !== true) {
  400. this.randomSeed = this.initialRandomSeed;
  401. let radius = nodesArray.length + 50;
  402. for (let i = 0; i < nodesArray.length; i++) {
  403. let node = nodesArray[i];
  404. let angle = 2 * Math.PI * this.seededRandom();
  405. if (node.x === undefined) {
  406. node.x = radius * Math.cos(angle);
  407. }
  408. if (node.y === undefined) {
  409. node.y = radius * Math.sin(angle);
  410. }
  411. }
  412. }
  413. }
  414. /**
  415. * Use Kamada Kawai to position nodes. This is quite a heavy algorithm so if there are a lot of nodes we
  416. * cluster them first to reduce the amount.
  417. */
  418. layoutNetwork() {
  419. if (this.options.hierarchical.enabled !== true && this.options.improvedLayout === true) {
  420. let indices = this.body.nodeIndices;
  421. // first check if we should Kamada Kawai to layout. The threshold is if less than half of the visible
  422. // nodes have predefined positions we use this.
  423. let positionDefined = 0;
  424. for (let i = 0; i < indices.length; i++) {
  425. let node = this.body.nodes[indices[i]];
  426. if (node.predefinedPosition === true) {
  427. positionDefined += 1;
  428. }
  429. }
  430. // if less than half of the nodes have a predefined position we continue
  431. if (positionDefined < 0.5 * indices.length) {
  432. let MAX_LEVELS = 10;
  433. let level = 0;
  434. let clusterThreshold = 150;
  435. // Performance enhancement, during clustering edges need only be simple straight lines.
  436. // These options don't propagate outside the clustering phase.
  437. let clusterOptions = {
  438. clusterEdgeProperties:{
  439. smooth: {
  440. enabled: false
  441. }
  442. }
  443. };
  444. // if there are a lot of nodes, we cluster before we run the algorithm.
  445. // NOTE: this part fails to find clusters for large scale-free networks, which should
  446. // be easily clusterable.
  447. // TODO: examine why this is so
  448. if (indices.length > clusterThreshold) {
  449. let startLength = indices.length;
  450. while (indices.length > clusterThreshold && level <= MAX_LEVELS) {
  451. //console.time("clustering")
  452. level += 1;
  453. let before = indices.length;
  454. // if there are many nodes we do a hubsize cluster
  455. if (level % 3 === 0) {
  456. this.body.modules.clustering.clusterBridges(clusterOptions);
  457. }
  458. else {
  459. this.body.modules.clustering.clusterOutliers(clusterOptions);
  460. }
  461. let after = indices.length;
  462. if (before == after && level % 3 !== 0) {
  463. this._declusterAll();
  464. this.body.emitter.emit("_layoutFailed");
  465. console.info("This network could not be positioned by this version of the improved layout algorithm."
  466. + " Please disable improvedLayout for better performance.");
  467. return;
  468. }
  469. //console.timeEnd("clustering")
  470. //console.log(before,level,after);
  471. }
  472. // increase the size of the edges
  473. this.body.modules.kamadaKawai.setOptions({springLength: Math.max(150, 2 * startLength)})
  474. }
  475. if (level > MAX_LEVELS){
  476. console.info("The clustering didn't succeed within the amount of interations allowed,"
  477. + " progressing with partial result.");
  478. }
  479. // position the system for these nodes and edges
  480. this.body.modules.kamadaKawai.solve(indices, this.body.edgeIndices, true);
  481. // shift to center point
  482. this._shiftToCenter();
  483. // perturb the nodes a little bit to force the physics to kick in
  484. let offset = 70;
  485. for (let i = 0; i < indices.length; i++) {
  486. // Only perturb the nodes that aren't fixed
  487. let node = this.body.nodes[indices[i]];
  488. if (node.predefinedPosition === false) {
  489. node.x += (0.5 - this.seededRandom())*offset;
  490. node.y += (0.5 - this.seededRandom())*offset;
  491. }
  492. }
  493. // uncluster all clusters
  494. this._declusterAll();
  495. // reposition all bezier nodes.
  496. this.body.emitter.emit("_repositionBezierNodes");
  497. }
  498. }
  499. }
  500. /**
  501. * Move all the nodes towards to the center so gravitational pull wil not move the nodes away from view
  502. * @private
  503. */
  504. _shiftToCenter() {
  505. let range = NetworkUtil.getRangeCore(this.body.nodes, this.body.nodeIndices);
  506. let center = NetworkUtil.findCenter(range);
  507. for (let i = 0; i < this.body.nodeIndices.length; i++) {
  508. let node = this.body.nodes[this.body.nodeIndices[i]];
  509. node.x -= center.x;
  510. node.y -= center.y;
  511. }
  512. }
  513. _declusterAll() {
  514. let clustersPresent = true;
  515. while (clustersPresent === true) {
  516. clustersPresent = false;
  517. for (let i = 0; i < this.body.nodeIndices.length; i++) {
  518. if (this.body.nodes[this.body.nodeIndices[i]].isCluster === true) {
  519. clustersPresent = true;
  520. this.body.modules.clustering.openCluster(this.body.nodeIndices[i], {}, false);
  521. }
  522. }
  523. if (clustersPresent === true) {
  524. this.body.emitter.emit('_dataChanged');
  525. }
  526. }
  527. }
  528. getSeed() {
  529. return this.initialRandomSeed;
  530. }
  531. /**
  532. * This is the main function to layout the nodes in a hierarchical way.
  533. * It checks if the node details are supplied correctly
  534. *
  535. * @private
  536. */
  537. setupHierarchicalLayout() {
  538. if (this.options.hierarchical.enabled === true && this.body.nodeIndices.length > 0) {
  539. // get the size of the largest hubs and check if the user has defined a level for a node.
  540. let node, nodeId;
  541. let definedLevel = false;
  542. let definedPositions = true;
  543. let undefinedLevel = false;
  544. this.lastNodeOnLevel = {};
  545. this.hierarchical = new HierarchicalStatus();
  546. for (nodeId in this.body.nodes) {
  547. if (this.body.nodes.hasOwnProperty(nodeId)) {
  548. node = this.body.nodes[nodeId];
  549. if (node.options.x === undefined && node.options.y === undefined) {
  550. definedPositions = false;
  551. }
  552. if (node.options.level !== undefined) {
  553. definedLevel = true;
  554. this.hierarchical.levels[nodeId] = node.options.level;
  555. }
  556. else {
  557. undefinedLevel = true;
  558. }
  559. }
  560. }
  561. // if the user defined some levels but not all, alert and run without hierarchical layout
  562. if (undefinedLevel === true && definedLevel === true) {
  563. throw new Error('To use the hierarchical layout, nodes require either no predefined levels'
  564. + ' or levels have to be defined for all nodes.');
  565. }
  566. else {
  567. // define levels if undefined by the users. Based on hubsize.
  568. if (undefinedLevel === true) {
  569. let sortMethod = this.options.hierarchical.sortMethod;
  570. if (sortMethod === 'hubsize') {
  571. this._determineLevelsByHubsize();
  572. }
  573. else if (sortMethod === 'directed') {
  574. this._determineLevelsDirected();
  575. }
  576. else if (sortMethod === 'custom') {
  577. this._determineLevelsCustomCallback();
  578. }
  579. }
  580. // fallback for cases where there are nodes but no edges
  581. for (let nodeId in this.body.nodes) {
  582. if (this.body.nodes.hasOwnProperty(nodeId)) {
  583. this.hierarchical.ensureLevel(nodeId);
  584. }
  585. }
  586. // check the distribution of the nodes per level.
  587. let distribution = this._getDistribution();
  588. // get the parent children relations.
  589. this._generateMap();
  590. // place the nodes on the canvas.
  591. this._placeNodesByHierarchy(distribution);
  592. // condense the whitespace.
  593. this._condenseHierarchy();
  594. // shift to center so gravity does not have to do much
  595. this._shiftToCenter();
  596. }
  597. }
  598. }
  599. /**
  600. * @private
  601. */
  602. _condenseHierarchy() {
  603. // Global var in this scope to define when the movement has stopped.
  604. let stillShifting = false;
  605. let branches = {};
  606. // first we have some methods to help shifting trees around.
  607. // the main method to shift the trees
  608. let shiftTrees = () => {
  609. let treeSizes = getTreeSizes();
  610. let shiftBy = 0;
  611. for (let i = 0; i < treeSizes.length - 1; i++) {
  612. let diff = treeSizes[i].max - treeSizes[i+1].min;
  613. shiftBy += diff + this.options.hierarchical.treeSpacing;
  614. shiftTree(i + 1, shiftBy);
  615. }
  616. };
  617. // shift a single tree by an offset
  618. let shiftTree = (index, offset) => {
  619. let trees = this.hierarchical.trees;
  620. for (let nodeId in trees) {
  621. if (trees.hasOwnProperty(nodeId)) {
  622. if (trees[nodeId] === index) {
  623. let node = this.body.nodes[nodeId];
  624. let pos = this._getPositionForHierarchy(node);
  625. this._setPositionForHierarchy(node, pos + offset, undefined, true);
  626. }
  627. }
  628. }
  629. };
  630. // get the width of a tree
  631. let getTreeSize = (index) => {
  632. let res = this.hierarchical.getTreeSize(this.body.nodes, index);
  633. if (this._isVertical()) {
  634. return {min: res.min_x, max: res.max_x};
  635. } else {
  636. return {min: res.min_y, max: res.max_y};
  637. }
  638. };
  639. // get the width of all trees
  640. let getTreeSizes = () => {
  641. let treeWidths = [];
  642. for (let i = 0; i <= this.hierarchical.numTrees(); i++) {
  643. treeWidths.push(getTreeSize(i));
  644. }
  645. return treeWidths;
  646. };
  647. // get a map of all nodes in this branch
  648. let getBranchNodes = (source, map) => {
  649. if (map[source.id]) {
  650. return;
  651. }
  652. map[source.id] = true;
  653. if (this.hierarchical.childrenReference[source.id]) {
  654. let children = this.hierarchical.childrenReference[source.id];
  655. if (children.length > 0) {
  656. for (let i = 0; i < children.length; i++) {
  657. getBranchNodes(this.body.nodes[children[i]], map);
  658. }
  659. }
  660. }
  661. };
  662. // get a min max width as well as the maximum movement space it has on either sides
  663. // we use min max terminology because width and height can interchange depending on the direction of the layout
  664. let getBranchBoundary = (branchMap, maxLevel = 1e9) => {
  665. let minSpace = 1e9;
  666. let maxSpace = 1e9;
  667. let min = 1e9;
  668. let max = -1e9;
  669. for (let branchNode in branchMap) {
  670. if (branchMap.hasOwnProperty(branchNode)) {
  671. let node = this.body.nodes[branchNode];
  672. let level = this.hierarchical.levels[node.id];
  673. let position = this._getPositionForHierarchy(node);
  674. // get the space around the node.
  675. let [minSpaceNode, maxSpaceNode] = this._getSpaceAroundNode(node,branchMap);
  676. minSpace = Math.min(minSpaceNode, minSpace);
  677. maxSpace = Math.min(maxSpaceNode, maxSpace);
  678. // the width is only relevant for the levels two nodes have in common. This is why we filter on this.
  679. if (level <= maxLevel) {
  680. min = Math.min(position, min);
  681. max = Math.max(position, max);
  682. }
  683. }
  684. }
  685. return [min, max, minSpace, maxSpace];
  686. };
  687. // check what the maximum level is these nodes have in common.
  688. let getCollisionLevel = (node1, node2) => {
  689. let maxLevel1 = this.hierarchical.getMaxLevel(node1.id);
  690. let maxLevel2 = this.hierarchical.getMaxLevel(node2.id);
  691. return Math.min(maxLevel1, maxLevel2);
  692. };
  693. /**
  694. * Condense elements. These can be nodes or branches depending on the callback.
  695. */
  696. let shiftElementsCloser = (callback, levels, centerParents) => {
  697. let hier = this.hierarchical;
  698. for (let i = 0; i < levels.length; i++) {
  699. let level = levels[i];
  700. let levelNodes = hier.distributionOrdering[level];
  701. if (levelNodes.length > 1) {
  702. for (let j = 0; j < levelNodes.length - 1; j++) {
  703. let node1 = levelNodes[j];
  704. let node2 = levelNodes[j+1];
  705. // NOTE: logic maintained as it was; if nodes have same ancestor,
  706. // then of course they are in the same sub-network.
  707. if (hier.hasSameParent(node1, node2) && hier.inSameSubNetwork(node1, node2) ) {
  708. callback(node1, node2, centerParents);
  709. }
  710. }
  711. }
  712. }
  713. };
  714. // callback for shifting branches
  715. let branchShiftCallback = (node1, node2, centerParent = false) => {
  716. //window.CALLBACKS.push(() => {
  717. let pos1 = this._getPositionForHierarchy(node1);
  718. let pos2 = this._getPositionForHierarchy(node2);
  719. let diffAbs = Math.abs(pos2 - pos1);
  720. let nodeSpacing = this.options.hierarchical.nodeSpacing;
  721. //console.log("NOW CHECKING:", node1.id, node2.id, diffAbs);
  722. if (diffAbs > nodeSpacing) {
  723. let branchNodes1 = {};
  724. let branchNodes2 = {};
  725. getBranchNodes(node1, branchNodes1);
  726. getBranchNodes(node2, branchNodes2);
  727. // check the largest distance between the branches
  728. let maxLevel = getCollisionLevel(node1, node2);
  729. let [min1,max1, minSpace1, maxSpace1] = getBranchBoundary(branchNodes1, maxLevel);
  730. let [min2,max2, minSpace2, maxSpace2] = getBranchBoundary(branchNodes2, maxLevel);
  731. //console.log(node1.id, getBranchBoundary(branchNodes1, maxLevel), node2.id,
  732. // getBranchBoundary(branchNodes2, maxLevel), maxLevel);
  733. let diffBranch = Math.abs(max1 - min2);
  734. if (diffBranch > nodeSpacing) {
  735. let offset = max1 - min2 + nodeSpacing;
  736. if (offset < -minSpace2 + nodeSpacing) {
  737. offset = -minSpace2 + nodeSpacing;
  738. //console.log("RESETTING OFFSET", max1 - min2 + this.options.hierarchical.nodeSpacing, -minSpace2, offset);
  739. }
  740. if (offset < 0) {
  741. //console.log("SHIFTING", node2.id, offset);
  742. this._shiftBlock(node2.id, offset);
  743. stillShifting = true;
  744. if (centerParent === true)
  745. this._centerParent(node2);
  746. }
  747. }
  748. }
  749. //this.body.emitter.emit("_redraw");})
  750. };
  751. let minimizeEdgeLength = (iterations, node) => {
  752. //window.CALLBACKS.push(() => {
  753. // console.log("ts",node.id);
  754. let nodeId = node.id;
  755. let allEdges = node.edges;
  756. let nodeLevel = this.hierarchical.levels[node.id];
  757. // gather constants
  758. let C2 = this.options.hierarchical.levelSeparation * this.options.hierarchical.levelSeparation;
  759. let referenceNodes = {};
  760. let aboveEdges = [];
  761. for (let i = 0; i < allEdges.length; i++) {
  762. let edge = allEdges[i];
  763. if (edge.toId != edge.fromId) {
  764. let otherNode = edge.toId == nodeId ? edge.from : edge.to;
  765. referenceNodes[allEdges[i].id] = otherNode;
  766. if (this.hierarchical.levels[otherNode.id] < nodeLevel) {
  767. aboveEdges.push(edge);
  768. }
  769. }
  770. }
  771. // differentiated sum of lengths based on only moving one node over one axis
  772. let getFx = (point, edges) => {
  773. let sum = 0;
  774. for (let i = 0; i < edges.length; i++) {
  775. if (referenceNodes[edges[i].id] !== undefined) {
  776. let a = this._getPositionForHierarchy(referenceNodes[edges[i].id]) - point;
  777. sum += a / Math.sqrt(a * a + C2);
  778. }
  779. }
  780. return sum;
  781. };
  782. // doubly differentiated sum of lengths based on only moving one node over one axis
  783. let getDFx = (point, edges) => {
  784. let sum = 0;
  785. for (let i = 0; i < edges.length; i++) {
  786. if (referenceNodes[edges[i].id] !== undefined) {
  787. let a = this._getPositionForHierarchy(referenceNodes[edges[i].id]) - point;
  788. sum -= (C2 * Math.pow(a * a + C2, -1.5));
  789. }
  790. }
  791. return sum;
  792. };
  793. let getGuess = (iterations, edges) => {
  794. let guess = this._getPositionForHierarchy(node);
  795. // Newton's method for optimization
  796. let guessMap = {};
  797. for (let i = 0; i < iterations; i++) {
  798. let fx = getFx(guess, edges);
  799. let dfx = getDFx(guess, edges);
  800. // we limit the movement to avoid instability.
  801. let limit = 40;
  802. let ratio = Math.max(-limit, Math.min(limit, Math.round(fx/dfx)));
  803. guess = guess - ratio;
  804. // reduce duplicates
  805. if (guessMap[guess] !== undefined) {
  806. break;
  807. }
  808. guessMap[guess] = i;
  809. }
  810. return guess;
  811. };
  812. let moveBranch = (guess) => {
  813. // position node if there is space
  814. let nodePosition = this._getPositionForHierarchy(node);
  815. // check movable area of the branch
  816. if (branches[node.id] === undefined) {
  817. let branchNodes = {};
  818. getBranchNodes(node, branchNodes);
  819. branches[node.id] = branchNodes;
  820. }
  821. let [minBranch, maxBranch, minSpaceBranch, maxSpaceBranch] = getBranchBoundary(branches[node.id]);
  822. let diff = guess - nodePosition;
  823. // check if we are allowed to move the node:
  824. let branchOffset = 0;
  825. if (diff > 0) {
  826. branchOffset = Math.min(diff, maxSpaceBranch - this.options.hierarchical.nodeSpacing);
  827. }
  828. else if (diff < 0) {
  829. branchOffset = -Math.min(-diff, minSpaceBranch - this.options.hierarchical.nodeSpacing);
  830. }
  831. if (branchOffset != 0) {
  832. //console.log("moving branch:",branchOffset, maxSpaceBranch, minSpaceBranch)
  833. this._shiftBlock(node.id, branchOffset);
  834. //this.body.emitter.emit("_redraw");
  835. stillShifting = true;
  836. }
  837. };
  838. let moveNode = (guess) => {
  839. let nodePosition = this._getPositionForHierarchy(node);
  840. // position node if there is space
  841. let [minSpace, maxSpace] = this._getSpaceAroundNode(node);
  842. let diff = guess - nodePosition;
  843. // check if we are allowed to move the node:
  844. let newPosition = nodePosition;
  845. if (diff > 0) {
  846. newPosition = Math.min(nodePosition + (maxSpace - this.options.hierarchical.nodeSpacing), guess);
  847. }
  848. else if (diff < 0) {
  849. newPosition = Math.max(nodePosition - (minSpace - this.options.hierarchical.nodeSpacing), guess);
  850. }
  851. if (newPosition !== nodePosition) {
  852. //console.log("moving Node:",diff, minSpace, maxSpace);
  853. this._setPositionForHierarchy(node, newPosition, undefined, true);
  854. //this.body.emitter.emit("_redraw");
  855. stillShifting = true;
  856. }
  857. };
  858. let guess = getGuess(iterations, aboveEdges);
  859. moveBranch(guess);
  860. guess = getGuess(iterations, allEdges);
  861. moveNode(guess);
  862. //})
  863. };
  864. // method to remove whitespace between branches. Because we do bottom up, we can center the parents.
  865. let minimizeEdgeLengthBottomUp = (iterations) => {
  866. let levels = this.hierarchical.getLevels();
  867. levels = levels.reverse();
  868. for (let i = 0; i < iterations; i++) {
  869. stillShifting = false;
  870. for (let j = 0; j < levels.length; j++) {
  871. let level = levels[j];
  872. let levelNodes = this.hierarchical.distributionOrdering[level];
  873. for (let k = 0; k < levelNodes.length; k++) {
  874. minimizeEdgeLength(1000, levelNodes[k]);
  875. }
  876. }
  877. if (stillShifting !== true) {
  878. //console.log("FINISHED minimizeEdgeLengthBottomUp IN " + i);
  879. break;
  880. }
  881. }
  882. };
  883. // method to remove whitespace between branches. Because we do bottom up, we can center the parents.
  884. let shiftBranchesCloserBottomUp = (iterations) => {
  885. let levels = this.hierarchical.getLevels();
  886. levels = levels.reverse();
  887. for (let i = 0; i < iterations; i++) {
  888. stillShifting = false;
  889. shiftElementsCloser(branchShiftCallback, levels, true);
  890. if (stillShifting !== true) {
  891. //console.log("FINISHED shiftBranchesCloserBottomUp IN " + (i+1));
  892. break;
  893. }
  894. }
  895. };
  896. // center all parents
  897. let centerAllParents = () => {
  898. for (let nodeId in this.body.nodes) {
  899. if (this.body.nodes.hasOwnProperty(nodeId))
  900. this._centerParent(this.body.nodes[nodeId]);
  901. }
  902. };
  903. // center all parents
  904. let centerAllParentsBottomUp = () => {
  905. let levels = this.hierarchical.getLevels();
  906. levels = levels.reverse();
  907. for (let i = 0; i < levels.length; i++) {
  908. let level = levels[i];
  909. let levelNodes = this.hierarchical.distributionOrdering[level];
  910. for (let j = 0; j < levelNodes.length; j++) {
  911. this._centerParent(levelNodes[j]);
  912. }
  913. }
  914. };
  915. // the actual work is done here.
  916. if (this.options.hierarchical.blockShifting === true) {
  917. shiftBranchesCloserBottomUp(5);
  918. centerAllParents();
  919. }
  920. // minimize edge length
  921. if (this.options.hierarchical.edgeMinimization === true) {
  922. minimizeEdgeLengthBottomUp(20);
  923. }
  924. if (this.options.hierarchical.parentCentralization === true) {
  925. centerAllParentsBottomUp()
  926. }
  927. shiftTrees();
  928. }
  929. /**
  930. * This gives the space around the node. IF a map is supplied, it will only check against nodes NOT in the map.
  931. * This is used to only get the distances to nodes outside of a branch.
  932. * @param node
  933. * @param map
  934. * @returns {*[]}
  935. * @private
  936. */
  937. _getSpaceAroundNode(node, map) {
  938. let useMap = true;
  939. if (map === undefined) {
  940. useMap = false;
  941. }
  942. let level = this.hierarchical.levels[node.id];
  943. if (level !== undefined) {
  944. let index = this.hierarchical.distributionIndex[node.id];
  945. let position = this._getPositionForHierarchy(node);
  946. let ordering = this.hierarchical.distributionOrdering[level];
  947. let minSpace = 1e9;
  948. let maxSpace = 1e9;
  949. if (index !== 0) {
  950. let prevNode = ordering[index - 1];
  951. if ((useMap === true && map[prevNode.id] === undefined) || useMap === false) {
  952. let prevPos = this._getPositionForHierarchy(prevNode);
  953. minSpace = position - prevPos;
  954. }
  955. }
  956. if (index != ordering.length - 1) {
  957. let nextNode = ordering[index + 1];
  958. if ((useMap === true && map[nextNode.id] === undefined) || useMap === false) {
  959. let nextPos = this._getPositionForHierarchy(nextNode);
  960. maxSpace = Math.min(maxSpace, nextPos - position);
  961. }
  962. }
  963. return [minSpace, maxSpace];
  964. }
  965. else {
  966. return [0, 0];
  967. }
  968. }
  969. /**
  970. * We use this method to center a parent node and check if it does not cross other nodes when it does.
  971. * @param node
  972. * @private
  973. */
  974. _centerParent(node) {
  975. if (this.hierarchical.parentReference[node.id]) {
  976. let parents = this.hierarchical.parentReference[node.id];
  977. for (var i = 0; i < parents.length; i++) {
  978. let parentId = parents[i];
  979. let parentNode = this.body.nodes[parentId];
  980. let children = this.hierarchical.childrenReference[parentId];
  981. if (children !== undefined) {
  982. // get the range of the children
  983. let newPosition = this._getCenterPosition(children);
  984. let position = this._getPositionForHierarchy(parentNode);
  985. let [minSpace, maxSpace] = this._getSpaceAroundNode(parentNode);
  986. let diff = position - newPosition;
  987. if ((diff < 0 && Math.abs(diff) < maxSpace - this.options.hierarchical.nodeSpacing) ||
  988. (diff > 0 && Math.abs(diff) < minSpace - this.options.hierarchical.nodeSpacing)) {
  989. this._setPositionForHierarchy(parentNode, newPosition, undefined, true);
  990. }
  991. }
  992. }
  993. }
  994. }
  995. /**
  996. * This function places the nodes on the canvas based on the hierarchial distribution.
  997. *
  998. * @param {Object} distribution | obtained by the function this._getDistribution()
  999. * @private
  1000. */
  1001. _placeNodesByHierarchy(distribution) {
  1002. this.positionedNodes = {};
  1003. // start placing all the level 0 nodes first. Then recursively position their branches.
  1004. for (let level in distribution) {
  1005. if (distribution.hasOwnProperty(level)) {
  1006. // sort nodes in level by position:
  1007. let nodeArray = Object.keys(distribution[level]);
  1008. nodeArray = this._indexArrayToNodes(nodeArray);
  1009. this._sortNodeArray(nodeArray);
  1010. let handledNodeCount = 0;
  1011. for (let i = 0; i < nodeArray.length; i++) {
  1012. let node = nodeArray[i];
  1013. if (this.positionedNodes[node.id] === undefined) {
  1014. let spacing = this.options.hierarchical.nodeSpacing;
  1015. let pos = spacing * handledNodeCount;
  1016. // We get the X or Y values we need and store them in pos and previousPos.
  1017. // The get and set make sure we get X or Y
  1018. if (handledNodeCount > 0) {
  1019. pos = this._getPositionForHierarchy(nodeArray[i-1]) + spacing;
  1020. }
  1021. this._setPositionForHierarchy(node, pos, level);
  1022. this._validatePositionAndContinue(node, level, pos);
  1023. handledNodeCount++;
  1024. }
  1025. }
  1026. }
  1027. }
  1028. }
  1029. /**
  1030. * This is a recursively called function to enumerate the branches from the largest hubs and place the nodes
  1031. * on a X position that ensures there will be no overlap.
  1032. *
  1033. * @param parentId
  1034. * @param parentLevel
  1035. * @private
  1036. */
  1037. _placeBranchNodes(parentId, parentLevel) {
  1038. let childRef = this.hierarchical.childrenReference[parentId];
  1039. // if this is not a parent, cancel the placing. This can happen with multiple parents to one child.
  1040. if (childRef === undefined) {
  1041. return;
  1042. }
  1043. // get a list of childNodes
  1044. let childNodes = [];
  1045. for (let i = 0; i < childRef.length; i++) {
  1046. childNodes.push(this.body.nodes[childRef[i]]);
  1047. }
  1048. // use the positions to order the nodes.
  1049. this._sortNodeArray(childNodes);
  1050. // position the childNodes
  1051. for (let i = 0; i < childNodes.length; i++) {
  1052. let childNode = childNodes[i];
  1053. let childNodeLevel = this.hierarchical.levels[childNode.id];
  1054. // check if the child node is below the parent node and if it has already been positioned.
  1055. if (childNodeLevel > parentLevel && this.positionedNodes[childNode.id] === undefined) {
  1056. // get the amount of space required for this node. If parent the width is based on the amount of children.
  1057. let spacing = this.options.hierarchical.nodeSpacing;
  1058. let pos;
  1059. // we get the X or Y values we need and store them in pos and previousPos.
  1060. // The get and set make sure we get X or Y
  1061. if (i === 0) {pos = this._getPositionForHierarchy(this.body.nodes[parentId]);}
  1062. else {pos = this._getPositionForHierarchy(childNodes[i-1]) + spacing;}
  1063. this._setPositionForHierarchy(childNode, pos, childNodeLevel);
  1064. this._validatePositionAndContinue(childNode, childNodeLevel, pos);
  1065. }
  1066. else {
  1067. return;
  1068. }
  1069. }
  1070. // center the parent nodes.
  1071. let center = this._getCenterPosition(childNodes);
  1072. this._setPositionForHierarchy(this.body.nodes[parentId], center, parentLevel);
  1073. }
  1074. /**
  1075. * This method checks for overlap and if required shifts the branch. It also keeps records of positioned nodes.
  1076. * Finally it will call _placeBranchNodes to place the branch nodes.
  1077. * @param node
  1078. * @param level
  1079. * @param pos
  1080. * @private
  1081. */
  1082. _validatePositionAndContinue(node, level, pos) {
  1083. // This method only works for formal trees and formal forests
  1084. // Early exit if this is not the case
  1085. if (!this.hierarchical.isTree) return;
  1086. // if overlap has been detected, we shift the branch
  1087. if (this.lastNodeOnLevel[level] !== undefined) {
  1088. let previousPos = this._getPositionForHierarchy(this.body.nodes[this.lastNodeOnLevel[level]]);
  1089. if (pos - previousPos < this.options.hierarchical.nodeSpacing) {
  1090. let diff = (previousPos + this.options.hierarchical.nodeSpacing) - pos;
  1091. let sharedParent = this._findCommonParent(this.lastNodeOnLevel[level], node.id);
  1092. this._shiftBlock(sharedParent.withChild, diff);
  1093. }
  1094. }
  1095. this.lastNodeOnLevel[level] = node.id; // store change in position.
  1096. this.positionedNodes[node.id] = true;
  1097. this._placeBranchNodes(node.id, level);
  1098. }
  1099. /**
  1100. * Receives an array with node indices and returns an array with the actual node references.
  1101. * Used for sorting based on node properties.
  1102. * @param idArray
  1103. */
  1104. _indexArrayToNodes(idArray) {
  1105. let array = [];
  1106. for (let i = 0; i < idArray.length; i++) {
  1107. array.push(this.body.nodes[idArray[i]])
  1108. }
  1109. return array;
  1110. }
  1111. /**
  1112. * This function get the distribution of levels based on hubsize
  1113. *
  1114. * @returns {Object}
  1115. * @private
  1116. */
  1117. _getDistribution() {
  1118. let distribution = {};
  1119. let nodeId, node;
  1120. // we fix Y because the hierarchy is vertical,
  1121. // we fix X so we do not give a node an x position for a second time.
  1122. // the fix of X is removed after the x value has been set.
  1123. for (nodeId in this.body.nodes) {
  1124. if (this.body.nodes.hasOwnProperty(nodeId)) {
  1125. node = this.body.nodes[nodeId];
  1126. let level = this.hierarchical.levels[nodeId] === undefined ? 0 : this.hierarchical.levels[nodeId];
  1127. if(this._isVertical()) {
  1128. node.y = this.options.hierarchical.levelSeparation * level;
  1129. node.options.fixed.y = true;
  1130. }
  1131. else {
  1132. node.x = this.options.hierarchical.levelSeparation * level;
  1133. node.options.fixed.x = true;
  1134. }
  1135. if (distribution[level] === undefined) {
  1136. distribution[level] = {};
  1137. }
  1138. distribution[level][nodeId] = node;
  1139. }
  1140. }
  1141. return distribution;
  1142. }
  1143. /**
  1144. * Return the active (i.e. visible) edges for this node
  1145. *
  1146. * @returns {array} Array of edge instances
  1147. * @private
  1148. */
  1149. _getActiveEdges(node) {
  1150. let result = [];
  1151. for (let j in node.edges) {
  1152. let edge = node.edges[j];
  1153. if (this.body.edgeIndices.indexOf(edge.id) !== -1) {
  1154. result.push(edge);
  1155. }
  1156. }
  1157. return result;
  1158. }
  1159. /**
  1160. * Get the hubsizes for all active nodes.
  1161. *
  1162. * @returns {number}
  1163. * @private
  1164. */
  1165. _getHubSizes() {
  1166. let hubSizes = {};
  1167. let nodeIds = this.body.nodeIndices;
  1168. for (let i in nodeIds) {
  1169. let nodeId = nodeIds[i];
  1170. let node = this.body.nodes[nodeId];
  1171. let hubSize = this._getActiveEdges(node).length;
  1172. hubSizes[hubSize] = true;
  1173. }
  1174. // Make an array of the size sorted descending
  1175. let result = [];
  1176. for (let size in hubSizes) {
  1177. result.push(Number(size));
  1178. }
  1179. result.sort(function(a, b) {
  1180. return b - a;
  1181. });
  1182. return result;
  1183. }
  1184. /**
  1185. * this function allocates nodes in levels based on the recursive branching from the largest hubs.
  1186. *
  1187. * @private
  1188. */
  1189. _determineLevelsByHubsize() {
  1190. let levelDownstream = (nodeA, nodeB) => {
  1191. this.hierarchical.levelDownstream(nodeA, nodeB);
  1192. }
  1193. let hubSizes = this._getHubSizes();
  1194. for (let i = 0; i < hubSizes.length; ++i ) {
  1195. let hubSize = hubSizes[i];
  1196. if (hubSize === 0) break;
  1197. let nodeIds = this.body.nodeIndices;
  1198. for (let j in nodeIds) {
  1199. let nodeId = nodeIds[j];
  1200. let node = this.body.nodes[nodeId];
  1201. if (hubSize === this._getActiveEdges(node).length) {
  1202. this._crawlNetwork(levelDownstream, nodeId);
  1203. }
  1204. }
  1205. }
  1206. }
  1207. /**
  1208. * TODO: release feature
  1209. * TODO: Determine if this feature is needed at all
  1210. *
  1211. * @private
  1212. */
  1213. _determineLevelsCustomCallback() {
  1214. let minLevel = 100000;
  1215. // TODO: this should come from options.
  1216. let customCallback = function(nodeA, nodeB, edge) {
  1217. };
  1218. // TODO: perhaps move to HierarchicalStatus.
  1219. // But I currently don't see the point, this method is not used.
  1220. let levelByDirection = (nodeA, nodeB, edge) => {
  1221. let levelA = this.hierarchical.levels[nodeA.id];
  1222. // set initial level
  1223. if (levelA === undefined) { levelA = this.hierarchical.levels[nodeA.id] = minLevel;}
  1224. let diff = customCallback(
  1225. NetworkUtil.cloneOptions(nodeA,'node'),
  1226. NetworkUtil.cloneOptions(nodeB,'node'),
  1227. NetworkUtil.cloneOptions(edge,'edge')
  1228. );
  1229. this.hierarchical.levels[nodeB.id] = levelA + diff;
  1230. };
  1231. this._crawlNetwork(levelByDirection);
  1232. this.hierarchical.setMinLevelToZero(this.body.nodes);
  1233. }
  1234. /**
  1235. * this function allocates nodes in levels based on the direction of the edges
  1236. *
  1237. * @param hubsize
  1238. * @private
  1239. */
  1240. _determineLevelsDirected() {
  1241. let minLevel = 10000;
  1242. let levelByDirection = (nodeA, nodeB, edge) => {
  1243. let levelA = this.hierarchical.levels[nodeA.id];
  1244. // set initial level
  1245. if (levelA === undefined) { levelA = this.hierarchical.levels[nodeA.id] = minLevel;}
  1246. if (edge.toId == nodeB.id) {
  1247. this.hierarchical.levels[nodeB.id] = levelA + 1;
  1248. }
  1249. else {
  1250. this.hierarchical.levels[nodeB.id] = levelA - 1;
  1251. }
  1252. };
  1253. this._crawlNetwork(levelByDirection);
  1254. this.hierarchical.setMinLevelToZero(this.body.nodes);
  1255. }
  1256. /**
  1257. * Update the bookkeeping of parent and child.
  1258. * @private
  1259. */
  1260. _generateMap() {
  1261. let fillInRelations = (parentNode, childNode) => {
  1262. if (this.hierarchical.levels[childNode.id] > this.hierarchical.levels[parentNode.id]) {
  1263. this.hierarchical.addRelation(parentNode.id, childNode.id);
  1264. }
  1265. };
  1266. this._crawlNetwork(fillInRelations);
  1267. this.hierarchical.checkIfTree();
  1268. }
  1269. /**
  1270. * Crawl over the entire network and use a callback on each node couple that is connected to each other.
  1271. * @param callback | will receive nodeA, nodeB and the connecting edge. A and B are distinct.
  1272. * @param startingNodeId
  1273. * @private
  1274. */
  1275. _crawlNetwork(callback = function() {}, startingNodeId) {
  1276. let progress = {};
  1277. let crawler = (node, tree) => {
  1278. if (progress[node.id] === undefined) {
  1279. this.hierarchical.setTreeIndex(node, tree);
  1280. progress[node.id] = true;
  1281. let childNode;
  1282. let edges = this._getActiveEdges(node);
  1283. for (let i = 0; i < edges.length; i++) {
  1284. let edge = edges[i];
  1285. if (edge.connected === true) {
  1286. if (edge.toId == node.id) { // Not '===' because id's can be string and numeric
  1287. childNode = edge.from;
  1288. }
  1289. else {
  1290. childNode = edge.to;
  1291. }
  1292. if (node.id != childNode.id) { // Not '!==' because id's can be string and numeric
  1293. callback(node, childNode, edge);
  1294. crawler(childNode, tree);
  1295. }
  1296. }
  1297. }
  1298. }
  1299. };
  1300. if (startingNodeId === undefined) {
  1301. // Crawl over all nodes
  1302. let treeIndex = 0; // Serves to pass a unique id for the current distinct tree
  1303. for (let i = 0; i < this.body.nodeIndices.length; i++) {
  1304. let nodeId = this.body.nodeIndices[i];
  1305. if (progress[nodeId] === undefined) {
  1306. let node = this.body.nodes[nodeId];
  1307. crawler(node, treeIndex);
  1308. treeIndex += 1;
  1309. }
  1310. }
  1311. }
  1312. else {
  1313. // Crawl from the given starting node
  1314. let node = this.body.nodes[startingNodeId];
  1315. if (node === undefined) {
  1316. console.error("Node not found:", startingNodeId);
  1317. return;
  1318. }
  1319. crawler(node);
  1320. }
  1321. }
  1322. /**
  1323. * Shift a branch a certain distance
  1324. * @param parentId
  1325. * @param diff
  1326. * @private
  1327. */
  1328. _shiftBlock(parentId, diff) {
  1329. let progress = {};
  1330. let shifter = (parentId) => {
  1331. if (progress[parentId]) {
  1332. return;
  1333. }
  1334. progress[parentId] = true;
  1335. if(this._isVertical()) {
  1336. this.body.nodes[parentId].x += diff;
  1337. }
  1338. else {
  1339. this.body.nodes[parentId].y += diff;
  1340. }
  1341. let childRef = this.hierarchical.childrenReference[parentId];
  1342. if (childRef !== undefined) {
  1343. for (let i = 0; i < childRef.length; i++) {
  1344. shifter(childRef[i]);
  1345. }
  1346. }
  1347. };
  1348. shifter(parentId);
  1349. }
  1350. /**
  1351. * Find a common parent between branches.
  1352. * @param childA
  1353. * @param childB
  1354. * @returns {{foundParent, withChild}}
  1355. * @private
  1356. */
  1357. _findCommonParent(childA,childB) {
  1358. let parents = {};
  1359. let iterateParents = (parents,child) => {
  1360. let parentRef = this.hierarchical.parentReference[child];
  1361. if (parentRef !== undefined) {
  1362. for (let i = 0; i < parentRef.length; i++) {
  1363. let parent = parentRef[i];
  1364. parents[parent] = true;
  1365. iterateParents(parents, parent)
  1366. }
  1367. }
  1368. };
  1369. let findParent = (parents, child) => {
  1370. let parentRef = this.hierarchical.parentReference[child];
  1371. if (parentRef !== undefined) {
  1372. for (let i = 0; i < parentRef.length; i++) {
  1373. let parent = parentRef[i];
  1374. if (parents[parent] !== undefined) {
  1375. return {foundParent:parent, withChild:child};
  1376. }
  1377. let branch = findParent(parents, parent);
  1378. if (branch.foundParent !== null) {
  1379. return branch;
  1380. }
  1381. }
  1382. }
  1383. return {foundParent:null, withChild:child};
  1384. };
  1385. iterateParents(parents, childA);
  1386. return findParent(parents, childB);
  1387. }
  1388. /**
  1389. * Abstract the getting of the position so we won't have to repeat the check for direction all the time
  1390. * @param node
  1391. * @param position
  1392. * @param level
  1393. * @private
  1394. */
  1395. _setPositionForHierarchy(node, position, level, doNotUpdate = false) {
  1396. //console.log('_setPositionForHierarchy',node.id, position)
  1397. if (doNotUpdate !== true) {
  1398. this.hierarchical.addToOrdering(node, level);
  1399. }
  1400. if(this._isVertical()) {
  1401. node.x = position;
  1402. }
  1403. else {
  1404. node.y = position;
  1405. }
  1406. }
  1407. /**
  1408. * Utility function to cut down on typing this all the time.
  1409. *
  1410. * TODO: use this in all applicable situations in this class.
  1411. *
  1412. * @private
  1413. */
  1414. _isVertical() {
  1415. return (this.options.hierarchical.direction === 'UD' || this.options.hierarchical.direction === 'DU');
  1416. }
  1417. /**
  1418. * Abstract the getting of the position of a node so we do not have to repeat the direction check all the time.
  1419. * @param node
  1420. * @returns {number|*}
  1421. * @private
  1422. */
  1423. _getPositionForHierarchy(node) {
  1424. if(this._isVertical()) {
  1425. return node.x;
  1426. }
  1427. else {
  1428. return node.y;
  1429. }
  1430. }
  1431. /**
  1432. * Use the x or y value to sort the array, allowing users to specify order.
  1433. * @param nodeArray
  1434. * @private
  1435. */
  1436. _sortNodeArray(nodeArray) {
  1437. if (nodeArray.length > 1) {
  1438. if(this._isVertical()) {
  1439. nodeArray.sort(function (a, b) {
  1440. return a.x - b.x;
  1441. })
  1442. }
  1443. else {
  1444. nodeArray.sort(function (a, b) {
  1445. return a.y - b.y;
  1446. })
  1447. }
  1448. }
  1449. }
  1450. /**
  1451. * Get the type of static smooth curve in case it is required.
  1452. *
  1453. * The return value is the type to use to translate dynamic curves to
  1454. * another type, in the case of hierarchical layout. Dynamic curves do
  1455. * not work for that layout type.
  1456. */
  1457. getStaticType() {
  1458. // Node that 'type' is the edge type, and therefore 'orthogonal' to the layout type.
  1459. let type = 'horizontal';
  1460. if (!this._isVertical()) {
  1461. type = 'vertical';
  1462. }
  1463. return type;
  1464. }
  1465. /**
  1466. * Determine the center position of a branch from the passed list of child nodes
  1467. *
  1468. * This takes into account the positions of all the child nodes.
  1469. * @param childNodes {array} Array of either child nodes or node id's
  1470. * @return {number}
  1471. * @private
  1472. */
  1473. _getCenterPosition(childNodes) {
  1474. let minPos = 1e9;
  1475. let maxPos = -1e9;
  1476. for (let i = 0; i < childNodes.length; i++) {
  1477. let childNode;
  1478. if (childNodes[i].id !== undefined) {
  1479. childNode = childNodes[i];
  1480. } else {
  1481. let childNodeId = childNodes[i];
  1482. childNode = this.body.nodes[childNodeId];
  1483. }
  1484. let position = this._getPositionForHierarchy(childNode);
  1485. minPos = Math.min(minPos, position);
  1486. maxPos = Math.max(maxPos, position);
  1487. }
  1488. return 0.5 * (minPos + maxPos);
  1489. }
  1490. }
  1491. export default LayoutEngine;