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.

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