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.

1741 lines
55 KiB

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