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.

1308 lines
46 KiB

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