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.initialRandomSeed = 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. this.randomSeed = this.initialRandomSeed;
  117. for (let i = 0; i < nodesArray.length; i++) {
  118. let node = nodesArray[i];
  119. if ((!node.isFixed()) && (node.x === undefined || node.y === undefined)) {
  120. let radius = 10 * 0.1 * nodesArray.length + 10;
  121. let angle = 2 * Math.PI * this.seededRandom();
  122. if (node.options.fixed.x === false) {
  123. node.x = radius * Math.cos(angle);
  124. }
  125. if (node.options.fixed.x === false) {
  126. node.y = radius * Math.sin(angle);
  127. }
  128. }
  129. }
  130. }
  131. }
  132. getSeed() {
  133. return this.initialRandomSeed;
  134. }
  135. /**
  136. * This is the main function to layout the nodes in a hierarchical way.
  137. * It checks if the node details are supplied correctly
  138. *
  139. * @private
  140. */
  141. setupHierarchicalLayout() {
  142. if (this.options.hierarchical.enabled === true && this.body.nodeIndices.length > 0) {
  143. // get the size of the largest hubs and check if the user has defined a level for a node.
  144. let node, nodeId;
  145. let definedLevel = false;
  146. let undefinedLevel = false;
  147. this.hierarchicalLevels = {};
  148. this.nodeSpacing = 100;
  149. for (nodeId in this.body.nodes) {
  150. if (this.body.nodes.hasOwnProperty(nodeId)) {
  151. node = this.body.nodes[nodeId];
  152. if (node.options.level !== undefined) {
  153. definedLevel = true;
  154. this.hierarchicalLevels[nodeId] = node.options.level;
  155. }
  156. else {
  157. undefinedLevel = true;
  158. }
  159. }
  160. }
  161. // if the user defined some levels but not all, alert and run without hierarchical layout
  162. if (undefinedLevel === true && definedLevel === true) {
  163. throw new Error('To use the hierarchical layout, nodes require either no predefined levels or levels have to be defined for all nodes.');
  164. return;
  165. }
  166. else {
  167. // setup the system to use hierarchical method.
  168. //this._changeConstants();
  169. // define levels if undefined by the users. Based on hubsize
  170. if (undefinedLevel === true) {
  171. if (this.options.hierarchical.sortMethod === 'hubsize') {
  172. this._determineLevelsByHubsize();
  173. }
  174. else if (this.options.hierarchical.sortMethod === 'directed' || 'direction') {
  175. this._determineLevelsDirected();
  176. }
  177. }
  178. // check the distribution of the nodes per level.
  179. let distribution = this._getDistribution();
  180. // place the nodes on the canvas.
  181. this._placeNodesByHierarchy(distribution);
  182. }
  183. }
  184. }
  185. /**
  186. * This function places the nodes on the canvas based on the hierarchial distribution.
  187. *
  188. * @param {Object} distribution | obtained by the function this._getDistribution()
  189. * @private
  190. */
  191. _placeNodesByHierarchy(distribution) {
  192. let nodeId, node;
  193. this.positionedNodes = {};
  194. // start placing all the level 0 nodes first. Then recursively position their branches.
  195. for (let level in distribution) {
  196. if (distribution.hasOwnProperty(level)) {
  197. for (nodeId in distribution[level].nodes) {
  198. if (distribution[level].nodes.hasOwnProperty(nodeId)) {
  199. node = distribution[level].nodes[nodeId];
  200. if (this.options.hierarchical.direction === 'UD' || this.options.hierarchical.direction === 'DU') {
  201. if (node.x === undefined) {node.x = distribution[level].distance;}
  202. distribution[level].distance = node.x + this.nodeSpacing;
  203. }
  204. else {
  205. if (node.y === undefined) {node.y = distribution[level].distance;}
  206. distribution[level].distance = node.y + this.nodeSpacing;
  207. }
  208. this.positionedNodes[nodeId] = true;
  209. this._placeBranchNodes(node.edges,node.id,distribution,level);
  210. }
  211. }
  212. }
  213. }
  214. }
  215. /**
  216. * This function get the distribution of levels based on hubsize
  217. *
  218. * @returns {Object}
  219. * @private
  220. */
  221. _getDistribution() {
  222. let distribution = {};
  223. let nodeId, node;
  224. // 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.
  225. // the fix of X is removed after the x value has been set.
  226. for (nodeId in this.body.nodes) {
  227. if (this.body.nodes.hasOwnProperty(nodeId)) {
  228. node = this.body.nodes[nodeId];
  229. let level = this.hierarchicalLevels[nodeId] === undefined ? 0 : this.hierarchicalLevels[nodeId];
  230. if (this.options.hierarchical.direction === 'UD' || this.options.hierarchical.direction === 'DU') {
  231. node.y = this.options.hierarchical.levelSeparation * level;
  232. node.options.fixed.y = true;
  233. }
  234. else {
  235. node.x = this.options.hierarchical.levelSeparation * level;
  236. node.options.fixed.x = true;
  237. }
  238. if (distribution[level] === undefined) {
  239. distribution[level] = {amount: 0, nodes: {}, distance: 0};
  240. }
  241. distribution[level].amount += 1;
  242. distribution[level].nodes[nodeId] = node;
  243. }
  244. }
  245. return distribution;
  246. }
  247. /**
  248. * Get the hubsize from all remaining unlevelled nodes.
  249. *
  250. * @returns {number}
  251. * @private
  252. */
  253. _getHubSize() {
  254. let hubSize = 0;
  255. for (let nodeId in this.body.nodes) {
  256. if (this.body.nodes.hasOwnProperty(nodeId)) {
  257. let node = this.body.nodes[nodeId];
  258. if (this.hierarchicalLevels[nodeId] === undefined) {
  259. hubSize = node.edges.length < hubSize ? hubSize : node.edges.length;
  260. }
  261. }
  262. }
  263. return hubSize;
  264. }
  265. /**
  266. * this function allocates nodes in levels based on the recursive branching from the largest hubs.
  267. *
  268. * @param hubsize
  269. * @private
  270. */
  271. _determineLevelsByHubsize() {
  272. let nodeId, node;
  273. let hubSize = 1;
  274. while (hubSize > 0) {
  275. // determine hubs
  276. hubSize = this._getHubSize();
  277. if (hubSize === 0)
  278. break;
  279. for (nodeId in this.body.nodes) {
  280. if (this.body.nodes.hasOwnProperty(nodeId)) {
  281. node = this.body.nodes[nodeId];
  282. if (node.edges.length === hubSize) {
  283. this._setLevel(0, node);
  284. }
  285. }
  286. }
  287. }
  288. }
  289. /**
  290. * this function is called recursively to enumerate the barnches of the largest hubs and give each node a level.
  291. *
  292. * @param level
  293. * @param edges
  294. * @param parentId
  295. * @private
  296. */
  297. _setLevel(level, node) {
  298. if (this.hierarchicalLevels[node.id] !== undefined)
  299. return;
  300. let childNode;
  301. this.hierarchicalLevels[node.id] = level;
  302. for (let i = 0; i < node.edges.length; i++) {
  303. if (node.edges[i].toId === node.id) {
  304. childNode = node.edges[i].from;
  305. }
  306. else {
  307. childNode = node.edges[i].to;
  308. }
  309. this._setLevel(level + 1, childNode);
  310. }
  311. }
  312. /**
  313. * this function allocates nodes in levels based on the direction of the edges
  314. *
  315. * @param hubsize
  316. * @private
  317. */
  318. _determineLevelsDirected() {
  319. let nodeId, node;
  320. let minLevel = 10000;
  321. // set first node to source
  322. for (nodeId in this.body.nodes) {
  323. if (this.body.nodes.hasOwnProperty(nodeId)) {
  324. node = this.body.nodes[nodeId];
  325. this._setLevelDirected(minLevel,node);
  326. }
  327. }
  328. // get the minimum level
  329. for (nodeId in this.body.nodes) {
  330. if (this.body.nodes.hasOwnProperty(nodeId)) {
  331. minLevel = this.hierarchicalLevels[nodeId] < minLevel ? this.hierarchicalLevels[nodeId] : minLevel;
  332. }
  333. }
  334. // subtract the minimum from the set so we have a range starting from 0
  335. for (nodeId in this.body.nodes) {
  336. if (this.body.nodes.hasOwnProperty(nodeId)) {
  337. this.hierarchicalLevels[nodeId] -= minLevel;
  338. }
  339. }
  340. }
  341. /**
  342. * this function is called recursively to enumerate the branched of the first node and give each node a level based on edge direction
  343. *
  344. * @param level
  345. * @param edges
  346. * @param parentId
  347. * @private
  348. */
  349. _setLevelDirected(level, node) {
  350. if (this.hierarchicalLevels[node.id] !== undefined)
  351. return;
  352. let childNode;
  353. this.hierarchicalLevels[node.id] = level;
  354. for (let i = 0; i < node.edges.length; i++) {
  355. if (node.edges[i].toId === node.id) {
  356. childNode = node.edges[i].from;
  357. this._setLevelDirected(level - 1, childNode);
  358. }
  359. else {
  360. childNode = node.edges[i].to;
  361. this._setLevelDirected(level + 1, childNode);
  362. }
  363. }
  364. }
  365. /**
  366. * This is a recursively called function to enumerate the branches from the largest hubs and place the nodes
  367. * on a X position that ensures there will be no overlap.
  368. *
  369. * @param edges
  370. * @param parentId
  371. * @param distribution
  372. * @param parentLevel
  373. * @private
  374. */
  375. _placeBranchNodes(edges, parentId, distribution, parentLevel) {
  376. for (let i = 0; i < edges.length; i++) {
  377. let childNode = undefined;
  378. let parentNode = undefined;
  379. if (edges[i].toId === parentId) {
  380. childNode = edges[i].from;
  381. parentNode = edges[i].to;
  382. }
  383. else {
  384. childNode = edges[i].to;
  385. parentNode = edges[i].from;
  386. }
  387. let childNodeLevel = this.hierarchicalLevels[childNode.id];
  388. if (this.positionedNodes[childNode.id] === undefined) {
  389. // if a node is conneceted to another node on the same level (or higher (means lower level))!, this is not handled here.
  390. if (childNodeLevel > parentLevel) {
  391. if (this.options.hierarchical.direction === 'UD' || this.options.hierarchical.direction === 'DU') {
  392. if (childNode.x === undefined) {
  393. childNode.x = Math.max(distribution[childNodeLevel].distance, parentNode.x);
  394. }
  395. distribution[childNodeLevel].distance = childNode.x + this.nodeSpacing;
  396. this.positionedNodes[childNode.id] = true;
  397. }
  398. else {
  399. if (childNode.y === undefined) {
  400. childNode.y = Math.max(distribution[childNodeLevel].distance, parentNode.y)
  401. }
  402. distribution[childNodeLevel].distance = childNode.y + this.nodeSpacing;
  403. }
  404. this.positionedNodes[childNode.id] = true;
  405. if (childNode.edges.length > 1) {
  406. this._placeBranchNodes(childNode.edges, childNode.id, distribution, childNodeLevel);
  407. }
  408. }
  409. }
  410. }
  411. }
  412. }
  413. export default LayoutEngine;