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.

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