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.

1362 lines
47 KiB

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