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.

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