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.

1376 lines
47 KiB

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