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.

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