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.

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