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.

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