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.

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