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.

1333 lines
46 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.setPhysics = false;
  10. this.options = {};
  11. this.optionsBackup = {physics:{}};
  12. this.defaultOptions = {
  13. randomSeed: undefined,
  14. improvedLayout: true,
  15. hierarchical: {
  16. enabled:false,
  17. levelSeparation: 150,
  18. nodeSpacing: 100,
  19. treeSpacing: 200,
  20. blockShifting: true,
  21. edgeMinimization: true,
  22. direction: 'UD', // UD, DU, LR, RL
  23. sortMethod: 'hubsize' // hubsize, directed
  24. }
  25. };
  26. util.extend(this.options, this.defaultOptions);
  27. this.bindEventListeners();
  28. }
  29. bindEventListeners() {
  30. this.body.emitter.on('_dataChanged', () => {
  31. this.setupHierarchicalLayout();
  32. });
  33. this.body.emitter.on('_dataLoaded', () => {
  34. this.layoutNetwork();
  35. });
  36. this.body.emitter.on('_resetHierarchicalLayout', () => {
  37. this.setupHierarchicalLayout();
  38. });
  39. }
  40. setOptions(options, allOptions) {
  41. if (options !== undefined) {
  42. let prevHierarchicalState = this.options.hierarchical.enabled;
  43. util.selectiveDeepExtend(["randomSeed", "improvedLayout"],this.options, options);
  44. util.mergeOptions(this.options, options, 'hierarchical');
  45. if (options.randomSeed !== undefined) {this.initialRandomSeed = options.randomSeed;}
  46. if (this.options.hierarchical.enabled === true) {
  47. if (prevHierarchicalState === true) {
  48. // refresh the overridden options for nodes and edges.
  49. this.body.emitter.emit('refresh', true);
  50. }
  51. // make sure the level separation is the right way up
  52. if (this.options.hierarchical.direction === 'RL' || this.options.hierarchical.direction === 'DU') {
  53. if (this.options.hierarchical.levelSeparation > 0) {
  54. this.options.hierarchical.levelSeparation *= -1;
  55. }
  56. }
  57. else {
  58. if (this.options.hierarchical.levelSeparation < 0) {
  59. this.options.hierarchical.levelSeparation *= -1;
  60. }
  61. }
  62. this.body.emitter.emit('_resetHierarchicalLayout');
  63. // because the hierarchical system needs it's own physics and smooth curve settings, we adapt the other options if needed.
  64. return this.adaptAllOptionsForHierarchicalLayout(allOptions);
  65. }
  66. else {
  67. if (prevHierarchicalState === true) {
  68. // refresh the overridden options for nodes and edges.
  69. this.body.emitter.emit('refresh');
  70. return util.deepExtend(allOptions,this.optionsBackup);
  71. }
  72. }
  73. }
  74. return allOptions;
  75. }
  76. adaptAllOptionsForHierarchicalLayout(allOptions) {
  77. if (this.options.hierarchical.enabled === true) {
  78. // set the physics
  79. if (allOptions.physics === undefined || allOptions.physics === true) {
  80. allOptions.physics = {
  81. enabled:this.optionsBackup.physics.enabled === undefined ? true : this.optionsBackup.physics.enabled,
  82. solver:'hierarchicalRepulsion'
  83. };
  84. this.optionsBackup.physics.enabled = this.optionsBackup.physics.enabled === undefined ? true : this.optionsBackup.physics.enabled;
  85. this.optionsBackup.physics.solver = this.optionsBackup.physics.solver || 'barnesHut';
  86. }
  87. else if (typeof allOptions.physics === 'object') {
  88. this.optionsBackup.physics.enabled = allOptions.physics.enabled === undefined ? true : allOptions.physics.enabled;
  89. this.optionsBackup.physics.solver = allOptions.physics.solver || 'barnesHut';
  90. allOptions.physics.solver = 'hierarchicalRepulsion';
  91. }
  92. else if (allOptions.physics !== false) {
  93. this.optionsBackup.physics.solver ='barnesHut';
  94. allOptions.physics = {solver:'hierarchicalRepulsion'};
  95. }
  96. // get the type of static smooth curve in case it is required
  97. let type = 'horizontal';
  98. if (this.options.hierarchical.direction === 'RL' || this.options.hierarchical.direction === 'LR') {
  99. type = 'vertical';
  100. }
  101. // disable smooth curves if nothing is defined. If smooth curves have been turned on, turn them into static smooth curves.
  102. if (allOptions.edges === undefined) {
  103. this.optionsBackup.edges = {smooth:{enabled:true, type:'dynamic'}};
  104. allOptions.edges = {smooth: false};
  105. }
  106. else if (allOptions.edges.smooth === undefined) {
  107. this.optionsBackup.edges = {smooth:{enabled:true, type:'dynamic'}};
  108. allOptions.edges.smooth = false;
  109. }
  110. else {
  111. if (typeof allOptions.edges.smooth === 'boolean') {
  112. this.optionsBackup.edges = {smooth:allOptions.edges.smooth};
  113. allOptions.edges.smooth = {enabled: allOptions.edges.smooth, type:type}
  114. }
  115. else {
  116. // allow custom types except for dynamic
  117. if (allOptions.edges.smooth.type !== undefined && allOptions.edges.smooth.type !== 'dynamic') {
  118. type = allOptions.edges.smooth.type;
  119. }
  120. this.optionsBackup.edges = {
  121. smooth: allOptions.edges.smooth.enabled === undefined ? true : allOptions.edges.smooth.enabled,
  122. type: allOptions.edges.smooth.type === undefined ? 'dynamic' : allOptions.edges.smooth.type,
  123. roundness: allOptions.edges.smooth.roundness === undefined ? 0.5 : allOptions.edges.smooth.roundness,
  124. forceDirection: allOptions.edges.smooth.forceDirection === undefined ? false : allOptions.edges.smooth.forceDirection
  125. };
  126. allOptions.edges.smooth = {
  127. enabled: allOptions.edges.smooth.enabled === undefined ? true : allOptions.edges.smooth.enabled,
  128. type:type,
  129. roundness: allOptions.edges.smooth.roundness === undefined ? 0.5 : allOptions.edges.smooth.roundness,
  130. forceDirection: allOptions.edges.smooth.forceDirection === undefined ? false : allOptions.edges.smooth.forceDirection
  131. }
  132. }
  133. }
  134. // force all edges into static smooth curves. Only applies to edges that do not use the global options for smooth.
  135. this.body.emitter.emit('_forceDisableDynamicCurves', type);
  136. }
  137. return allOptions;
  138. }
  139. seededRandom() {
  140. let x = Math.sin(this.randomSeed++) * 10000;
  141. return x - Math.floor(x);
  142. }
  143. positionInitially(nodesArray) {
  144. if (this.options.hierarchical.enabled !== true) {
  145. this.randomSeed = this.initialRandomSeed;
  146. for (let i = 0; i < nodesArray.length; i++) {
  147. let node = nodesArray[i];
  148. let radius = 10 * 0.1 * nodesArray.length + 10;
  149. let angle = 2 * Math.PI * this.seededRandom();
  150. if (node.x === undefined) {
  151. node.x = radius * Math.cos(angle);
  152. }
  153. if (node.y === undefined) {
  154. node.y = radius * Math.sin(angle);
  155. }
  156. }
  157. }
  158. }
  159. /**
  160. * Use Kamada Kawai to position nodes. This is quite a heavy algorithm so if there are a lot of nodes we
  161. * cluster them first to reduce the amount.
  162. */
  163. layoutNetwork() {
  164. if (this.options.hierarchical.enabled !== true && this.options.improvedLayout === true) {
  165. // first check if we should Kamada Kawai to layout. The threshold is if less than half of the visible
  166. // nodes have predefined positions we use this.
  167. let positionDefined = 0;
  168. for (let i = 0; i < this.body.nodeIndices.length; i++) {
  169. let node = this.body.nodes[this.body.nodeIndices[i]];
  170. if (node.predefinedPosition === true) {
  171. positionDefined += 1;
  172. }
  173. }
  174. // if less than half of the nodes have a predefined position we continue
  175. if (positionDefined < 0.5 * this.body.nodeIndices.length) {
  176. let MAX_LEVELS = 10;
  177. let level = 0;
  178. let clusterThreshold = 100;
  179. // if there are a lot of nodes, we cluster before we run the algorithm.
  180. if (this.body.nodeIndices.length > clusterThreshold) {
  181. let startLength = this.body.nodeIndices.length;
  182. while (this.body.nodeIndices.length > clusterThreshold) {
  183. //console.time("clustering")
  184. level += 1;
  185. let before = this.body.nodeIndices.length;
  186. // if there are many nodes we do a hubsize cluster
  187. if (level % 3 === 0) {
  188. this.body.modules.clustering.clusterBridges();
  189. }
  190. else {
  191. this.body.modules.clustering.clusterOutliers();
  192. }
  193. let after = this.body.nodeIndices.length;
  194. if ((before == after && level % 3 !== 0) || level > MAX_LEVELS) {
  195. this._declusterAll();
  196. this.body.emitter.emit("_layoutFailed");
  197. console.info("This network could not be positioned by this version of the improved layout algorithm. Please disable improvedLayout for better performance.");
  198. return;
  199. }
  200. //console.timeEnd("clustering")
  201. //console.log(level,after)
  202. }
  203. // increase the size of the edges
  204. this.body.modules.kamadaKawai.setOptions({springLength: Math.max(150, 2 * startLength)})
  205. }
  206. // position the system for these nodes and edges
  207. this.body.modules.kamadaKawai.solve(this.body.nodeIndices, this.body.edgeIndices, true);
  208. // shift to center point
  209. this._shiftToCenter();
  210. // perturb the nodes a little bit to force the physics to kick in
  211. let offset = 70;
  212. for (let i = 0; i < this.body.nodeIndices.length; i++) {
  213. this.body.nodes[this.body.nodeIndices[i]].x += (0.5 - this.seededRandom())*offset;
  214. this.body.nodes[this.body.nodeIndices[i]].y += (0.5 - this.seededRandom())*offset;
  215. }
  216. // uncluster all clusters
  217. this._declusterAll();
  218. // reposition all bezier nodes.
  219. this.body.emitter.emit("_repositionBezierNodes");
  220. }
  221. }
  222. }
  223. /**
  224. * Move all the nodes towards to the center so gravitational pull wil not move the nodes away from view
  225. * @private
  226. */
  227. _shiftToCenter() {
  228. let range = NetworkUtil.getRangeCore(this.body.nodes, this.body.nodeIndices);
  229. let center = NetworkUtil.findCenter(range);
  230. for (let i = 0; i < this.body.nodeIndices.length; i++) {
  231. this.body.nodes[this.body.nodeIndices[i]].x -= center.x;
  232. this.body.nodes[this.body.nodeIndices[i]].y -= center.y;
  233. }
  234. }
  235. _declusterAll() {
  236. let clustersPresent = true;
  237. while (clustersPresent === true) {
  238. clustersPresent = false;
  239. for (let i = 0; i < this.body.nodeIndices.length; i++) {
  240. if (this.body.nodes[this.body.nodeIndices[i]].isCluster === true) {
  241. clustersPresent = true;
  242. this.body.modules.clustering.openCluster(this.body.nodeIndices[i], {}, false);
  243. }
  244. }
  245. if (clustersPresent === true) {
  246. this.body.emitter.emit('_dataChanged');
  247. }
  248. }
  249. }
  250. getSeed() {
  251. return this.initialRandomSeed;
  252. }
  253. /**
  254. * This is the main function to layout the nodes in a hierarchical way.
  255. * It checks if the node details are supplied correctly
  256. *
  257. * @private
  258. */
  259. setupHierarchicalLayout() {
  260. if (this.options.hierarchical.enabled === true && this.body.nodeIndices.length > 0) {
  261. // get the size of the largest hubs and check if the user has defined a level for a node.
  262. let node, nodeId;
  263. let definedLevel = false;
  264. let definedPositions = true;
  265. let undefinedLevel = false;
  266. this.hierarchicalLevels = {};
  267. this.lastNodeOnLevel = {};
  268. this.hierarchicalParents = {};
  269. this.hierarchicalChildren = {};
  270. this.hierarchicalTrees = {};
  271. this.treeIndex = -1;
  272. this.distributionOrdering = {};
  273. this.distributionIndex = {};
  274. this.distributionOrderingPresence = {};
  275. for (nodeId in this.body.nodes) {
  276. if (this.body.nodes.hasOwnProperty(nodeId)) {
  277. node = this.body.nodes[nodeId];
  278. if (node.options.x === undefined && node.options.y === undefined) {
  279. definedPositions = false;
  280. }
  281. if (node.options.level !== undefined) {
  282. definedLevel = true;
  283. this.hierarchicalLevels[nodeId] = node.options.level;
  284. }
  285. else {
  286. undefinedLevel = true;
  287. }
  288. }
  289. }
  290. // if the user defined some levels but not all, alert and run without hierarchical layout
  291. if (undefinedLevel === true && definedLevel === true) {
  292. throw new Error('To use the hierarchical layout, nodes require either no predefined levels or levels have to be defined for all nodes.');
  293. return;
  294. }
  295. else {
  296. // define levels if undefined by the users. Based on hubsize.
  297. if (undefinedLevel === true) {
  298. if (this.options.hierarchical.sortMethod === 'hubsize') {
  299. this._determineLevelsByHubsize();
  300. }
  301. else if (this.options.hierarchical.sortMethod === 'directed') {
  302. this._determineLevelsDirected();
  303. }
  304. else if (this.options.hierarchical.sortMethod === 'custom') {
  305. this._determineLevelsCustomCallback();
  306. }
  307. }
  308. // fallback for cases where there are nodes but no edges
  309. for (let nodeId in this.body.nodes) {
  310. if (this.body.nodes.hasOwnProperty(nodeId)) {
  311. if (this.hierarchicalLevels[nodeId] === undefined) {
  312. this.hierarchicalLevels[nodeId] = 0;
  313. }
  314. }
  315. }
  316. // check the distribution of the nodes per level.
  317. let distribution = this._getDistribution();
  318. // get the parent children relations.
  319. this._generateMap();
  320. // place the nodes on the canvas.
  321. this._placeNodesByHierarchy(distribution);
  322. // condense the whitespace.
  323. this._condenseHierarchy();
  324. // shift to center so gravity does not have to do much
  325. this._shiftToCenter();
  326. }
  327. }
  328. }
  329. /**
  330. * @private
  331. */
  332. _condenseHierarchy() {
  333. // Global var in this scope to define when the movement has stopped.
  334. let stillShifting = false;
  335. let branches = {};
  336. // first we have some methods to help shifting trees around.
  337. // the main method to shift the trees
  338. let shiftTrees = () => {
  339. let treeSizes = getTreeSizes();
  340. for (let i = 0; i < treeSizes.length - 1; i++) {
  341. let diff = treeSizes[i].max - treeSizes[i+1].min;
  342. if (diff !== this.options.hierarchical.treeSpacing) {
  343. shiftTree(i + 1, diff - this.options.hierarchical.treeSpacing);
  344. }
  345. }
  346. };
  347. // shift a single tree by an offset
  348. let shiftTree = (index, offset) => {
  349. for (let nodeId in this.hierarchicalTrees) {
  350. if (this.hierarchicalTrees.hasOwnProperty(nodeId)) {
  351. if (this.hierarchicalTrees[nodeId] === index) {
  352. this._setPositionForHierarchy(this.body.nodes[nodeId], offset, undefined, true);
  353. }
  354. }
  355. }
  356. };
  357. // get the width of a tree
  358. let getTreeSize = (index) => {
  359. let min = 1e9;
  360. let max = -1e9;
  361. for (let nodeId in this.hierarchicalTrees) {
  362. if (this.hierarchicalTrees.hasOwnProperty(nodeId)) {
  363. if (this.hierarchicalTrees[nodeId] === index) {
  364. let pos = this._getPositionForHierarchy(this.body.nodes[nodeId]);
  365. min = Math.min(pos, min);
  366. max = Math.max(pos, max);
  367. }
  368. }
  369. }
  370. return {min:min, max:max};
  371. };
  372. // get the width of all trees
  373. let getTreeSizes = () => {
  374. let treeWidths = [];
  375. for (let i = 0; i < this.treeIndex; i++) {
  376. treeWidths.push(getTreeSize(i));
  377. }
  378. return treeWidths;
  379. };
  380. // get a map of all nodes in this branch
  381. let getBranchNodes = (source, map) => {
  382. map[source.id] = true;
  383. if (this.hierarchicalParents[source.id]) {
  384. let children = this.hierarchicalParents[source.id].children;
  385. if (children.length > 0) {
  386. for (let i = 0; i < children.length; i++) {
  387. getBranchNodes(this.body.nodes[children[i]], map);
  388. }
  389. }
  390. }
  391. };
  392. // get a min max width as well as the maximum movement space it has on either sides
  393. // we use min max terminology because width and height can interchange depending on the direction of the layout
  394. let getBranchBoundary = (branchMap, maxLevel = 1e9) => {
  395. let minSpace = 1e9;
  396. let maxSpace = 1e9;
  397. let min = 1e9;
  398. let max = -1e9;
  399. for (let branchNode in branchMap) {
  400. if (branchMap.hasOwnProperty(branchNode)) {
  401. let node = this.body.nodes[branchNode];
  402. let level = this.hierarchicalLevels[node.id];
  403. let position = this._getPositionForHierarchy(node);
  404. // get the space around the node.
  405. let [minSpaceNode, maxSpaceNode] = this._getSpaceAroundNode(node,branchMap);
  406. minSpace = Math.min(minSpaceNode, minSpace);
  407. maxSpace = Math.min(maxSpaceNode, maxSpace);
  408. // the width is only relevant for the levels two nodes have in common. This is why we filter on this.
  409. if (level <= maxLevel) {
  410. min = Math.min(position, min);
  411. max = Math.max(position, max);
  412. }
  413. }
  414. }
  415. return [min, max, minSpace, maxSpace];
  416. };
  417. // get the maximum level of a branch.
  418. let getMaxLevel = (nodeId) => {
  419. let level = this.hierarchicalLevels[nodeId];
  420. if (this.hierarchicalParents[nodeId]) {
  421. let children = this.hierarchicalParents[nodeId].children;
  422. if (children.length > 0) {
  423. for (let i = 0; i < children.length; i++) {
  424. level = Math.max(level,getMaxLevel(children[i]));
  425. }
  426. }
  427. }
  428. return level;
  429. };
  430. // check what the maximum level is these nodes have in common.
  431. let getCollisionLevel = (node1, node2) => {
  432. let maxLevel1 = getMaxLevel(node1.id);
  433. let maxLevel2 = getMaxLevel(node2.id);
  434. return Math.min(maxLevel1, maxLevel2);
  435. };
  436. // check if two nodes have the same parent(s)
  437. let hasSameParent = (node1, node2) => {
  438. let parents1 = this.hierarchicalChildren[node1.id];
  439. let parents2 = this.hierarchicalChildren[node2.id];
  440. if (parents1 === undefined || parents2 === undefined) {
  441. return false;
  442. }
  443. parents1 = parents1.parents;
  444. parents2 = parents2.parents;
  445. for (let i = 0; i < parents1.length; i++) {
  446. for (let j = 0; j < parents2.length; j++) {
  447. if (parents1[i] == parents2[j]) {
  448. return true;
  449. }
  450. }
  451. }
  452. return false;
  453. };
  454. // condense elements. These can be nodes or branches depending on the callback.
  455. let shiftElementsCloser = (callback, levels, centerParents) => {
  456. for (let i = 0; i < levels.length; i++) {
  457. let level = levels[i];
  458. let levelNodes = this.distributionOrdering[level];
  459. if (levelNodes.length > 1) {
  460. for (let j = 0; j < levelNodes.length - 1; j++) {
  461. if (hasSameParent(levelNodes[j],levelNodes[j+1]) === true) {
  462. if (this.hierarchicalTrees[levelNodes[j].id] === this.hierarchicalTrees[levelNodes[j+1].id]) {
  463. callback(levelNodes[j],levelNodes[j+1], centerParents);
  464. }
  465. }}
  466. }
  467. }
  468. };
  469. // callback for shifting branches
  470. let branchShiftCallback = (node1, node2, centerParent = false) => {
  471. //window.CALLBACKS.push(() => {
  472. let pos1 = this._getPositionForHierarchy(node1);
  473. let pos2 = this._getPositionForHierarchy(node2);
  474. let diffAbs = Math.abs(pos2 - pos1);
  475. //console.log("NOW CHEcKING:", node1.id, node2.id, diffAbs);
  476. if (diffAbs > this.options.hierarchical.nodeSpacing) {
  477. let branchNodes1 = {}; branchNodes1[node1.id] = true;
  478. let branchNodes2 = {}; branchNodes2[node2.id] = true;
  479. getBranchNodes(node1, branchNodes1);
  480. getBranchNodes(node2, branchNodes2);
  481. // check the largest distance between the branches
  482. let maxLevel = getCollisionLevel(node1, node2);
  483. let [min1,max1, minSpace1, maxSpace1] = getBranchBoundary(branchNodes1, maxLevel);
  484. let [min2,max2, minSpace2, maxSpace2] = getBranchBoundary(branchNodes2, maxLevel);
  485. //console.log(node1.id, getBranchBoundary(branchNodes1, maxLevel), node2.id, getBranchBoundary(branchNodes2, maxLevel), maxLevel);
  486. let diffBranch = Math.abs(max1 - min2);
  487. if (diffBranch > this.options.hierarchical.nodeSpacing) {
  488. let offset = max1 - min2 + this.options.hierarchical.nodeSpacing;
  489. if (offset < -minSpace2 + this.options.hierarchical.nodeSpacing) {
  490. offset = -minSpace2 + this.options.hierarchical.nodeSpacing;
  491. //console.log("RESETTING OFFSET", max1 - min2 + this.options.hierarchical.nodeSpacing, -minSpace2, offset);
  492. }
  493. if (offset < 0) {
  494. //console.log("SHIFTING", node2.id, offset);
  495. this._shiftBlock(node2.id, offset);
  496. stillShifting = true;
  497. if (centerParent === true)
  498. this._centerParent(node2);
  499. }
  500. }
  501. }
  502. //this.body.emitter.emit("_redraw");})
  503. };
  504. let minimizeEdgeLength = (iterations, node) => {
  505. //window.CALLBACKS.push(() => {
  506. // console.log("ts",node.id);
  507. let nodeId = node.id;
  508. let allEdges = node.edges;
  509. let nodeLevel = this.hierarchicalLevels[node.id];
  510. // gather constants
  511. let C2 = this.options.hierarchical.levelSeparation * this.options.hierarchical.levelSeparation;
  512. let referenceNodes = {};
  513. let aboveEdges = [];
  514. for (let i = 0; i < allEdges.length; i++) {
  515. let edge = allEdges[i];
  516. if (edge.toId != edge.fromId) {
  517. let otherNode = edge.toId == nodeId ? edge.from : edge.to;
  518. referenceNodes[allEdges[i].id] = otherNode;
  519. if (this.hierarchicalLevels[otherNode.id] < nodeLevel) {
  520. aboveEdges.push(edge);
  521. }
  522. }
  523. }
  524. // differentiated sum of lengths based on only moving one node over one axis
  525. let getFx = (point, edges) => {
  526. let sum = 0;
  527. for (let i = 0; i < edges.length; i++) {
  528. if (referenceNodes[edges[i].id] !== undefined) {
  529. let a = this._getPositionForHierarchy(referenceNodes[edges[i].id]) - point;
  530. sum += a / Math.sqrt(a * a + C2);
  531. }
  532. }
  533. return sum;
  534. };
  535. // doubly differentiated sum of lengths based on only moving one node over one axis
  536. let getDFx = (point, edges) => {
  537. let sum = 0;
  538. for (let i = 0; i < edges.length; i++) {
  539. if (referenceNodes[edges[i].id] !== undefined) {
  540. let a = this._getPositionForHierarchy(referenceNodes[edges[i].id]) - point;
  541. sum -= (C2 * Math.pow(a * a + C2, -1.5));
  542. }
  543. }
  544. return sum;
  545. };
  546. let getGuess = (iterations, edges) => {
  547. let guess = this._getPositionForHierarchy(node);
  548. // Newton's method for optimization
  549. let guessMap = {};
  550. for (let i = 0; i < iterations; i++) {
  551. let fx = getFx(guess, edges);
  552. let dfx = getDFx(guess, edges);
  553. // we limit the movement to avoid instability.
  554. let limit = 40;
  555. let ratio = Math.max(-limit, Math.min(limit, Math.round(fx/dfx)));
  556. guess = guess - ratio;
  557. // reduce duplicates
  558. if (guessMap[guess] !== undefined) {
  559. break;
  560. }
  561. guessMap[guess] = i;
  562. }
  563. return guess;
  564. };
  565. let moveBranch = (guess) => {
  566. // position node if there is space
  567. let nodePosition = this._getPositionForHierarchy(node);
  568. // check movable area of the branch
  569. if (branches[node.id] === undefined) {
  570. let branchNodes = {};
  571. branchNodes[node.id] = true;
  572. getBranchNodes(node, branchNodes);
  573. branches[node.id] = branchNodes;
  574. }
  575. let [minBranch, maxBranch, minSpaceBranch, maxSpaceBranch] = getBranchBoundary(branches[node.id]);
  576. let diff = guess - nodePosition;
  577. // check if we are allowed to move the node:
  578. let branchOffset = 0;
  579. if (diff > 0) {
  580. branchOffset = Math.min(diff, maxSpaceBranch - this.options.hierarchical.nodeSpacing);
  581. }
  582. else if (diff < 0) {
  583. branchOffset = -Math.min(-diff, minSpaceBranch - this.options.hierarchical.nodeSpacing);
  584. }
  585. if (branchOffset != 0) {
  586. //console.log("moving branch:",branchOffset, maxSpaceBranch, minSpaceBranch)
  587. this._shiftBlock(node.id, branchOffset);
  588. //this.body.emitter.emit("_redraw");
  589. stillShifting = true;
  590. }
  591. };
  592. let moveNode = (guess) => {
  593. let nodePosition = this._getPositionForHierarchy(node);
  594. // position node if there is space
  595. let [minSpace, maxSpace] = this._getSpaceAroundNode(node);
  596. let diff = guess - nodePosition;
  597. // check if we are allowed to move the node:
  598. let newPosition = nodePosition;
  599. if (diff > 0) {
  600. newPosition = Math.min(nodePosition + (maxSpace - this.options.hierarchical.nodeSpacing), guess);
  601. }
  602. else if (diff < 0) {
  603. newPosition = Math.max(nodePosition - (minSpace - this.options.hierarchical.nodeSpacing), guess);
  604. }
  605. if (newPosition !== nodePosition) {
  606. //console.log("moving Node:",diff, minSpace, maxSpace)
  607. this._setPositionForHierarchy(node, newPosition, undefined, true);
  608. //this.body.emitter.emit("_redraw");
  609. stillShifting = true;
  610. }
  611. };
  612. let guess = getGuess(iterations, aboveEdges);
  613. moveBranch(guess);
  614. guess = getGuess(iterations, allEdges);
  615. moveNode(guess);
  616. //})
  617. };
  618. // method to remove whitespace between branches. Because we do bottom up, we can center the parents.
  619. let minimizeEdgeLengthBottomUp = (iterations) => {
  620. let levels = Object.keys(this.distributionOrdering);
  621. levels = levels.reverse();
  622. for (let i = 0; i < iterations; i++) {
  623. stillShifting = false;
  624. for (let j = 0; j < levels.length; j++) {
  625. let level = levels[j];
  626. let levelNodes = this.distributionOrdering[level];
  627. for (let k = 0; k < levelNodes.length; k++) {
  628. minimizeEdgeLength(1000, levelNodes[k]);
  629. }
  630. }
  631. if (stillShifting !== true) {
  632. //console.log("FINISHED minimizeEdgeLengthBottomUp IN " + i);
  633. break;
  634. }
  635. }
  636. };
  637. //// method to remove whitespace between branches. Because we do bottom up, we can center the parents.
  638. let shiftBranchesCloserBottomUp = (iterations) => {
  639. let levels = Object.keys(this.distributionOrdering);
  640. levels = levels.reverse();
  641. for (let i = 0; i < iterations; i++) {
  642. stillShifting = false;
  643. shiftElementsCloser(branchShiftCallback, levels, true);
  644. if (stillShifting !== true) {
  645. //console.log("FINISHED shiftBranchesCloserBottomUp IN " + (i+1));
  646. break;
  647. }
  648. }
  649. };
  650. // center all parents
  651. let centerAllParents = () => {
  652. for (let nodeId in this.body.nodes) {
  653. if (this.body.nodes.hasOwnProperty(nodeId))
  654. this._centerParent(this.body.nodes[nodeId]);
  655. }
  656. };
  657. // the actual work is done here.
  658. if (this.options.hierarchical.blockShifting === true) {
  659. shiftBranchesCloserBottomUp(5);
  660. centerAllParents();
  661. }
  662. // minimize edge length
  663. if (this.options.hierarchical.edgeMinimization === true) {
  664. minimizeEdgeLengthBottomUp(20);
  665. }
  666. shiftTrees();
  667. }
  668. /**
  669. * This gives the space around the node. IF a map is supplied, it will only check against nodes NOT in the map.
  670. * This is used to only get the distances to nodes outside of a branch.
  671. * @param node
  672. * @param map
  673. * @returns {*[]}
  674. * @private
  675. */
  676. _getSpaceAroundNode(node, map) {
  677. let useMap = true;
  678. if (map === undefined) {
  679. useMap = false;
  680. }
  681. let level = this.hierarchicalLevels[node.id];
  682. if (level !== undefined) {
  683. let index = this.distributionIndex[node.id];
  684. let position = this._getPositionForHierarchy(node);
  685. let minSpace = 1e9;
  686. let maxSpace = 1e9;
  687. if (index !== 0) {
  688. let prevNode = this.distributionOrdering[level][index - 1];
  689. if ((useMap === true && map[prevNode.id] === undefined) || useMap === false) {
  690. let prevPos = this._getPositionForHierarchy(prevNode);
  691. minSpace = position - prevPos;
  692. }
  693. }
  694. if (index != this.distributionOrdering[level].length - 1) {
  695. let nextNode = this.distributionOrdering[level][index + 1];
  696. if ((useMap === true && map[nextNode.id] === undefined) || useMap === false) {
  697. let nextPos = this._getPositionForHierarchy(nextNode);
  698. maxSpace = Math.min(maxSpace, nextPos - position);
  699. }
  700. }
  701. return [minSpace, maxSpace];
  702. }
  703. else {
  704. return [0, 0];
  705. }
  706. }
  707. /**
  708. * We use this method to center a parent node and check if it does not cross other nodes when it does.
  709. * @param node
  710. * @private
  711. */
  712. _centerParent(node) {
  713. if (this.hierarchicalChildren[node.id]) {
  714. let parents = this.hierarchicalChildren[node.id].parents;
  715. for (var i = 0; i < parents.length; i++) {
  716. let parentId = parents[i];
  717. let parentNode = this.body.nodes[parentId];
  718. if (this.hierarchicalParents[parentId]) {
  719. // get the range of the children
  720. let minPos = 1e9;
  721. let maxPos = -1e9;
  722. let children = this.hierarchicalParents[parentId].children;
  723. if (children.length > 0) {
  724. for (let i = 0; i < children.length; i++) {
  725. let childNode = this.body.nodes[children[i]];
  726. minPos = Math.min(minPos, this._getPositionForHierarchy(childNode));
  727. maxPos = Math.max(maxPos, this._getPositionForHierarchy(childNode));
  728. }
  729. }
  730. let position = this._getPositionForHierarchy(parentNode);
  731. let [minSpace, maxSpace] = this._getSpaceAroundNode(parentNode);
  732. let newPosition = 0.5 * (minPos + maxPos);
  733. let diff = position - newPosition;
  734. if ((diff < 0 && Math.abs(diff) < maxSpace - this.options.hierarchical.nodeSpacing) || (diff > 0 && Math.abs(diff) < minSpace - this.options.hierarchical.nodeSpacing)) {
  735. this._setPositionForHierarchy(parentNode, newPosition, undefined, true);
  736. }
  737. }
  738. }
  739. }
  740. }
  741. /**
  742. * This function places the nodes on the canvas based on the hierarchial distribution.
  743. *
  744. * @param {Object} distribution | obtained by the function this._getDistribution()
  745. * @private
  746. */
  747. _placeNodesByHierarchy(distribution) {
  748. this.positionedNodes = {};
  749. // start placing all the level 0 nodes first. Then recursively position their branches.
  750. for (let level in distribution) {
  751. if (distribution.hasOwnProperty(level)) {
  752. // sort nodes in level by position:
  753. let nodeArray = Object.keys(distribution[level]);
  754. nodeArray = this._indexArrayToNodes(nodeArray);
  755. this._sortNodeArray(nodeArray);
  756. for (let i = 0; i < nodeArray.length; i++) {
  757. let node = nodeArray[i];
  758. if (this.positionedNodes[node.id] === undefined) {
  759. this._setPositionForHierarchy(node, this.options.hierarchical.nodeSpacing * i, level);
  760. this.positionedNodes[node.id] = true;
  761. this._placeBranchNodes(node.id, level);
  762. }
  763. }
  764. }
  765. }
  766. }
  767. /**
  768. * Receives an array with node indices and returns an array with the actual node references. Used for sorting based on
  769. * node properties.
  770. * @param idArray
  771. */
  772. _indexArrayToNodes(idArray) {
  773. let array = [];
  774. for (let i = 0; i < idArray.length; i++) {
  775. array.push(this.body.nodes[idArray[i]])
  776. }
  777. return array;
  778. }
  779. /**
  780. * This function get the distribution of levels based on hubsize
  781. *
  782. * @returns {Object}
  783. * @private
  784. */
  785. _getDistribution() {
  786. let distribution = {};
  787. let nodeId, node;
  788. // 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.
  789. // the fix of X is removed after the x value has been set.
  790. for (nodeId in this.body.nodes) {
  791. if (this.body.nodes.hasOwnProperty(nodeId)) {
  792. node = this.body.nodes[nodeId];
  793. let level = this.hierarchicalLevels[nodeId] === undefined ? 0 : this.hierarchicalLevels[nodeId];
  794. if (this.options.hierarchical.direction === 'UD' || this.options.hierarchical.direction === 'DU') {
  795. node.y = this.options.hierarchical.levelSeparation * level;
  796. node.options.fixed.y = true;
  797. }
  798. else {
  799. node.x = this.options.hierarchical.levelSeparation * level;
  800. node.options.fixed.x = true;
  801. }
  802. if (distribution[level] === undefined) {
  803. distribution[level] = {};
  804. }
  805. distribution[level][nodeId] = node;
  806. }
  807. }
  808. return distribution;
  809. }
  810. /**
  811. * Get the hubsize from all remaining unlevelled nodes.
  812. *
  813. * @returns {number}
  814. * @private
  815. */
  816. _getHubSize() {
  817. let hubSize = 0;
  818. for (let nodeId in this.body.nodes) {
  819. if (this.body.nodes.hasOwnProperty(nodeId)) {
  820. let node = this.body.nodes[nodeId];
  821. if (this.hierarchicalLevels[nodeId] === undefined) {
  822. hubSize = node.edges.length < hubSize ? hubSize : node.edges.length;
  823. }
  824. }
  825. }
  826. return hubSize;
  827. }
  828. /**
  829. * this function allocates nodes in levels based on the recursive branching from the largest hubs.
  830. *
  831. * @param hubsize
  832. * @private
  833. */
  834. _determineLevelsByHubsize() {
  835. let hubSize = 1;
  836. let levelDownstream = (nodeA, nodeB) => {
  837. if (this.hierarchicalLevels[nodeB.id] === undefined) {
  838. // set initial level
  839. if (this.hierarchicalLevels[nodeA.id] === undefined) {
  840. this.hierarchicalLevels[nodeA.id] = 0;
  841. }
  842. // set level
  843. this.hierarchicalLevels[nodeB.id] = this.hierarchicalLevels[nodeA.id] + 1;
  844. }
  845. };
  846. while (hubSize > 0) {
  847. // determine hubs
  848. hubSize = this._getHubSize();
  849. if (hubSize === 0)
  850. break;
  851. for (let nodeId in this.body.nodes) {
  852. if (this.body.nodes.hasOwnProperty(nodeId)) {
  853. let node = this.body.nodes[nodeId];
  854. if (node.edges.length === hubSize) {
  855. this._crawlNetwork(levelDownstream,nodeId);
  856. }
  857. }
  858. }
  859. }
  860. }
  861. /**
  862. * TODO: release feature
  863. * @private
  864. */
  865. _determineLevelsCustomCallback() {
  866. let minLevel = 100000;
  867. // TODO: this should come from options.
  868. let customCallback = function(nodeA, nodeB, edge) {
  869. };
  870. let levelByDirection = (nodeA, nodeB, edge) => {
  871. let levelA = this.hierarchicalLevels[nodeA.id];
  872. // set initial level
  873. if (levelA === undefined) {this.hierarchicalLevels[nodeA.id] = minLevel;}
  874. let diff = customCallback(
  875. NetworkUtil.cloneOptions(nodeA,'node'),
  876. NetworkUtil.cloneOptions(nodeB,'node'),
  877. NetworkUtil.cloneOptions(edge,'edge')
  878. );
  879. this.hierarchicalLevels[nodeB.id] = this.hierarchicalLevels[nodeA.id] + diff;
  880. };
  881. this._crawlNetwork(levelByDirection);
  882. this._setMinLevelToZero();
  883. }
  884. /**
  885. * this function allocates nodes in levels based on the direction of the edges
  886. *
  887. * @param hubsize
  888. * @private
  889. */
  890. _determineLevelsDirected() {
  891. let minLevel = 10000;
  892. let levelByDirection = (nodeA, nodeB, edge) => {
  893. let levelA = this.hierarchicalLevels[nodeA.id];
  894. // set initial level
  895. if (levelA === undefined) {this.hierarchicalLevels[nodeA.id] = minLevel;}
  896. if (edge.toId == nodeB.id) {
  897. this.hierarchicalLevels[nodeB.id] = this.hierarchicalLevels[nodeA.id] + 1;
  898. }
  899. else {
  900. this.hierarchicalLevels[nodeB.id] = this.hierarchicalLevels[nodeA.id] - 1;
  901. }
  902. };
  903. this._crawlNetwork(levelByDirection);
  904. this._setMinLevelToZero();
  905. }
  906. /**
  907. * Small util method to set the minimum levels of the nodes to zero.
  908. * @private
  909. */
  910. _setMinLevelToZero() {
  911. let minLevel = 1e9;
  912. // get the minimum level
  913. for (let nodeId in this.body.nodes) {
  914. if (this.body.nodes.hasOwnProperty(nodeId)) {
  915. if (this.hierarchicalLevels[nodeId] !== undefined) {
  916. minLevel = Math.min(this.hierarchicalLevels[nodeId], minLevel);
  917. }
  918. }
  919. }
  920. // subtract the minimum from the set so we have a range starting from 0
  921. for (let nodeId in this.body.nodes) {
  922. if (this.body.nodes.hasOwnProperty(nodeId)) {
  923. if (this.hierarchicalLevels[nodeId] !== undefined) {
  924. this.hierarchicalLevels[nodeId] -= minLevel;
  925. }
  926. }
  927. }
  928. }
  929. /**
  930. * Update the bookkeeping of parent and child.
  931. * @private
  932. */
  933. _generateMap() {
  934. let fillInRelations = (parentNode, childNode) => {
  935. if (this.hierarchicalLevels[childNode.id] > this.hierarchicalLevels[parentNode.id]) {
  936. let parentNodeId = parentNode.id;
  937. let childNodeId = childNode.id;
  938. if (this.hierarchicalParents[parentNodeId] === undefined) {
  939. this.hierarchicalParents[parentNodeId] = {children: [], amount: 0};
  940. }
  941. this.hierarchicalParents[parentNodeId].children.push(childNodeId);
  942. if (this.hierarchicalChildren[childNodeId] === undefined) {
  943. this.hierarchicalChildren[childNodeId] = {parents: [], amount: 0};
  944. }
  945. this.hierarchicalChildren[childNodeId].parents.push(parentNodeId);
  946. }
  947. };
  948. this._crawlNetwork(fillInRelations);
  949. }
  950. /**
  951. * Crawl over the entire network and use a callback on each node couple that is connected to each other.
  952. * @param callback | will receive nodeA nodeB and the connecting edge. A and B are unique.
  953. * @param startingNodeId
  954. * @private
  955. */
  956. _crawlNetwork(callback = function() {}, startingNodeId) {
  957. let progress = {};
  958. let crawler = (node) => {
  959. if (progress[node.id] === undefined) {
  960. progress[node.id] = true;
  961. let childNode;
  962. for (let i = 0; i < node.edges.length; i++) {
  963. if (node.edges[i].connected === true) {
  964. if (node.edges[i].toId === node.id) {
  965. childNode = node.edges[i].from;
  966. }
  967. else {
  968. childNode = node.edges[i].to;
  969. }
  970. if (node.id !== childNode.id) {
  971. callback(node, childNode, node.edges[i]);
  972. crawler(childNode);
  973. }
  974. }
  975. }
  976. }
  977. };
  978. // we can crawl from a specific node or over all nodes.
  979. if (startingNodeId === undefined) {
  980. for (let i = 0; i < this.body.nodeIndices.length; i++) {
  981. let node = this.body.nodes[this.body.nodeIndices[i]];
  982. crawler(node);
  983. }
  984. }
  985. else {
  986. let node = this.body.nodes[startingNodeId];
  987. if (node === undefined) {
  988. console.error("Node not found:", startingNodeId);
  989. return;
  990. }
  991. crawler(node);
  992. }
  993. }
  994. /**
  995. * This is a recursively called function to enumerate the branches from the largest hubs and place the nodes
  996. * on a X position that ensures there will be no overlap.
  997. *
  998. * @param parentId
  999. * @param parentLevel
  1000. * @private
  1001. */
  1002. _placeBranchNodes(parentId, parentLevel) {
  1003. // if this is not a parent, cancel the placing. This can happen with multiple parents to one child.
  1004. if (this.hierarchicalParents[parentId] === undefined) {
  1005. return;
  1006. }
  1007. // get a list of childNodes
  1008. let childNodes = [];
  1009. for (let i = 0; i < this.hierarchicalParents[parentId].children.length; i++) {
  1010. childNodes.push(this.body.nodes[this.hierarchicalParents[parentId].children[i]]);
  1011. }
  1012. // use the positions to order the nodes.
  1013. this._sortNodeArray(childNodes);
  1014. // position the childNodes
  1015. for (let i = 0; i < childNodes.length; i++) {
  1016. let childNode = childNodes[i];
  1017. let childNodeLevel = this.hierarchicalLevels[childNode.id];
  1018. // check if the child node is below the parent node and if it has already been positioned.
  1019. if (childNodeLevel > parentLevel && this.positionedNodes[childNode.id] === undefined) {
  1020. // get the amount of space required for this node. If parent the width is based on the amount of children.
  1021. let pos;
  1022. // 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
  1023. if (i === 0) {pos = this._getPositionForHierarchy(this.body.nodes[parentId]);}
  1024. else {pos = this._getPositionForHierarchy(childNodes[i-1]) + this.options.hierarchical.nodeSpacing;}
  1025. this._setPositionForHierarchy(childNode, pos, childNodeLevel);
  1026. // if overlap has been detected, we shift the branch
  1027. if (this.lastNodeOnLevel[childNodeLevel] !== undefined) {
  1028. let previousPos = this._getPositionForHierarchy(this.body.nodes[this.lastNodeOnLevel[childNodeLevel]]);
  1029. if (pos - previousPos < this.options.hierarchical.nodeSpacing) {
  1030. let diff = (previousPos + this.options.hierarchical.nodeSpacing) - pos;
  1031. let sharedParent = this._findCommonParent(this.lastNodeOnLevel[childNodeLevel], childNode.id);
  1032. this._shiftBlock(sharedParent.withChild, diff);
  1033. }
  1034. }
  1035. // store change in position.
  1036. this.lastNodeOnLevel[childNodeLevel] = childNode.id;
  1037. this.positionedNodes[childNode.id] = true;
  1038. this._placeBranchNodes(childNode.id, childNodeLevel);
  1039. }
  1040. else {
  1041. return;
  1042. }
  1043. }
  1044. // center the parent nodes.
  1045. let minPos = 1e9;
  1046. let maxPos = -1e9;
  1047. for (let i = 0; i < childNodes.length; i++) {
  1048. let childNodeId = childNodes[i].id;
  1049. minPos = Math.min(minPos, this._getPositionForHierarchy(this.body.nodes[childNodeId]));
  1050. maxPos = Math.max(maxPos, this._getPositionForHierarchy(this.body.nodes[childNodeId]));
  1051. }
  1052. this._setPositionForHierarchy(this.body.nodes[parentId], 0.5 * (minPos + maxPos), parentLevel);
  1053. }
  1054. /**
  1055. * Shift a branch a certain distance
  1056. * @param parentId
  1057. * @param diff
  1058. * @private
  1059. */
  1060. _shiftBlock(parentId, diff) {
  1061. if (this.options.hierarchical.direction === 'UD' || this.options.hierarchical.direction === 'DU') {
  1062. this.body.nodes[parentId].x += diff;
  1063. }
  1064. else {
  1065. this.body.nodes[parentId].y += diff;
  1066. }
  1067. if (this.hierarchicalParents[parentId] !== undefined) {
  1068. for (let i = 0; i < this.hierarchicalParents[parentId].children.length; i++) {
  1069. this._shiftBlock(this.hierarchicalParents[parentId].children[i], diff);
  1070. }
  1071. }
  1072. }
  1073. /**
  1074. * Find a common parent between branches.
  1075. * @param childA
  1076. * @param childB
  1077. * @returns {{foundParent, withChild}}
  1078. * @private
  1079. */
  1080. _findCommonParent(childA,childB) {
  1081. let parents = {};
  1082. let iterateParents = (parents,child) => {
  1083. if (this.hierarchicalChildren[child] !== undefined) {
  1084. for (let i = 0; i < this.hierarchicalChildren[child].parents.length; i++) {
  1085. let parent = this.hierarchicalChildren[child].parents[i];
  1086. parents[parent] = true;
  1087. iterateParents(parents, parent)
  1088. }
  1089. }
  1090. };
  1091. let findParent = (parents, child) => {
  1092. if (this.hierarchicalChildren[child] !== undefined) {
  1093. for (let i = 0; i < this.hierarchicalChildren[child].parents.length; i++) {
  1094. let parent = this.hierarchicalChildren[child].parents[i];
  1095. if (parents[parent] !== undefined) {
  1096. return {foundParent:parent, withChild:child};
  1097. }
  1098. let branch = findParent(parents, parent);
  1099. if (branch.foundParent !== null) {
  1100. return branch;
  1101. }
  1102. }
  1103. }
  1104. return {foundParent:null, withChild:child};
  1105. };
  1106. iterateParents(parents, childA);
  1107. return findParent(parents, childB);
  1108. }
  1109. /**
  1110. * Abstract the getting of the position so we won't have to repeat the check for direction all the time
  1111. * @param node
  1112. * @param position
  1113. * @param level
  1114. * @private
  1115. */
  1116. _setPositionForHierarchy(node, position, level, doNotUpdate = false) {
  1117. if (doNotUpdate !== true) {
  1118. if (this.distributionOrdering[level] === undefined) {
  1119. this.distributionOrdering[level] = [];
  1120. this.distributionOrderingPresence[level] = {};
  1121. }
  1122. if (this.distributionOrderingPresence[level][node.id] === undefined) {
  1123. this.distributionOrdering[level].push(node);
  1124. this.distributionIndex[node.id] = this.distributionOrdering[level].length - 1;
  1125. }
  1126. this.distributionOrderingPresence[level][node.id] = true;
  1127. if (this.hierarchicalTrees[node.id] === undefined) {
  1128. if (this.hierarchicalChildren[node.id] !== undefined) {
  1129. let tree = 1;
  1130. // get the lowest tree denominator.
  1131. for (let i = 0; i < this.hierarchicalChildren[node.id].parents.length; i++) {
  1132. let parentId = this.hierarchicalChildren[node.id].parents[i];
  1133. if (this.hierarchicalTrees[parentId] !== undefined) {
  1134. //tree = Math.min(tree,this.hierarchicalTrees[parentId]);
  1135. tree = this.hierarchicalTrees[parentId];
  1136. }
  1137. }
  1138. //for (let i = 0; i < this.hierarchicalChildren.parents.length; i++) {
  1139. // let parentId = this.hierarchicalChildren.parents[i];
  1140. // this.hierarchicalTrees[parentId] = tree;
  1141. //}
  1142. this.hierarchicalTrees[node.id] = tree;
  1143. }
  1144. else {
  1145. this.hierarchicalTrees[node.id] = ++this.treeIndex;
  1146. }
  1147. }
  1148. }
  1149. if (this.options.hierarchical.direction === 'UD' || this.options.hierarchical.direction === 'DU') {
  1150. node.x = position;
  1151. }
  1152. else {
  1153. node.y = position;
  1154. }
  1155. }
  1156. /**
  1157. * Abstract the getting of the position of a node so we do not have to repeat the direction check all the time.
  1158. * @param node
  1159. * @returns {number|*}
  1160. * @private
  1161. */
  1162. _getPositionForHierarchy(node) {
  1163. if (this.options.hierarchical.direction === 'UD' || this.options.hierarchical.direction === 'DU') {
  1164. return node.x;
  1165. }
  1166. else {
  1167. return node.y;
  1168. }
  1169. }
  1170. /**
  1171. * Use the x or y value to sort the array, allowing users to specify order.
  1172. * @param nodeArray
  1173. * @private
  1174. */
  1175. _sortNodeArray(nodeArray) {
  1176. if (nodeArray.length > 1) {
  1177. if (this.options.hierarchical.direction === 'UD' || this.options.hierarchical.direction === 'DU') {
  1178. nodeArray.sort(function (a, b) {
  1179. return a.x - b.x;
  1180. })
  1181. }
  1182. else {
  1183. nodeArray.sort(function (a, b) {
  1184. return a.y - b.y;
  1185. })
  1186. }
  1187. }
  1188. }
  1189. }
  1190. export default LayoutEngine;