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.

492 lines
16 KiB

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