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.

778 lines
25 KiB

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' || 'direction') {
  287. this._determineLevelsDirected();
  288. }
  289. }
  290. // check the distribution of the nodes per level.
  291. let distribution = this._getDistribution();
  292. // get the parent children relations.
  293. this._generateMap();
  294. // place the nodes on the canvas.
  295. this._placeNodesByHierarchy(distribution);
  296. // Todo: condense the whitespace.
  297. this._condenseHierarchy();
  298. // shift to center so gravity does not have to do much
  299. this._shiftToCenter();
  300. }
  301. }
  302. }
  303. /**
  304. * TODO: implement. Clear whitespace after positioning.
  305. * @private
  306. */
  307. _condenseHierarchy() {
  308. }
  309. /**
  310. * This function places the nodes on the canvas based on the hierarchial distribution.
  311. *
  312. * @param {Object} distribution | obtained by the function this._getDistribution()
  313. * @private
  314. */
  315. _placeNodesByHierarchy(distribution) {
  316. let nodeId, node;
  317. this.positionedNodes = {};
  318. // start placing all the level 0 nodes first. Then recursively position their branches.
  319. for (let level in distribution) {
  320. if (distribution.hasOwnProperty(level)) {
  321. // sort nodes in level by position:
  322. let nodeArray = Object.keys(distribution[level]);
  323. this._sortNodeArray(nodeArray)
  324. for (let i = 0; i < nodeArray.length; i++) {
  325. nodeId = nodeArray[i];
  326. node = distribution[level][nodeId];
  327. if (this.positionedNodes[nodeId] === undefined) {
  328. this._setPositionForHierarchy(node, this.nodeSpacing * i)
  329. this.positionedNodes[nodeId] = true;
  330. this._placeBranchNodes(nodeId, level);
  331. }
  332. }
  333. }
  334. }
  335. }
  336. /**
  337. * This function get the distribution of levels based on hubsize
  338. *
  339. * @returns {Object}
  340. * @private
  341. */
  342. _getDistribution() {
  343. let distribution = {};
  344. let nodeId, node;
  345. // 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.
  346. // the fix of X is removed after the x value has been set.
  347. for (nodeId in this.body.nodes) {
  348. if (this.body.nodes.hasOwnProperty(nodeId)) {
  349. node = this.body.nodes[nodeId];
  350. let level = this.hierarchicalLevels[nodeId] === undefined ? 0 : this.hierarchicalLevels[nodeId];
  351. if (this.options.hierarchical.direction === 'UD' || this.options.hierarchical.direction === 'DU') {
  352. node.y = this.options.hierarchical.levelSeparation * level;
  353. node.options.fixed.y = true;
  354. }
  355. else {
  356. node.x = this.options.hierarchical.levelSeparation * level;
  357. node.options.fixed.x = true;
  358. }
  359. if (distribution[level] === undefined) {
  360. distribution[level] = {};
  361. }
  362. distribution[level][nodeId] = node;
  363. }
  364. }
  365. return distribution;
  366. }
  367. /**
  368. * Get the hubsize from all remaining unlevelled nodes.
  369. *
  370. * @returns {number}
  371. * @private
  372. */
  373. _getHubSize() {
  374. let hubSize = 0;
  375. for (let nodeId in this.body.nodes) {
  376. if (this.body.nodes.hasOwnProperty(nodeId)) {
  377. let node = this.body.nodes[nodeId];
  378. if (this.hierarchicalLevels[nodeId] === undefined) {
  379. hubSize = node.edges.length < hubSize ? hubSize : node.edges.length;
  380. }
  381. }
  382. }
  383. return hubSize;
  384. }
  385. /**
  386. * this function allocates nodes in levels based on the recursive branching from the largest hubs.
  387. *
  388. * @param hubsize
  389. * @private
  390. */
  391. _determineLevelsByHubsize() {
  392. let nodeId, node;
  393. let hubSize = 1;
  394. while (hubSize > 0) {
  395. // determine hubs
  396. hubSize = this._getHubSize();
  397. if (hubSize === 0)
  398. break;
  399. for (nodeId in this.body.nodes) {
  400. if (this.body.nodes.hasOwnProperty(nodeId)) {
  401. node = this.body.nodes[nodeId];
  402. if (node.edges.length === hubSize) {
  403. this._setLevelByHubsize(0, node);
  404. }
  405. }
  406. }
  407. }
  408. }
  409. /**
  410. * this function is called recursively to enumerate the barnches of the largest hubs and give each node a level.
  411. *
  412. * @param level
  413. * @param edges
  414. * @param parentId
  415. * @private
  416. */
  417. _setLevelByHubsize(level, node) {
  418. if (this.hierarchicalLevels[node.id] !== undefined)
  419. return;
  420. let childNode;
  421. this.hierarchicalLevels[node.id] = level;
  422. for (let i = 0; i < node.edges.length; i++) {
  423. if (node.edges[i].toId === node.id) {
  424. childNode = node.edges[i].from;
  425. }
  426. else {
  427. childNode = node.edges[i].to;
  428. }
  429. this._setLevelByHubsize(level + 1, childNode, node.id);
  430. }
  431. }
  432. /**
  433. * this function allocates nodes in levels based on the direction of the edges
  434. *
  435. * @param hubsize
  436. * @private
  437. */
  438. _determineLevelsDirected() {
  439. let nodeId, node;
  440. let minLevel = 10000;
  441. // set first node to source
  442. for (nodeId in this.body.nodes) {
  443. if (this.body.nodes.hasOwnProperty(nodeId)) {
  444. node = this.body.nodes[nodeId];
  445. this._setLevelDirected(minLevel,node);
  446. }
  447. }
  448. // get the minimum level
  449. for (nodeId in this.body.nodes) {
  450. if (this.body.nodes.hasOwnProperty(nodeId)) {
  451. minLevel = Math.min(this.hierarchicalLevels[nodeId], minLevel);
  452. }
  453. }
  454. // subtract the minimum from the set so we have a range starting from 0
  455. for (nodeId in this.body.nodes) {
  456. if (this.body.nodes.hasOwnProperty(nodeId)) {
  457. this.hierarchicalLevels[nodeId] -= minLevel;
  458. }
  459. }
  460. }
  461. /**
  462. * this function is called recursively to enumerate the branched of the first node and give each node a level based on edge direction
  463. *
  464. * @param level
  465. * @param edges
  466. * @param parentId
  467. * @private
  468. */
  469. _setLevelDirected(level, node, parentId) {
  470. if (this.hierarchicalLevels[node.id] !== undefined)
  471. return;
  472. let childNode;
  473. this.hierarchicalLevels[node.id] = level;
  474. for (let i = 0; i < node.edges.length; i++) {
  475. if (node.edges[i].toId === node.id) {
  476. childNode = node.edges[i].from;
  477. this._setLevelDirected(level - 1, childNode, node.id);
  478. }
  479. else {
  480. childNode = node.edges[i].to;
  481. this._setLevelDirected(level + 1, childNode, node.id);
  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. _crawlNetwork(callback = function() {}) {
  509. let progress = {};
  510. let crawler = (node) => {
  511. if (progress[node.id] === undefined) {
  512. progress[node.id] = true;
  513. let childNode;
  514. for (let i = 0; i < node.edges.length; i++) {
  515. if (node.edges[i].toId === node.id) {childNode = node.edges[i].from;}
  516. else {childNode = node.edges[i].to;}
  517. if (node.id !== childNode.id) {
  518. callback(node, childNode);
  519. crawler(childNode);
  520. }
  521. }
  522. }
  523. }
  524. for (let i = 0; i < this.body.nodeIndices.length; i++) {
  525. let node = this.body.nodes[this.body.nodeIndices[i]];
  526. crawler(node);
  527. }
  528. }
  529. /**
  530. * This is a recursively called function to enumerate the branches from the largest hubs and place the nodes
  531. * on a X position that ensures there will be no overlap.
  532. *
  533. * @param edges
  534. * @param parentId
  535. * @param distribution
  536. * @param parentLevel
  537. * @private
  538. */
  539. _placeBranchNodes(parentId, parentLevel) {
  540. if (this.hierarchicalParents[parentId] === undefined) {
  541. return;
  542. }
  543. // get a list of childNodes
  544. let childNodes = [];
  545. for (let i = 0; i < this.hierarchicalParents[parentId].children.length; i++) {
  546. childNodes.push(this.body.nodes[this.hierarchicalParents[parentId].children[i]]);
  547. }
  548. // use the positions to order the nodes.
  549. this._sortNodeArray(childNodes);
  550. // position the childNodes
  551. for (let i = 0; i < childNodes.length; i++) {
  552. let childNode = childNodes[i];
  553. let childNodeLevel = this.hierarchicalLevels[childNode.id];
  554. // check if the childnode is below the parent node and if it has already been positioned.
  555. if (childNodeLevel > parentLevel && this.positionedNodes[childNode.id] === undefined) {
  556. // get the amount of space required for this node. If parent the width is based on the amount of children.
  557. let pos;
  558. // 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
  559. if (i === 0) {pos = this._getPositionForHierarchy(this.body.nodes[parentId]);}
  560. else {pos = this._getPositionForHierarchy(childNodes[i-1]) + this.nodeSpacing;}
  561. this._setPositionForHierarchy(childNode, pos);
  562. // if overlap has been detected, we shift the branch
  563. if (this.lastNodeOnLevel[childNodeLevel] !== undefined) {
  564. let previousPos = this._getPositionForHierarchy(this.body.nodes[this.lastNodeOnLevel[childNodeLevel]]);
  565. if (pos - previousPos < this.nodeSpacing) {
  566. let diff = (previousPos + this.nodeSpacing) - pos;
  567. let sharedParent = this._findCommonParent(this.lastNodeOnLevel[childNodeLevel], childNode.id);
  568. this._shiftBlock(sharedParent.withChild, diff);
  569. }
  570. }
  571. // store change in position.
  572. this.lastNodeOnLevel[childNodeLevel] = childNode.id;
  573. this.positionedNodes[childNode.id] = true;
  574. this._placeBranchNodes(childNode.id, childNodeLevel);
  575. }
  576. else {
  577. return
  578. }
  579. }
  580. // center the parent nodes.
  581. let minPos = 1e9;
  582. let maxPos = -1e9;
  583. for (let i = 0; i < childNodes.length; i++) {
  584. let childNodeId = childNodes[i].id;
  585. minPos = Math.min(minPos, this._getPositionForHierarchy(this.body.nodes[childNodeId]));
  586. maxPos = Math.max(maxPos, this._getPositionForHierarchy(this.body.nodes[childNodeId]));
  587. }
  588. this._setPositionForHierarchy(this.body.nodes[parentId], 0.5 * (minPos + maxPos));
  589. }
  590. /**
  591. * Shift a branch a certain distance
  592. * @param parentId
  593. * @param diff
  594. * @private
  595. */
  596. _shiftBlock(parentId, diff) {
  597. if (this.options.hierarchical.direction === 'UD' || this.options.hierarchical.direction === 'DU') {
  598. this.body.nodes[parentId].x += diff;
  599. }
  600. else {
  601. this.body.nodes[parentId].y += diff;
  602. }
  603. if (this.hierarchicalParents[parentId] !== undefined) {
  604. for (let i = 0; i < this.hierarchicalParents[parentId].children.length; i++) {
  605. this._shiftBlock(this.hierarchicalParents[parentId].children[i], diff);
  606. }
  607. }
  608. }
  609. /**
  610. * Find a common parent between branches.
  611. * @param childA
  612. * @param childB
  613. * @returns {{foundParent, withChild}}
  614. * @private
  615. */
  616. _findCommonParent(childA,childB) {
  617. let parents = {}
  618. let iterateParents = (parents,child) => {
  619. if (this.hierarchicalChildren[child] !== undefined) {
  620. for (let i = 0; i < this.hierarchicalChildren[child].parents.length; i++) {
  621. let parent = this.hierarchicalChildren[child].parents[i];
  622. parents[parent] = true;
  623. iterateParents(parents, parent)
  624. }
  625. }
  626. }
  627. let findParent = (parents, child) => {
  628. if (this.hierarchicalChildren[child] !== undefined) {
  629. for (let i = 0; i < this.hierarchicalChildren[child].parents.length; i++) {
  630. let parent = this.hierarchicalChildren[child].parents[i];
  631. if (parents[parent] !== undefined) {
  632. return {foundParent:parent, withChild:child};
  633. }
  634. return findParent(parents, parent);
  635. }
  636. }
  637. return {foundParent:null, withChild:child};
  638. }
  639. iterateParents(parents, childA);
  640. return findParent(parents, childB)
  641. }
  642. /**
  643. * Abstract the getting of the position so we won't have to repeat the check for direction all the time
  644. * @param node
  645. * @param position
  646. * @private
  647. */
  648. _setPositionForHierarchy(node, position) {
  649. if (this.options.hierarchical.direction === 'UD' || this.options.hierarchical.direction === 'DU') {
  650. node.x = position;
  651. }
  652. else {
  653. node.y = position;
  654. }
  655. }
  656. /**
  657. * Abstract the getting of the position of a node so we do not have to repeat the direction check all the time.
  658. * @param node
  659. * @returns {number|*}
  660. * @private
  661. */
  662. _getPositionForHierarchy(node) {
  663. if (this.options.hierarchical.direction === 'UD' || this.options.hierarchical.direction === 'DU') {
  664. return node.x;
  665. }
  666. else {
  667. return node.y;
  668. }
  669. }
  670. /**
  671. * Use the x or y value to sort the array, allowing users to specify order.
  672. * @param nodeArray
  673. * @private
  674. */
  675. _sortNodeArray(nodeArray) {
  676. if (this.options.hierarchical.direction === 'UD' || this.options.hierarchical.direction === 'DU') {
  677. nodeArray.sort(function (a,b) {return a.x - b.x;})
  678. }
  679. else {
  680. nodeArray.sort(function (a,b) {return a.y - b.y;})
  681. }
  682. }
  683. }
  684. export default LayoutEngine;