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.

1504 lines
50 KiB

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