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.

1392 lines
48 KiB

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