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.

467 lines
15 KiB

9 years ago
9 years ago
9 years ago
  1. var util = require('../../util');
  2. class LayoutEngine {
  3. constructor(body) {
  4. this.body = body;
  5. this.initialRandomSeed = Math.round(Math.random() * 1000000);
  6. this.randomSeed = this.initialRandomSeed;
  7. this.options = {};
  8. this.optionsBackup = {};
  9. this.defaultOptions = {
  10. randomSeed: undefined,
  11. hierarchical: {
  12. enabled:false,
  13. levelSeparation: 150,
  14. direction: 'UD', // UD, DU, LR, RL
  15. sortMethod: 'hubsize' // hubsize, directed
  16. }
  17. };
  18. util.extend(this.options, this.defaultOptions);
  19. this.hierarchicalLevels = {};
  20. this.bindEventListeners();
  21. }
  22. bindEventListeners() {
  23. this.body.emitter.on('_dataChanged', () => {
  24. this.setupHierarchicalLayout();
  25. });
  26. this.body.emitter.on('_resetHierarchicalLayout', () => {
  27. this.setupHierarchicalLayout();
  28. });
  29. }
  30. setOptions(options, allOptions) {
  31. if (options !== undefined) {
  32. let prevHierarchicalState = this.options.hierarchical.enabled;
  33. util.mergeOptions(this.options, options, 'hierarchical');
  34. if (options.randomSeed !== undefined) {
  35. this.randomSeed = options.randomSeed;
  36. }
  37. if (this.options.hierarchical.enabled === true) {
  38. // make sure the level seperation is the right way up
  39. if (this.options.hierarchical.direction === 'RL' || this.options.hierarchical.direction === 'DU') {
  40. if (this.options.hierarchical.levelSeparation > 0) {
  41. this.options.hierarchical.levelSeparation *= -1;
  42. }
  43. }
  44. else {
  45. if (this.options.hierarchical.levelSeparation < 0) {
  46. this.options.hierarchical.levelSeparation *= -1;
  47. }
  48. }
  49. this.body.emitter.emit('_resetHierarchicalLayout');
  50. // because the hierarchical system needs it's own physics and smooth curve settings, we adapt the other options if needed.
  51. return this.adaptAllOptions(allOptions);
  52. }
  53. else {
  54. if (prevHierarchicalState === true) {
  55. // refresh the overridden options for nodes and edges.
  56. this.body.emitter.emit('refresh');
  57. return util.deepExtend(allOptions,this.optionsBackup);
  58. }
  59. }
  60. }
  61. return allOptions;
  62. }
  63. adaptAllOptions(allOptions) {
  64. if (this.options.hierarchical.enabled === true) {
  65. // set the physics
  66. if (allOptions.physics === undefined || allOptions.physics === true) {
  67. allOptions.physics = {solver: 'hierarchicalRepulsion'};
  68. this.optionsBackup.physics = {solver:'barnesHut'};
  69. }
  70. else if (typeof options.physics === 'object') {
  71. this.optionsBackup.physics = {solver:'barnesHut'};
  72. if (options.physics.solver !== undefined) {
  73. this.optionsBackup.physics = {solver:options.physics.solver};
  74. }
  75. allOptions.physics['solver'] = 'hierarchicalRepulsion';
  76. }
  77. else if (options.physics !== false) {
  78. this.optionsBackup.physics = {solver:'barnesHut'};
  79. allOptions.physics['solver'] = 'hierarchicalRepulsion';
  80. }
  81. // get the type of static smooth curve in case it is required
  82. let type = 'horizontal';
  83. if (this.options.hierarchical.direction === 'RL' || this.options.hierarchical.direction === 'LR') {
  84. type = 'vertical';
  85. }
  86. // disable smooth curves if nothing is defined. If smooth curves have been turned on, turn them into static smooth curves.
  87. if (allOptions.edges === undefined) {
  88. this.optionsBackup.edges = {smooth:true, dynamic:true};
  89. allOptions.edges = {smooth: false};
  90. }
  91. else if (allOptions.edges.smooth === undefined) {
  92. this.optionsBackup.edges = {smooth:true, dynamic:true};
  93. allOptions.edges.smooth = false;
  94. }
  95. else {
  96. if (typeof allOptions.edges.smooth === 'boolean') {
  97. this.optionsBackup.edges = {smooth:allOptions.edges.smooth, dynamic:true};
  98. allOptions.edges.smooth = {enabled: allOptions.edges.smooth, dynamic: false, type:type}
  99. }
  100. else {
  101. this.optionsBackup.edges = {smooth: allOptions.edges.smooth.enabled === undefined ? true : allOptions.edges.smooth.enabled, dynamic:true};
  102. allOptions.edges.smooth = {enabled: allOptions.edges.smooth.enabled === undefined ? true : allOptions.edges.smooth.enabled, dynamic: false, type:type}
  103. }
  104. }
  105. // force all edges into static smooth curves. Only applies to edges that do not use the global options for smooth.
  106. this.body.emitter.emit('_forceDisableDynamicCurves', type);
  107. }
  108. return allOptions;
  109. }
  110. seededRandom() {
  111. var x = Math.sin(this.randomSeed++) * 10000;
  112. return x - Math.floor(x);
  113. }
  114. positionInitially(nodesArray) {
  115. if (this.options.hierarchical.enabled !== true) {
  116. for (let i = 0; i < nodesArray.length; i++) {
  117. let node = nodesArray[i];
  118. if ((!node.isFixed()) && (node.x === undefined || node.y === undefined)) {
  119. let radius = 10 * 0.1 * nodesArray.length + 10;
  120. let angle = 2 * Math.PI * this.seededRandom();
  121. if (node.options.fixed.x === false) {
  122. node.x = radius * Math.cos(angle);
  123. }
  124. if (node.options.fixed.x === false) {
  125. node.y = radius * Math.sin(angle);
  126. }
  127. }
  128. }
  129. }
  130. }
  131. getSeed() {
  132. return this.initialRandomSeed;
  133. }
  134. /**
  135. * This is the main function to layout the nodes in a hierarchical way.
  136. * It checks if the node details are supplied correctly
  137. *
  138. * @private
  139. */
  140. setupHierarchicalLayout() {
  141. if (this.options.hierarchical.enabled === true && this.body.nodeIndices.length > 0) {
  142. // get the size of the largest hubs and check if the user has defined a level for a node.
  143. let node, nodeId;
  144. let definedLevel = false;
  145. let undefinedLevel = false;
  146. this.hierarchicalLevels = {};
  147. this.nodeSpacing = 100;
  148. for (nodeId in this.body.nodes) {
  149. if (this.body.nodes.hasOwnProperty(nodeId)) {
  150. node = this.body.nodes[nodeId];
  151. if (node.options.level !== undefined) {
  152. definedLevel = true;
  153. this.hierarchicalLevels[nodeId] = node.options.level;
  154. }
  155. else {
  156. undefinedLevel = true;
  157. }
  158. }
  159. }
  160. // if the user defined some levels but not all, alert and run without hierarchical layout
  161. if (undefinedLevel === true && definedLevel === true) {
  162. throw new Error('To use the hierarchical layout, nodes require either no predefined levels or levels have to be defined for all nodes.');
  163. return;
  164. }
  165. else {
  166. // setup the system to use hierarchical method.
  167. //this._changeConstants();
  168. // define levels if undefined by the users. Based on hubsize
  169. if (undefinedLevel === true) {
  170. if (this.options.hierarchical.sortMethod === 'hubsize') {
  171. this._determineLevelsByHubsize();
  172. }
  173. else if (this.options.hierarchical.sortMethod === 'directed' || 'direction') {
  174. this._determineLevelsDirected();
  175. }
  176. }
  177. // check the distribution of the nodes per level.
  178. let distribution = this._getDistribution();
  179. // place the nodes on the canvas.
  180. this._placeNodesByHierarchy(distribution);
  181. }
  182. }
  183. }
  184. /**
  185. * This function places the nodes on the canvas based on the hierarchial distribution.
  186. *
  187. * @param {Object} distribution | obtained by the function this._getDistribution()
  188. * @private
  189. */
  190. _placeNodesByHierarchy(distribution) {
  191. let nodeId, node;
  192. this.positionedNodes = {};
  193. // start placing all the level 0 nodes first. Then recursively position their branches.
  194. for (let level in distribution) {
  195. if (distribution.hasOwnProperty(level)) {
  196. for (nodeId in distribution[level].nodes) {
  197. if (distribution[level].nodes.hasOwnProperty(nodeId)) {
  198. node = distribution[level].nodes[nodeId];
  199. if (this.options.hierarchical.direction === 'UD' || this.options.hierarchical.direction === 'DU') {
  200. if (node.x === undefined) {node.x = distribution[level].distance;}
  201. distribution[level].distance = node.x + this.nodeSpacing;
  202. }
  203. else {
  204. if (node.y === undefined) {node.y = distribution[level].distance;}
  205. distribution[level].distance = node.y + this.nodeSpacing;
  206. }
  207. this.positionedNodes[nodeId] = true;
  208. this._placeBranchNodes(node.edges,node.id,distribution,level);
  209. }
  210. }
  211. }
  212. }
  213. }
  214. /**
  215. * This function get the distribution of levels based on hubsize
  216. *
  217. * @returns {Object}
  218. * @private
  219. */
  220. _getDistribution() {
  221. let distribution = {};
  222. let nodeId, node;
  223. // 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.
  224. // the fix of X is removed after the x value has been set.
  225. for (nodeId in this.body.nodes) {
  226. if (this.body.nodes.hasOwnProperty(nodeId)) {
  227. node = this.body.nodes[nodeId];
  228. let level = this.hierarchicalLevels[nodeId] === undefined ? 0 : this.hierarchicalLevels[nodeId];
  229. if (this.options.hierarchical.direction === 'UD' || this.options.hierarchical.direction === 'DU') {
  230. node.y = this.options.hierarchical.levelSeparation * level;
  231. node.options.fixed.y = true;
  232. }
  233. else {
  234. node.x = this.options.hierarchical.levelSeparation * level;
  235. node.options.fixed.x = true;
  236. }
  237. if (distribution[level] === undefined) {
  238. distribution[level] = {amount: 0, nodes: {}, distance: 0};
  239. }
  240. distribution[level].amount += 1;
  241. distribution[level].nodes[nodeId] = node;
  242. }
  243. }
  244. return distribution;
  245. }
  246. /**
  247. * Get the hubsize from all remaining unlevelled nodes.
  248. *
  249. * @returns {number}
  250. * @private
  251. */
  252. _getHubSize() {
  253. let hubSize = 0;
  254. for (let nodeId in this.body.nodes) {
  255. if (this.body.nodes.hasOwnProperty(nodeId)) {
  256. let node = this.body.nodes[nodeId];
  257. if (this.hierarchicalLevels[nodeId] === undefined) {
  258. hubSize = node.edges.length < hubSize ? hubSize : node.edges.length;
  259. }
  260. }
  261. }
  262. return hubSize;
  263. }
  264. /**
  265. * this function allocates nodes in levels based on the recursive branching from the largest hubs.
  266. *
  267. * @param hubsize
  268. * @private
  269. */
  270. _determineLevelsByHubsize() {
  271. let nodeId, node;
  272. let hubSize = 1;
  273. while (hubSize > 0) {
  274. // determine hubs
  275. hubSize = this._getHubSize();
  276. if (hubSize === 0)
  277. break;
  278. for (nodeId in this.body.nodes) {
  279. if (this.body.nodes.hasOwnProperty(nodeId)) {
  280. node = this.body.nodes[nodeId];
  281. if (node.edges.length === hubSize) {
  282. this._setLevel(0, node);
  283. }
  284. }
  285. }
  286. }
  287. }
  288. /**
  289. * this function is called recursively to enumerate the barnches of the largest hubs and give each node a level.
  290. *
  291. * @param level
  292. * @param edges
  293. * @param parentId
  294. * @private
  295. */
  296. _setLevel(level, node) {
  297. if (this.hierarchicalLevels[node.id] !== undefined)
  298. return;
  299. let childNode;
  300. this.hierarchicalLevels[node.id] = level;
  301. for (let i = 0; i < node.edges.length; i++) {
  302. if (node.edges[i].toId === node.id) {
  303. childNode = node.edges[i].from;
  304. }
  305. else {
  306. childNode = node.edges[i].to;
  307. }
  308. this._setLevel(level + 1, childNode);
  309. }
  310. }
  311. /**
  312. * this function allocates nodes in levels based on the direction of the edges
  313. *
  314. * @param hubsize
  315. * @private
  316. */
  317. _determineLevelsDirected() {
  318. let nodeId, node;
  319. let minLevel = 10000;
  320. // set first node to source
  321. for (nodeId in this.body.nodes) {
  322. if (this.body.nodes.hasOwnProperty(nodeId)) {
  323. node = this.body.nodes[nodeId];
  324. this._setLevelDirected(minLevel,node);
  325. }
  326. }
  327. // get the minimum level
  328. for (nodeId in this.body.nodes) {
  329. if (this.body.nodes.hasOwnProperty(nodeId)) {
  330. minLevel = this.hierarchicalLevels[nodeId] < minLevel ? this.hierarchicalLevels[nodeId] : minLevel;
  331. }
  332. }
  333. // subtract the minimum from the set so we have a range starting from 0
  334. for (nodeId in this.body.nodes) {
  335. if (this.body.nodes.hasOwnProperty(nodeId)) {
  336. this.hierarchicalLevels[nodeId] -= minLevel;
  337. }
  338. }
  339. }
  340. /**
  341. * this function is called recursively to enumerate the branched of the first node and give each node a level based on edge direction
  342. *
  343. * @param level
  344. * @param edges
  345. * @param parentId
  346. * @private
  347. */
  348. _setLevelDirected(level, node) {
  349. if (this.hierarchicalLevels[node.id] !== undefined)
  350. return;
  351. let childNode;
  352. this.hierarchicalLevels[node.id] = level;
  353. for (let i = 0; i < node.edges.length; i++) {
  354. if (node.edges[i].toId === node.id) {
  355. childNode = node.edges[i].from;
  356. this._setLevelDirected(level - 1, childNode);
  357. }
  358. else {
  359. childNode = node.edges[i].to;
  360. this._setLevelDirected(level + 1, childNode);
  361. }
  362. }
  363. }
  364. /**
  365. * This is a recursively called function to enumerate the branches from the largest hubs and place the nodes
  366. * on a X position that ensures there will be no overlap.
  367. *
  368. * @param edges
  369. * @param parentId
  370. * @param distribution
  371. * @param parentLevel
  372. * @private
  373. */
  374. _placeBranchNodes(edges, parentId, distribution, parentLevel) {
  375. for (let i = 0; i < edges.length; i++) {
  376. let childNode = undefined;
  377. let parentNode = undefined;
  378. if (edges[i].toId === parentId) {
  379. childNode = edges[i].from;
  380. parentNode = edges[i].to;
  381. }
  382. else {
  383. childNode = edges[i].to;
  384. parentNode = edges[i].from;
  385. }
  386. let childNodeLevel = this.hierarchicalLevels[childNode.id];
  387. if (this.positionedNodes[childNode.id] === undefined) {
  388. // if a node is conneceted to another node on the same level (or higher (means lower level))!, this is not handled here.
  389. if (childNodeLevel > parentLevel) {
  390. if (this.options.hierarchical.direction === 'UD' || this.options.hierarchical.direction === 'DU') {
  391. if (childNode.x === undefined) {
  392. childNode.x = Math.max(distribution[childNodeLevel].distance, parentNode.x);
  393. }
  394. distribution[childNodeLevel].distance = childNode.x + this.nodeSpacing;
  395. this.positionedNodes[childNode.id] = true;
  396. }
  397. else {
  398. if (childNode.y === undefined) {
  399. childNode.y = Math.max(distribution[childNodeLevel].distance, parentNode.y)
  400. }
  401. distribution[childNodeLevel].distance = childNode.y + this.nodeSpacing;
  402. }
  403. this.positionedNodes[childNode.id] = true;
  404. if (childNode.edges.length > 1) {
  405. this._placeBranchNodes(childNode.edges, childNode.id, distribution, childNodeLevel);
  406. }
  407. }
  408. }
  409. }
  410. }
  411. }
  412. export default LayoutEngine;