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.

1380 lines
47 KiB

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