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.

1363 lines
47 KiB

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