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.

797 lines
26 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();
  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() {
  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. let nodeId, node;
  320. this.positionedNodes = {};
  321. // start placing all the level 0 nodes first. Then recursively position their branches.
  322. for (let level in distribution) {
  323. if (distribution.hasOwnProperty(level)) {
  324. // sort nodes in level by position:
  325. let nodeArray = Object.keys(distribution[level]);
  326. this._sortNodeArray(nodeArray)
  327. for (let i = 0; i < nodeArray.length; i++) {
  328. nodeId = nodeArray[i];
  329. node = distribution[level][nodeId];
  330. if (this.positionedNodes[nodeId] === undefined) {
  331. this._setPositionForHierarchy(node, this.nodeSpacing * i)
  332. this.positionedNodes[nodeId] = true;
  333. this._placeBranchNodes(nodeId, level);
  334. }
  335. }
  336. }
  337. }
  338. }
  339. /**
  340. * This function get the distribution of levels based on hubsize
  341. *
  342. * @returns {Object}
  343. * @private
  344. */
  345. _getDistribution() {
  346. let distribution = {};
  347. let nodeId, node;
  348. // 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.
  349. // the fix of X is removed after the x value has been set.
  350. for (nodeId in this.body.nodes) {
  351. if (this.body.nodes.hasOwnProperty(nodeId)) {
  352. node = this.body.nodes[nodeId];
  353. let level = this.hierarchicalLevels[nodeId] === undefined ? 0 : this.hierarchicalLevels[nodeId];
  354. if (this.options.hierarchical.direction === 'UD' || this.options.hierarchical.direction === 'DU') {
  355. node.y = this.options.hierarchical.levelSeparation * level;
  356. node.options.fixed.y = true;
  357. }
  358. else {
  359. node.x = this.options.hierarchical.levelSeparation * level;
  360. node.options.fixed.x = true;
  361. }
  362. if (distribution[level] === undefined) {
  363. distribution[level] = {};
  364. }
  365. distribution[level][nodeId] = node;
  366. }
  367. }
  368. return distribution;
  369. }
  370. /**
  371. * Get the hubsize from all remaining unlevelled nodes.
  372. *
  373. * @returns {number}
  374. * @private
  375. */
  376. _getHubSize() {
  377. let hubSize = 0;
  378. for (let nodeId in this.body.nodes) {
  379. if (this.body.nodes.hasOwnProperty(nodeId)) {
  380. let node = this.body.nodes[nodeId];
  381. if (this.hierarchicalLevels[nodeId] === undefined) {
  382. hubSize = node.edges.length < hubSize ? hubSize : node.edges.length;
  383. }
  384. }
  385. }
  386. return hubSize;
  387. }
  388. /**
  389. * this function allocates nodes in levels based on the recursive branching from the largest hubs.
  390. *
  391. * @param hubsize
  392. * @private
  393. */
  394. _determineLevelsByHubsize() {
  395. let hubSize = 1;
  396. let levelDownstream = (nodeA, nodeB) => {
  397. if (this.hierarchicalLevels[nodeB.id] === undefined) {
  398. // set initial level
  399. if (this.hierarchicalLevels[nodeA.id] === undefined) {
  400. this.hierarchicalLevels[nodeA.id] = 0;
  401. }
  402. // set level
  403. this.hierarchicalLevels[nodeB.id] = this.hierarchicalLevels[nodeA.id] + 1;
  404. }
  405. }
  406. while (hubSize > 0) {
  407. // determine hubs
  408. hubSize = this._getHubSize();
  409. if (hubSize === 0)
  410. break;
  411. for (let nodeId in this.body.nodes) {
  412. if (this.body.nodes.hasOwnProperty(nodeId)) {
  413. let node = this.body.nodes[nodeId];
  414. if (node.edges.length === hubSize) {
  415. this._crawlNetwork(levelDownstream,nodeId);
  416. }
  417. }
  418. }
  419. }
  420. }
  421. /**
  422. * TODO: release feature
  423. * @private
  424. */
  425. _determineLevelsCustomCallback() {
  426. let minLevel = 100000;
  427. // TODO: this should come from options.
  428. let customCallback = function(nodeA, nodeB, edge) {
  429. }
  430. let levelByDirection = (nodeA, nodeB, edge) => {
  431. let levelA = this.hierarchicalLevels[nodeA.id];
  432. // set initial level
  433. if (levelA === undefined) {this.hierarchicalLevels[nodeA.id] = minLevel;}
  434. let diff = customCallback(
  435. NetworkUtil._cloneOptions(nodeA,'node'),
  436. NetworkUtil._cloneOptions(nodeB,'node'),
  437. NetworkUtil._cloneOptions(edge,'edge')
  438. );
  439. this.hierarchicalLevels[nodeB.id] = this.hierarchicalLevels[nodeA.id] + diff;
  440. }
  441. this._crawlNetwork(levelByDirection);
  442. this._setMinLevelToZero();
  443. }
  444. /**
  445. * this function allocates nodes in levels based on the direction of the edges
  446. *
  447. * @param hubsize
  448. * @private
  449. */
  450. _determineLevelsDirected() {
  451. let minLevel = 10000;
  452. let levelByDirection = (nodeA, nodeB, edge) => {
  453. let levelA = this.hierarchicalLevels[nodeA.id];
  454. // set initial level
  455. if (levelA === undefined) {this.hierarchicalLevels[nodeA.id] = minLevel;}
  456. if (edge.toId == nodeB.id) {
  457. this.hierarchicalLevels[nodeB.id] = this.hierarchicalLevels[nodeA.id] + 1;
  458. }
  459. else {
  460. this.hierarchicalLevels[nodeB.id] = this.hierarchicalLevels[nodeA.id] - 1;
  461. }
  462. }
  463. this._crawlNetwork(levelByDirection)
  464. this._setMinLevelToZero();
  465. }
  466. /**
  467. * Small util method to set the minimum levels of the nodes to zero.
  468. * @private
  469. */
  470. _setMinLevelToZero() {
  471. let minLevel = 1e9;
  472. // get the minimum level
  473. for (let nodeId in this.body.nodes) {
  474. if (this.body.nodes.hasOwnProperty(nodeId)) {
  475. minLevel = Math.min(this.hierarchicalLevels[nodeId], minLevel);
  476. }
  477. }
  478. // subtract the minimum from the set so we have a range starting from 0
  479. for (let nodeId in this.body.nodes) {
  480. if (this.body.nodes.hasOwnProperty(nodeId)) {
  481. this.hierarchicalLevels[nodeId] -= minLevel;
  482. }
  483. }
  484. }
  485. /**
  486. * Update the bookkeeping of parent and child.
  487. * @param parentNodeId
  488. * @param childNodeId
  489. * @private
  490. */
  491. _generateMap() {
  492. let fillInRelations = (parentNode, childNode) => {
  493. if (this.hierarchicalLevels[childNode.id] > this.hierarchicalLevels[parentNode.id]) {
  494. let parentNodeId = parentNode.id;
  495. let childNodeId = childNode.id;
  496. if (this.hierarchicalParents[parentNodeId] === undefined) {
  497. this.hierarchicalParents[parentNodeId] = {children: [], amount: 0};
  498. }
  499. this.hierarchicalParents[parentNodeId].children.push(childNodeId);
  500. if (this.hierarchicalChildren[childNodeId] === undefined) {
  501. this.hierarchicalChildren[childNodeId] = {parents: [], amount: 0};
  502. }
  503. this.hierarchicalChildren[childNodeId].parents.push(parentNodeId);
  504. }
  505. }
  506. this._crawlNetwork(fillInRelations);
  507. }
  508. /**
  509. * Crawl over the entire network and use a callback on each node couple that is connected to eachother.
  510. * @param callback | will receive nodeA nodeB and the connecting edge. A and B are unique.
  511. * @param startingNodeId
  512. * @private
  513. */
  514. _crawlNetwork(callback = function() {}, startingNodeId) {
  515. let progress = {};
  516. let crawler = (node) => {
  517. if (progress[node.id] === undefined) {
  518. progress[node.id] = true;
  519. let childNode;
  520. for (let i = 0; i < node.edges.length; i++) {
  521. if (node.edges[i].toId === node.id) {childNode = node.edges[i].from;}
  522. else {childNode = node.edges[i].to;}
  523. if (node.id !== childNode.id) {
  524. callback(node, childNode, node.edges[i]);
  525. crawler(childNode);
  526. }
  527. }
  528. }
  529. }
  530. // we can crawl from a specific node or over all nodes.
  531. if (startingNodeId === undefined) {
  532. for (let i = 0; i < this.body.nodeIndices.length; i++) {
  533. let node = this.body.nodes[this.body.nodeIndices[i]];
  534. crawler(node);
  535. }
  536. }
  537. else {
  538. let node = this.body.nodes[startingNodeId];
  539. if (node === undefined) {
  540. console.error("Node not found:", startingNodeId);
  541. return;
  542. }
  543. crawler(node);
  544. }
  545. }
  546. /**
  547. * This is a recursively called function to enumerate the branches from the largest hubs and place the nodes
  548. * on a X position that ensures there will be no overlap.
  549. *
  550. * @param parentId
  551. * @param parentLevel
  552. * @private
  553. */
  554. _placeBranchNodes(parentId, parentLevel) {
  555. // if this is not a parent, cancel the placing. This can happen with multiple parents to one child.
  556. if (this.hierarchicalParents[parentId] === undefined) {
  557. return;
  558. }
  559. // get a list of childNodes
  560. let childNodes = [];
  561. for (let i = 0; i < this.hierarchicalParents[parentId].children.length; i++) {
  562. childNodes.push(this.body.nodes[this.hierarchicalParents[parentId].children[i]]);
  563. }
  564. // use the positions to order the nodes.
  565. this._sortNodeArray(childNodes);
  566. // position the childNodes
  567. for (let i = 0; i < childNodes.length; i++) {
  568. let childNode = childNodes[i];
  569. let childNodeLevel = this.hierarchicalLevels[childNode.id];
  570. // check if the childnode is below the parent node and if it has already been positioned.
  571. if (childNodeLevel > parentLevel && this.positionedNodes[childNode.id] === undefined) {
  572. // get the amount of space required for this node. If parent the width is based on the amount of children.
  573. let pos;
  574. // 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
  575. if (i === 0) {pos = this._getPositionForHierarchy(this.body.nodes[parentId]);}
  576. else {pos = this._getPositionForHierarchy(childNodes[i-1]) + this.nodeSpacing;}
  577. this._setPositionForHierarchy(childNode, pos);
  578. // if overlap has been detected, we shift the branch
  579. if (this.lastNodeOnLevel[childNodeLevel] !== undefined) {
  580. let previousPos = this._getPositionForHierarchy(this.body.nodes[this.lastNodeOnLevel[childNodeLevel]]);
  581. if (pos - previousPos < this.nodeSpacing) {
  582. let diff = (previousPos + this.nodeSpacing) - pos;
  583. let sharedParent = this._findCommonParent(this.lastNodeOnLevel[childNodeLevel], childNode.id);
  584. this._shiftBlock(sharedParent.withChild, diff);
  585. }
  586. }
  587. // store change in position.
  588. this.lastNodeOnLevel[childNodeLevel] = childNode.id;
  589. this.positionedNodes[childNode.id] = true;
  590. this._placeBranchNodes(childNode.id, childNodeLevel);
  591. }
  592. else {
  593. return
  594. }
  595. }
  596. // center the parent nodes.
  597. let minPos = 1e9;
  598. let maxPos = -1e9;
  599. for (let i = 0; i < childNodes.length; i++) {
  600. let childNodeId = childNodes[i].id;
  601. minPos = Math.min(minPos, this._getPositionForHierarchy(this.body.nodes[childNodeId]));
  602. maxPos = Math.max(maxPos, this._getPositionForHierarchy(this.body.nodes[childNodeId]));
  603. }
  604. this._setPositionForHierarchy(this.body.nodes[parentId], 0.5 * (minPos + maxPos));
  605. }
  606. /**
  607. * Shift a branch a certain distance
  608. * @param parentId
  609. * @param diff
  610. * @private
  611. */
  612. _shiftBlock(parentId, diff) {
  613. if (this.options.hierarchical.direction === 'UD' || this.options.hierarchical.direction === 'DU') {
  614. this.body.nodes[parentId].x += diff;
  615. }
  616. else {
  617. this.body.nodes[parentId].y += diff;
  618. }
  619. if (this.hierarchicalParents[parentId] !== undefined) {
  620. for (let i = 0; i < this.hierarchicalParents[parentId].children.length; i++) {
  621. this._shiftBlock(this.hierarchicalParents[parentId].children[i], diff);
  622. }
  623. }
  624. }
  625. /**
  626. * Find a common parent between branches.
  627. * @param childA
  628. * @param childB
  629. * @returns {{foundParent, withChild}}
  630. * @private
  631. */
  632. _findCommonParent(childA,childB) {
  633. let parents = {}
  634. let iterateParents = (parents,child) => {
  635. if (this.hierarchicalChildren[child] !== undefined) {
  636. for (let i = 0; i < this.hierarchicalChildren[child].parents.length; i++) {
  637. let parent = this.hierarchicalChildren[child].parents[i];
  638. parents[parent] = true;
  639. iterateParents(parents, parent)
  640. }
  641. }
  642. }
  643. let findParent = (parents, child) => {
  644. if (this.hierarchicalChildren[child] !== undefined) {
  645. for (let i = 0; i < this.hierarchicalChildren[child].parents.length; i++) {
  646. let parent = this.hierarchicalChildren[child].parents[i];
  647. if (parents[parent] !== undefined) {
  648. return {foundParent:parent, withChild:child};
  649. }
  650. return findParent(parents, parent);
  651. }
  652. }
  653. return {foundParent:null, withChild:child};
  654. }
  655. iterateParents(parents, childA);
  656. return findParent(parents, childB)
  657. }
  658. /**
  659. * Abstract the getting of the position so we won't have to repeat the check for direction all the time
  660. * @param node
  661. * @param position
  662. * @private
  663. */
  664. _setPositionForHierarchy(node, position) {
  665. if (this.options.hierarchical.direction === 'UD' || this.options.hierarchical.direction === 'DU') {
  666. node.x = position;
  667. }
  668. else {
  669. node.y = position;
  670. }
  671. }
  672. /**
  673. * Abstract the getting of the position of a node so we do not have to repeat the direction check all the time.
  674. * @param node
  675. * @returns {number|*}
  676. * @private
  677. */
  678. _getPositionForHierarchy(node) {
  679. if (this.options.hierarchical.direction === 'UD' || this.options.hierarchical.direction === 'DU') {
  680. return node.x;
  681. }
  682. else {
  683. return node.y;
  684. }
  685. }
  686. /**
  687. * Use the x or y value to sort the array, allowing users to specify order.
  688. * @param nodeArray
  689. * @private
  690. */
  691. _sortNodeArray(nodeArray) {
  692. if (this.options.hierarchical.direction === 'UD' || this.options.hierarchical.direction === 'DU') {
  693. nodeArray.sort(function (a,b) {return a.x - b.x;})
  694. }
  695. else {
  696. nodeArray.sort(function (a,b) {return a.y - b.y;})
  697. }
  698. }
  699. }
  700. export default LayoutEngine;