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.

816 lines
27 KiB

9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
  1. 'use strict';
  2. let util = require('../../util');
  3. import NetworkUtil from '../NetworkUtil';
  4. class LayoutEngine {
  5. constructor(body) {
  6. this.body = body;
  7. this.initialRandomSeed = Math.round(Math.random() * 1000000);
  8. this.randomSeed = this.initialRandomSeed;
  9. this.options = {};
  10. this.optionsBackup = {};
  11. this.defaultOptions = {
  12. randomSeed: undefined,
  13. improvedLayout: true,
  14. hierarchical: {
  15. enabled:false,
  16. levelSeparation: 150,
  17. direction: 'UD', // UD, DU, LR, RL
  18. sortMethod: 'hubsize' // hubsize, directed
  19. }
  20. };
  21. util.extend(this.options, this.defaultOptions);
  22. this.lastNodeOnLevel = {};
  23. this.hierarchicalParents = {};
  24. this.hierarchicalChildren = {};
  25. this.bindEventListeners();
  26. }
  27. bindEventListeners() {
  28. this.body.emitter.on('_dataChanged', () => {
  29. this.setupHierarchicalLayout();
  30. });
  31. this.body.emitter.on('_dataLoaded', () => {
  32. this.layoutNetwork();
  33. });
  34. this.body.emitter.on('_resetHierarchicalLayout', () => {
  35. this.setupHierarchicalLayout();
  36. });
  37. }
  38. setOptions(options, allOptions) {
  39. if (options !== undefined) {
  40. let prevHierarchicalState = this.options.hierarchical.enabled;
  41. util.selectiveDeepExtend(["randomSeed", "improvedLayout"],this.options, options);
  42. util.mergeOptions(this.options, options, 'hierarchical');
  43. if (options.randomSeed !== undefined) {this.initialRandomSeed = options.randomSeed;}
  44. if (this.options.hierarchical.enabled === true) {
  45. if (prevHierarchicalState === true) {
  46. // refresh the overridden options for nodes and edges.
  47. this.body.emitter.emit('refresh', true);
  48. }
  49. // make sure the level seperation is the right way up
  50. if (this.options.hierarchical.direction === 'RL' || this.options.hierarchical.direction === 'DU') {
  51. if (this.options.hierarchical.levelSeparation > 0) {
  52. this.options.hierarchical.levelSeparation *= -1;
  53. }
  54. }
  55. else {
  56. if (this.options.hierarchical.levelSeparation < 0) {
  57. this.options.hierarchical.levelSeparation *= -1;
  58. }
  59. }
  60. this.body.emitter.emit('_resetHierarchicalLayout');
  61. // because the hierarchical system needs it's own physics and smooth curve settings, we adapt the other options if needed.
  62. return this.adaptAllOptionsForHierarchicalLayout(allOptions);
  63. }
  64. else {
  65. if (prevHierarchicalState === true) {
  66. // refresh the overridden options for nodes and edges.
  67. this.body.emitter.emit('refresh');
  68. return util.deepExtend(allOptions,this.optionsBackup);
  69. }
  70. }
  71. }
  72. return allOptions;
  73. }
  74. adaptAllOptionsForHierarchicalLayout(allOptions) {
  75. if (this.options.hierarchical.enabled === true) {
  76. // set the physics
  77. if (allOptions.physics === undefined || allOptions.physics === true) {
  78. allOptions.physics = {solver: 'hierarchicalRepulsion'};
  79. this.optionsBackup.physics = {solver:'barnesHut'};
  80. }
  81. else if (typeof allOptions.physics === 'object') {
  82. this.optionsBackup.physics = {solver:'barnesHut'};
  83. if (allOptions.physics.solver !== undefined) {
  84. this.optionsBackup.physics = {solver:allOptions.physics.solver};
  85. }
  86. allOptions.physics['solver'] = 'hierarchicalRepulsion';
  87. }
  88. else if (allOptions.physics !== false) {
  89. this.optionsBackup.physics = {solver:'barnesHut'};
  90. allOptions.physics['solver'] = 'hierarchicalRepulsion';
  91. }
  92. // get the type of static smooth curve in case it is required
  93. let type = 'horizontal';
  94. if (this.options.hierarchical.direction === 'RL' || this.options.hierarchical.direction === 'LR') {
  95. type = 'vertical';
  96. }
  97. // disable smooth curves if nothing is defined. If smooth curves have been turned on, turn them into static smooth curves.
  98. if (allOptions.edges === undefined) {
  99. this.optionsBackup.edges = {smooth:{enabled:true, type:'dynamic'}};
  100. allOptions.edges = {smooth: false};
  101. }
  102. else if (allOptions.edges.smooth === undefined) {
  103. this.optionsBackup.edges = {smooth:{enabled:true, type:'dynamic'}};
  104. allOptions.edges.smooth = false;
  105. }
  106. else {
  107. if (typeof allOptions.edges.smooth === 'boolean') {
  108. this.optionsBackup.edges = {smooth:allOptions.edges.smooth};
  109. allOptions.edges.smooth = {enabled: allOptions.edges.smooth, type:type}
  110. }
  111. else {
  112. // allow custom types except for dynamic
  113. if (allOptions.edges.smooth.type !== undefined && allOptions.edges.smooth.type !== 'dynamic') {
  114. type = allOptions.edges.smooth.type;
  115. }
  116. this.optionsBackup.edges = {
  117. smooth: allOptions.edges.smooth.enabled === undefined ? true : allOptions.edges.smooth.enabled,
  118. type:allOptions.edges.smooth.type === undefined ? 'dynamic' : allOptions.edges.smooth.type,
  119. roundness: allOptions.edges.smooth.roundness === undefined ? 0.5 : allOptions.edges.smooth.roundness,
  120. forceDirection: allOptions.edges.smooth.forceDirection === undefined ? false : allOptions.edges.smooth.forceDirection
  121. };
  122. allOptions.edges.smooth = {
  123. enabled: allOptions.edges.smooth.enabled === undefined ? true : allOptions.edges.smooth.enabled,
  124. type:type,
  125. roundness: allOptions.edges.smooth.roundness === undefined ? 0.5 : allOptions.edges.smooth.roundness,
  126. forceDirection: allOptions.edges.smooth.forceDirection === undefined ? false : allOptions.edges.smooth.forceDirection
  127. }
  128. }
  129. }
  130. // force all edges into static smooth curves. Only applies to edges that do not use the global options for smooth.
  131. this.body.emitter.emit('_forceDisableDynamicCurves', type);
  132. }
  133. return allOptions;
  134. }
  135. seededRandom() {
  136. let x = Math.sin(this.randomSeed++) * 10000;
  137. return x - Math.floor(x);
  138. }
  139. positionInitially(nodesArray) {
  140. if (this.options.hierarchical.enabled !== true) {
  141. this.randomSeed = this.initialRandomSeed;
  142. for (let i = 0; i < nodesArray.length; i++) {
  143. let node = nodesArray[i];
  144. let radius = 10 * 0.1 * nodesArray.length + 10;
  145. let angle = 2 * Math.PI * this.seededRandom();
  146. if (node.x === undefined) {
  147. node.x = radius * Math.cos(angle);
  148. }
  149. if (node.y === undefined) {
  150. node.y = radius * Math.sin(angle);
  151. }
  152. }
  153. }
  154. }
  155. /**
  156. * Use KamadaKawai to position nodes. This is quite a heavy algorithm so if there are a lot of nodes we
  157. * cluster them first to reduce the amount.
  158. */
  159. layoutNetwork() {
  160. if (this.options.hierarchical.enabled !== true && this.options.improvedLayout === true) {
  161. // first check if we should KamadaKawai to layout. The threshold is if less than half of the visible
  162. // nodes have predefined positions we use this.
  163. let positionDefined = 0;
  164. for (let i = 0; i < this.body.nodeIndices.length; i++) {
  165. let node = this.body.nodes[this.body.nodeIndices[i]];
  166. if (node.predefinedPosition === true) {
  167. positionDefined += 1;
  168. }
  169. }
  170. // if less than half of the nodes have a predefined position we continue
  171. if (positionDefined < 0.5 * this.body.nodeIndices.length) {
  172. let MAX_LEVELS = 10;
  173. let level = 0;
  174. let clusterThreshold = 100;
  175. // if there are a lot of nodes, we cluster before we run the algorithm.
  176. if (this.body.nodeIndices.length > clusterThreshold) {
  177. let startLength = this.body.nodeIndices.length;
  178. while (this.body.nodeIndices.length > clusterThreshold) {
  179. //console.time("clustering")
  180. level += 1;
  181. let before = this.body.nodeIndices.length;
  182. // if there are many nodes we do a hubsize cluster
  183. if (level % 3 === 0) {
  184. this.body.modules.clustering.clusterBridges();
  185. }
  186. else {
  187. this.body.modules.clustering.clusterOutliers();
  188. }
  189. let after = this.body.nodeIndices.length;
  190. if ((before == after && level % 3 !== 0) || level > MAX_LEVELS) {
  191. this._declusterAll();
  192. this.body.emitter.emit("_layoutFailed");
  193. console.info("This network could not be positioned by this version of the improved layout algorithm. Please disable improvedLayout for better performance.");
  194. return;
  195. }
  196. //console.timeEnd("clustering")
  197. //console.log(level,after)
  198. }
  199. // increase the size of the edges
  200. this.body.modules.kamadaKawai.setOptions({springLength: Math.max(150, 2 * startLength)})
  201. }
  202. // position the system for these nodes and edges
  203. this.body.modules.kamadaKawai.solve(this.body.nodeIndices, this.body.edgeIndices, true);
  204. // shift to center point
  205. this._shiftToCenter();
  206. // perturb the nodes a little bit to force the physics to kick in
  207. let offset = 70;
  208. for (let i = 0; i < this.body.nodeIndices.length; i++) {
  209. this.body.nodes[this.body.nodeIndices[i]].x += (0.5 - this.seededRandom())*offset;
  210. this.body.nodes[this.body.nodeIndices[i]].y += (0.5 - this.seededRandom())*offset;
  211. }
  212. // uncluster all clusters
  213. this._declusterAll();
  214. // reposition all bezier nodes.
  215. this.body.emitter.emit("_repositionBezierNodes");
  216. }
  217. }
  218. }
  219. /**
  220. * Move all the nodes towards to the center so gravitational pull wil not move the nodes away from view
  221. * @private
  222. */
  223. _shiftToCenter() {
  224. let range = NetworkUtil.getRangeCore(this.body.nodes, this.body.nodeIndices);
  225. let center = NetworkUtil.findCenter(range);
  226. for (let i = 0; i < this.body.nodeIndices.length; i++) {
  227. this.body.nodes[this.body.nodeIndices[i]].x -= center.x;
  228. this.body.nodes[this.body.nodeIndices[i]].y -= center.y;
  229. }
  230. }
  231. _declusterAll() {
  232. let clustersPresent = true;
  233. while (clustersPresent === true) {
  234. clustersPresent = false;
  235. for (let i = 0; i < this.body.nodeIndices.length; i++) {
  236. if (this.body.nodes[this.body.nodeIndices[i]].isCluster === true) {
  237. clustersPresent = true;
  238. this.body.modules.clustering.openCluster(this.body.nodeIndices[i], {}, false);
  239. }
  240. }
  241. if (clustersPresent === true) {
  242. this.body.emitter.emit('_dataChanged');
  243. }
  244. }
  245. }
  246. getSeed() {
  247. return this.initialRandomSeed;
  248. }
  249. /**
  250. * This is the main function to layout the nodes in a hierarchical way.
  251. * It checks if the node details are supplied correctly
  252. *
  253. * @private
  254. */
  255. setupHierarchicalLayout() {
  256. if (this.options.hierarchical.enabled === true && this.body.nodeIndices.length > 0) {
  257. // get the size of the largest hubs and check if the user has defined a level for a node.
  258. let node, nodeId;
  259. let definedLevel = false;
  260. let undefinedLevel = false;
  261. this.hierarchicalLevels = {};
  262. this.nodeSpacing = 100;
  263. for (nodeId in this.body.nodes) {
  264. if (this.body.nodes.hasOwnProperty(nodeId)) {
  265. node = this.body.nodes[nodeId];
  266. if (node.options.level !== undefined) {
  267. definedLevel = true;
  268. this.hierarchicalLevels[nodeId] = node.options.level;
  269. }
  270. else {
  271. undefinedLevel = true;
  272. }
  273. }
  274. }
  275. // if the user defined some levels but not all, alert and run without hierarchical layout
  276. if (undefinedLevel === true && definedLevel === true) {
  277. throw new Error('To use the hierarchical layout, nodes require either no predefined levels or levels have to be defined for all nodes.');
  278. return;
  279. }
  280. else {
  281. // define levels if undefined by the users. Based on hubsize
  282. if (undefinedLevel === true) {
  283. if (this.options.hierarchical.sortMethod === 'hubsize') {
  284. this._determineLevelsByHubsize();
  285. }
  286. else if (this.options.hierarchical.sortMethod === 'directed') {
  287. this._determineLevelsDirected();
  288. }
  289. else if (this.options.hierarchical.sortMethod === 'custom') {
  290. this._determineLevelsCustomCallback();
  291. }
  292. }
  293. // check the distribution of the nodes per level.
  294. let distribution = this._getDistribution();
  295. // get the parent children relations.
  296. this._generateMap();
  297. // place the nodes on the canvas.
  298. this._placeNodesByHierarchy(distribution);
  299. // Todo: condense the whitespace.
  300. this._condenseHierarchy(distribution);
  301. // shift to center so gravity does not have to do much
  302. this._shiftToCenter();
  303. }
  304. }
  305. }
  306. /**
  307. * TODO: implement. Clear whitespace after positioning.
  308. * @private
  309. */
  310. _condenseHierarchy(distribution) {
  311. }
  312. /**
  313. * This function places the nodes on the canvas based on the hierarchial distribution.
  314. *
  315. * @param {Object} distribution | obtained by the function this._getDistribution()
  316. * @private
  317. */
  318. _placeNodesByHierarchy(distribution) {
  319. this.positionedNodes = {};
  320. // start placing all the level 0 nodes first. Then recursively position their branches.
  321. for (let level in distribution) {
  322. if (distribution.hasOwnProperty(level)) {
  323. // sort nodes in level by position:
  324. let nodeArray = Object.keys(distribution[level]);
  325. nodeArray = this._indexArrayToNodes(nodeArray);
  326. this._sortNodeArray(nodeArray);
  327. for (let i = 0; i < nodeArray.length; i++) {
  328. let node = nodeArray[i];
  329. if (this.positionedNodes[node.id] === undefined) {
  330. this._setPositionForHierarchy(node, this.nodeSpacing * i);
  331. this.positionedNodes[node.id] = true;
  332. this._placeBranchNodes(node.id, level);
  333. }
  334. }
  335. }
  336. }
  337. }
  338. /**
  339. * Receives an array with node indices and returns an array with the actual node references. Used for sorting based on
  340. * node properties.
  341. * @param idArray
  342. */
  343. _indexArrayToNodes(idArray) {
  344. let array = [];
  345. for (let i = 0; i < idArray.length; i++) {
  346. array.push(this.body.nodes[idArray[i]])
  347. }
  348. return array;
  349. }
  350. /**
  351. * This function get the distribution of levels based on hubsize
  352. *
  353. * @returns {Object}
  354. * @private
  355. */
  356. _getDistribution() {
  357. let distribution = {};
  358. let nodeId, node;
  359. // we fix Y because the hierarchy is vertical, we fix X so we do not give a node an x position for a second time.
  360. // the fix of X is removed after the x value has been set.
  361. for (nodeId in this.body.nodes) {
  362. if (this.body.nodes.hasOwnProperty(nodeId)) {
  363. node = this.body.nodes[nodeId];
  364. let level = this.hierarchicalLevels[nodeId] === undefined ? 0 : this.hierarchicalLevels[nodeId];
  365. if (this.options.hierarchical.direction === 'UD' || this.options.hierarchical.direction === 'DU') {
  366. node.y = this.options.hierarchical.levelSeparation * level;
  367. node.options.fixed.y = true;
  368. }
  369. else {
  370. node.x = this.options.hierarchical.levelSeparation * level;
  371. node.options.fixed.x = true;
  372. }
  373. if (distribution[level] === undefined) {
  374. distribution[level] = {};
  375. }
  376. distribution[level][nodeId] = node;
  377. }
  378. }
  379. return distribution;
  380. }
  381. /**
  382. * Get the hubsize from all remaining unlevelled nodes.
  383. *
  384. * @returns {number}
  385. * @private
  386. */
  387. _getHubSize() {
  388. let hubSize = 0;
  389. for (let nodeId in this.body.nodes) {
  390. if (this.body.nodes.hasOwnProperty(nodeId)) {
  391. let node = this.body.nodes[nodeId];
  392. if (this.hierarchicalLevels[nodeId] === undefined) {
  393. hubSize = node.edges.length < hubSize ? hubSize : node.edges.length;
  394. }
  395. }
  396. }
  397. return hubSize;
  398. }
  399. /**
  400. * this function allocates nodes in levels based on the recursive branching from the largest hubs.
  401. *
  402. * @param hubsize
  403. * @private
  404. */
  405. _determineLevelsByHubsize() {
  406. let hubSize = 1;
  407. let levelDownstream = (nodeA, nodeB) => {
  408. if (this.hierarchicalLevels[nodeB.id] === undefined) {
  409. // set initial level
  410. if (this.hierarchicalLevels[nodeA.id] === undefined) {
  411. this.hierarchicalLevels[nodeA.id] = 0;
  412. }
  413. // set level
  414. this.hierarchicalLevels[nodeB.id] = this.hierarchicalLevels[nodeA.id] + 1;
  415. }
  416. };
  417. while (hubSize > 0) {
  418. // determine hubs
  419. hubSize = this._getHubSize();
  420. if (hubSize === 0)
  421. break;
  422. for (let nodeId in this.body.nodes) {
  423. if (this.body.nodes.hasOwnProperty(nodeId)) {
  424. let node = this.body.nodes[nodeId];
  425. if (node.edges.length === hubSize) {
  426. this._crawlNetwork(levelDownstream,nodeId);
  427. }
  428. }
  429. }
  430. }
  431. }
  432. /**
  433. * TODO: release feature
  434. * @private
  435. */
  436. _determineLevelsCustomCallback() {
  437. let minLevel = 100000;
  438. // TODO: this should come from options.
  439. let customCallback = function(nodeA, nodeB, edge) {
  440. };
  441. let levelByDirection = (nodeA, nodeB, edge) => {
  442. let levelA = this.hierarchicalLevels[nodeA.id];
  443. // set initial level
  444. if (levelA === undefined) {this.hierarchicalLevels[nodeA.id] = minLevel;}
  445. let diff = customCallback(
  446. NetworkUtil.cloneOptions(nodeA,'node'),
  447. NetworkUtil.cloneOptions(nodeB,'node'),
  448. NetworkUtil.cloneOptions(edge,'edge')
  449. );
  450. this.hierarchicalLevels[nodeB.id] = this.hierarchicalLevels[nodeA.id] + diff;
  451. };
  452. this._crawlNetwork(levelByDirection);
  453. this._setMinLevelToZero();
  454. }
  455. /**
  456. * this function allocates nodes in levels based on the direction of the edges
  457. *
  458. * @param hubsize
  459. * @private
  460. */
  461. _determineLevelsDirected() {
  462. let minLevel = 10000;
  463. let levelByDirection = (nodeA, nodeB, edge) => {
  464. let levelA = this.hierarchicalLevels[nodeA.id];
  465. // set initial level
  466. if (levelA === undefined) {this.hierarchicalLevels[nodeA.id] = minLevel;}
  467. if (edge.toId == nodeB.id) {
  468. this.hierarchicalLevels[nodeB.id] = this.hierarchicalLevels[nodeA.id] + 1;
  469. }
  470. else {
  471. this.hierarchicalLevels[nodeB.id] = this.hierarchicalLevels[nodeA.id] - 1;
  472. }
  473. };
  474. this._crawlNetwork(levelByDirection);
  475. this._setMinLevelToZero();
  476. }
  477. /**
  478. * Small util method to set the minimum levels of the nodes to zero.
  479. * @private
  480. */
  481. _setMinLevelToZero() {
  482. let minLevel = 1e9;
  483. // get the minimum level
  484. for (let nodeId in this.body.nodes) {
  485. if (this.body.nodes.hasOwnProperty(nodeId)) {
  486. minLevel = Math.min(this.hierarchicalLevels[nodeId], minLevel);
  487. }
  488. }
  489. // subtract the minimum from the set so we have a range starting from 0
  490. for (let nodeId in this.body.nodes) {
  491. if (this.body.nodes.hasOwnProperty(nodeId)) {
  492. this.hierarchicalLevels[nodeId] -= minLevel;
  493. }
  494. }
  495. }
  496. /**
  497. * Update the bookkeeping of parent and child.
  498. * @param parentNodeId
  499. * @param childNodeId
  500. * @private
  501. */
  502. _generateMap() {
  503. let fillInRelations = (parentNode, childNode) => {
  504. if (this.hierarchicalLevels[childNode.id] > this.hierarchicalLevels[parentNode.id]) {
  505. let parentNodeId = parentNode.id;
  506. let childNodeId = childNode.id;
  507. if (this.hierarchicalParents[parentNodeId] === undefined) {
  508. this.hierarchicalParents[parentNodeId] = {children: [], amount: 0};
  509. }
  510. this.hierarchicalParents[parentNodeId].children.push(childNodeId);
  511. if (this.hierarchicalChildren[childNodeId] === undefined) {
  512. this.hierarchicalChildren[childNodeId] = {parents: [], amount: 0};
  513. }
  514. this.hierarchicalChildren[childNodeId].parents.push(parentNodeId);
  515. }
  516. };
  517. this._crawlNetwork(fillInRelations);
  518. }
  519. /**
  520. * Crawl over the entire network and use a callback on each node couple that is connected to eachother.
  521. * @param callback | will receive nodeA nodeB and the connecting edge. A and B are unique.
  522. * @param startingNodeId
  523. * @private
  524. */
  525. _crawlNetwork(callback = function() {}, startingNodeId) {
  526. let progress = {};
  527. let crawler = (node) => {
  528. if (progress[node.id] === undefined) {
  529. progress[node.id] = true;
  530. let childNode;
  531. for (let i = 0; i < node.edges.length; i++) {
  532. if (node.edges[i].toId === node.id) {childNode = node.edges[i].from;}
  533. else {childNode = node.edges[i].to;}
  534. if (node.id !== childNode.id) {
  535. callback(node, childNode, node.edges[i]);
  536. crawler(childNode);
  537. }
  538. }
  539. }
  540. };
  541. // we can crawl from a specific node or over all nodes.
  542. if (startingNodeId === undefined) {
  543. for (let i = 0; i < this.body.nodeIndices.length; i++) {
  544. let node = this.body.nodes[this.body.nodeIndices[i]];
  545. crawler(node);
  546. }
  547. }
  548. else {
  549. let node = this.body.nodes[startingNodeId];
  550. if (node === undefined) {
  551. console.error("Node not found:", startingNodeId);
  552. return;
  553. }
  554. crawler(node);
  555. }
  556. }
  557. /**
  558. * This is a recursively called function to enumerate the branches from the largest hubs and place the nodes
  559. * on a X position that ensures there will be no overlap.
  560. *
  561. * @param parentId
  562. * @param parentLevel
  563. * @private
  564. */
  565. _placeBranchNodes(parentId, parentLevel) {
  566. // if this is not a parent, cancel the placing. This can happen with multiple parents to one child.
  567. if (this.hierarchicalParents[parentId] === undefined) {
  568. return;
  569. }
  570. // get a list of childNodes
  571. let childNodes = [];
  572. for (let i = 0; i < this.hierarchicalParents[parentId].children.length; i++) {
  573. childNodes.push(this.body.nodes[this.hierarchicalParents[parentId].children[i]]);
  574. }
  575. // use the positions to order the nodes.
  576. this._sortNodeArray(childNodes);
  577. // position the childNodes
  578. for (let i = 0; i < childNodes.length; i++) {
  579. let childNode = childNodes[i];
  580. let childNodeLevel = this.hierarchicalLevels[childNode.id];
  581. // check if the childnode is below the parent node and if it has already been positioned.
  582. if (childNodeLevel > parentLevel && this.positionedNodes[childNode.id] === undefined) {
  583. // get the amount of space required for this node. If parent the width is based on the amount of children.
  584. let pos;
  585. // we get the X or Y values we need and store them in pos and previousPos. The get and set make sure we get X or Y
  586. if (i === 0) {pos = this._getPositionForHierarchy(this.body.nodes[parentId]);}
  587. else {pos = this._getPositionForHierarchy(childNodes[i-1]) + this.nodeSpacing;}
  588. this._setPositionForHierarchy(childNode, pos);
  589. // if overlap has been detected, we shift the branch
  590. if (this.lastNodeOnLevel[childNodeLevel] !== undefined) {
  591. let previousPos = this._getPositionForHierarchy(this.body.nodes[this.lastNodeOnLevel[childNodeLevel]]);
  592. if (pos - previousPos < this.nodeSpacing) {
  593. let diff = (previousPos + this.nodeSpacing) - pos;
  594. let sharedParent = this._findCommonParent(this.lastNodeOnLevel[childNodeLevel], childNode.id);
  595. this._shiftBlock(sharedParent.withChild, diff);
  596. }
  597. }
  598. // store change in position.
  599. this.lastNodeOnLevel[childNodeLevel] = childNode.id;
  600. this.positionedNodes[childNode.id] = true;
  601. this._placeBranchNodes(childNode.id, childNodeLevel);
  602. }
  603. else {
  604. return
  605. }
  606. }
  607. // center the parent nodes.
  608. let minPos = 1e9;
  609. let maxPos = -1e9;
  610. for (let i = 0; i < childNodes.length; i++) {
  611. let childNodeId = childNodes[i].id;
  612. minPos = Math.min(minPos, this._getPositionForHierarchy(this.body.nodes[childNodeId]));
  613. maxPos = Math.max(maxPos, this._getPositionForHierarchy(this.body.nodes[childNodeId]));
  614. }
  615. this._setPositionForHierarchy(this.body.nodes[parentId], 0.5 * (minPos + maxPos));
  616. }
  617. /**
  618. * Shift a branch a certain distance
  619. * @param parentId
  620. * @param diff
  621. * @private
  622. */
  623. _shiftBlock(parentId, diff) {
  624. if (this.options.hierarchical.direction === 'UD' || this.options.hierarchical.direction === 'DU') {
  625. this.body.nodes[parentId].x += diff;
  626. }
  627. else {
  628. this.body.nodes[parentId].y += diff;
  629. }
  630. if (this.hierarchicalParents[parentId] !== undefined) {
  631. for (let i = 0; i < this.hierarchicalParents[parentId].children.length; i++) {
  632. this._shiftBlock(this.hierarchicalParents[parentId].children[i], diff);
  633. }
  634. }
  635. }
  636. /**
  637. * Find a common parent between branches.
  638. * @param childA
  639. * @param childB
  640. * @returns {{foundParent, withChild}}
  641. * @private
  642. */
  643. _findCommonParent(childA,childB) {
  644. let parents = {};
  645. let iterateParents = (parents,child) => {
  646. if (this.hierarchicalChildren[child] !== undefined) {
  647. for (let i = 0; i < this.hierarchicalChildren[child].parents.length; i++) {
  648. let parent = this.hierarchicalChildren[child].parents[i];
  649. parents[parent] = true;
  650. iterateParents(parents, parent)
  651. }
  652. }
  653. };
  654. let findParent = (parents, child) => {
  655. if (this.hierarchicalChildren[child] !== undefined) {
  656. for (let i = 0; i < this.hierarchicalChildren[child].parents.length; i++) {
  657. let parent = this.hierarchicalChildren[child].parents[i];
  658. if (parents[parent] !== undefined) {
  659. return {foundParent:parent, withChild:child};
  660. }
  661. let branch = findParent(parents, parent);
  662. if (branch.foundParent !== null) {
  663. return branch;
  664. }
  665. }
  666. }
  667. return {foundParent:null, withChild:child};
  668. };
  669. iterateParents(parents, childA);
  670. return findParent(parents, childB);
  671. }
  672. /**
  673. * Abstract the getting of the position so we won't have to repeat the check for direction all the time
  674. * @param node
  675. * @param position
  676. * @private
  677. */
  678. _setPositionForHierarchy(node, position) {
  679. if (this.options.hierarchical.direction === 'UD' || this.options.hierarchical.direction === 'DU') {
  680. node.x = position;
  681. }
  682. else {
  683. node.y = position;
  684. }
  685. }
  686. /**
  687. * Abstract the getting of the position of a node so we do not have to repeat the direction check all the time.
  688. * @param node
  689. * @returns {number|*}
  690. * @private
  691. */
  692. _getPositionForHierarchy(node) {
  693. if (this.options.hierarchical.direction === 'UD' || this.options.hierarchical.direction === 'DU') {
  694. return node.x;
  695. }
  696. else {
  697. return node.y;
  698. }
  699. }
  700. /**
  701. * Use the x or y value to sort the array, allowing users to specify order.
  702. * @param nodeArray
  703. * @private
  704. */
  705. _sortNodeArray(nodeArray) {
  706. if (nodeArray.length > 1) {
  707. if (this.options.hierarchical.direction === 'UD' || this.options.hierarchical.direction === 'DU') {
  708. nodeArray.sort(function (a, b) {
  709. return a.x - b.x;
  710. })
  711. }
  712. else {
  713. nodeArray.sort(function (a, b) {
  714. return a.y - b.y;
  715. })
  716. }
  717. }
  718. }
  719. }
  720. export default LayoutEngine;