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.

469 lines
15 KiB

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