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.

1360 lines
47 KiB

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