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.

511 lines
16 KiB

10 years ago
10 years ago
10 years ago
  1. // Load custom shapes into CanvasRenderingContext2D
  2. require('./shapes');
  3. var Emitter = require('emitter-component');
  4. var Hammer = require('../module/hammer');
  5. var util = require('../util');
  6. var DataSet = require('../DataSet');
  7. var DataView = require('../DataView');
  8. var dotparser = require('./dotparser');
  9. var gephiParser = require('./gephiParser');
  10. var Images = require('./Images');
  11. var Activator = require('../shared/Activator');
  12. import Groups from './modules/Groups';
  13. import NodesHandler from './modules/NodesHandler';
  14. import EdgesHandler from './modules/EdgesHandler';
  15. import PhysicsEngine from './modules/PhysicsEngine';
  16. import ClusterEngine from './modules/Clustering';
  17. import CanvasRenderer from './modules/CanvasRenderer';
  18. import Canvas from './modules/Canvas';
  19. import View from './modules/View';
  20. import InteractionHandler from './modules/InteractionHandler';
  21. import SelectionHandler from "./modules/SelectionHandler";
  22. import LayoutEngine from "./modules/LayoutEngine";
  23. import ManipulationSystem from "./modules/ManipulationSystem";
  24. import ConfigurationSystem from "./modules/ConfigurationSystem";
  25. /**
  26. * @constructor Network
  27. * Create a network visualization, displaying nodes and edges.
  28. *
  29. * @param {Element} container The DOM element in which the Network will
  30. * be created. Normally a div element.
  31. * @param {Object} data An object containing parameters
  32. * {Array} nodes
  33. * {Array} edges
  34. * @param {Object} options Options
  35. */
  36. function Network (container, data, options) {
  37. if (!(this instanceof Network)) {
  38. throw new SyntaxError('Constructor must be called with the new operator');
  39. }
  40. // set constant values
  41. this.options = {};
  42. this.defaultOptions = {
  43. clickToUse: false
  44. };
  45. util.extend(this.options, this.defaultOptions);
  46. // containers for nodes and edges
  47. this.body = {
  48. nodes: {},
  49. nodeIndices: [],
  50. edges: {},
  51. edgeIndices: [],
  52. data: {
  53. nodes: null, // A DataSet or DataView
  54. edges: null // A DataSet or DataView
  55. },
  56. functions:{
  57. createNode: () => {},
  58. createEdge: () => {},
  59. getPointer: () => {}
  60. },
  61. emitter: {
  62. on: this.on.bind(this),
  63. off: this.off.bind(this),
  64. emit: this.emit.bind(this),
  65. once: this.once.bind(this)
  66. },
  67. eventListeners: {
  68. onTap: function() {},
  69. onTouch: function() {},
  70. onDoubleTap: function() {},
  71. onHold: function() {},
  72. onDragStart: function() {},
  73. onDrag: function() {},
  74. onDragEnd: function() {},
  75. onMouseWheel: function() {},
  76. onPinch: function() {},
  77. onMouseMove: function() {},
  78. onRelease: function() {}
  79. },
  80. container: container,
  81. view: {
  82. scale:1,
  83. translation:{x:0,y:0}
  84. }
  85. };
  86. // bind the event listeners
  87. this.bindEventListeners();
  88. // setting up all modules
  89. var images = new Images(() => this.body.emitter.emit("_requestRedraw")); // object with images
  90. this.groups = new Groups(); // object with groups
  91. this.canvas = new Canvas(this.body); // DOM handler
  92. this.selectionHandler = new SelectionHandler(this.body, this.canvas); // Selection handler
  93. this.interactionHandler = new InteractionHandler(this.body, this.canvas, this.selectionHandler); // Interaction handler handles all the hammer bindings (that are bound by canvas), key
  94. this.view = new View(this.body, this.canvas); // camera handler, does animations and zooms
  95. this.renderer = new CanvasRenderer(this.body, this.canvas); // renderer, starts renderloop, has events that modules can hook into
  96. this.physics = new PhysicsEngine(this.body); // physics engine, does all the simulations
  97. this.layoutEngine = new LayoutEngine(this.body); // layout engine for inital layout and hierarchical layout
  98. this.clustering = new ClusterEngine(this.body); // clustering api
  99. this.manipulation = new ManipulationSystem(this.body, this.canvas, this.selectionHandler); // data manipulation system
  100. this.nodesHandler = new NodesHandler(this.body, images, this.groups, this.layoutEngine); // Handle adding, deleting and updating of nodes as well as global options
  101. this.edgesHandler = new EdgesHandler(this.body, images, this.groups); // Handle adding, deleting and updating of edges as well as global options
  102. this.configurationSystem = new ConfigurationSystem(this);
  103. // create the DOM elements
  104. this.canvas.create();
  105. // apply options
  106. this.setOptions(options);
  107. // load data (the disable start variable will be the same as the enabled clustering)
  108. this.setData(data);
  109. }
  110. // Extend Network with an Emitter mixin
  111. Emitter(Network.prototype);
  112. /**
  113. * Set options
  114. * @param {Object} options
  115. */
  116. Network.prototype.setOptions = function (options) {
  117. if (options !== undefined) {
  118. // the hierarchical system can adapt the edges and the physics to it's own options because not all combinations work with the hierarichical system.
  119. options = this.layoutEngine.setOptions(options.layout, options);
  120. // pass the options to the modules
  121. this.groups.setOptions(options.groups);
  122. this.nodesHandler.setOptions(options.nodes);
  123. this.edgesHandler.setOptions(options.edges);
  124. this.physics.setOptions(options.physics);
  125. this.canvas.setOptions(options.canvas);
  126. this.renderer.setOptions(options.rendering);
  127. this.view.setOptions(options.view);
  128. this.interactionHandler.setOptions(options.interaction);
  129. this.selectionHandler.setOptions(options.selection);
  130. this.clustering.setOptions(options.clustering);
  131. this.manipulation.setOptions(options.manipulation);
  132. this.configurationSystem.setOptions(options);
  133. // handle network global options
  134. if (options.clickToUse !== undefined) {
  135. if (options.clickToUse === true) {
  136. if (this.activator === undefined) {
  137. this.activator = new Activator(this.frame);
  138. this.activator.on('change', this._createKeyBinds.bind(this));
  139. }
  140. }
  141. else {
  142. if (this.activator !== undefined) {
  143. this.activator.destroy();
  144. delete this.activator;
  145. }
  146. this.body.emitter.emit("activate");
  147. }
  148. }
  149. else {
  150. this.body.emitter.emit("activate");
  151. }
  152. this.canvas.setSize();
  153. // start the physics simulation. Can be safely called multiple times.
  154. this.body.emitter.emit("startSimulation");
  155. this.body.emitter.emit("_requestRedraw");
  156. }
  157. };
  158. /**
  159. * Update the this.body.nodeIndices with the most recent node index list
  160. * @private
  161. */
  162. Network.prototype._updateVisibleIndices = function() {
  163. let nodes = this.body.nodes;
  164. let edges = this.body.edges;
  165. this.body.nodeIndices = [];
  166. this.body.edgeIndices = [];
  167. for (let nodeId in nodes) {
  168. if (nodes.hasOwnProperty(nodeId)) {
  169. if (nodes[nodeId].options.hidden === false) {
  170. this.body.nodeIndices.push(nodeId);
  171. }
  172. }
  173. }
  174. for (let edgeId in edges) {
  175. if (edges.hasOwnProperty(edgeId)) {
  176. if (edges[edgeId].options.hidden === false) {
  177. this.body.edgeIndices.push(edgeId);
  178. }
  179. }
  180. }
  181. };
  182. Network.prototype.bindEventListeners = function() {
  183. // this event will trigger a rebuilding of the cache everything. Used when nodes or edges have been added or removed.
  184. this.body.emitter.on("_dataChanged", (params) => {
  185. // update shortcut lists
  186. this._updateVisibleIndices();
  187. this.physics.updatePhysicsIndices();
  188. // call the dataUpdated event because the only difference between the two is the updating of the indices
  189. this.body.emitter.emit("_dataUpdated");
  190. });
  191. // this is called when options of EXISTING nodes or edges have changed.
  192. this.body.emitter.on("_dataUpdated", () => {
  193. // update values
  194. this._updateValueRange(this.body.nodes);
  195. this._updateValueRange(this.body.edges);
  196. // start simulation (can be called safely, even if already running)
  197. this.body.emitter.emit("startSimulation");
  198. });
  199. }
  200. /**
  201. * Set nodes and edges, and optionally options as well.
  202. *
  203. * @param {Object} data Object containing parameters:
  204. * {Array | DataSet | DataView} [nodes] Array with nodes
  205. * {Array | DataSet | DataView} [edges] Array with edges
  206. * {String} [dot] String containing data in DOT format
  207. * {String} [gephi] String containing data in gephi JSON format
  208. * {Options} [options] Object with options
  209. * @param {Boolean} [disableStart] | optional: disable the calling of the start function.
  210. */
  211. Network.prototype.setData = function(data) {
  212. // reset the physics engine.
  213. this.body.emitter.emit("resetPhysics");
  214. this.body.emitter.emit("_resetData");
  215. // unselect all to ensure no selections from old data are carried over.
  216. this.selectionHandler.unselectAll();
  217. if (data && data.dot && (data.nodes || data.edges)) {
  218. throw new SyntaxError('Data must contain either parameter "dot" or ' +
  219. ' parameter pair "nodes" and "edges", but not both.');
  220. }
  221. // set options
  222. this.setOptions(data && data.options);
  223. // set all data
  224. if (data && data.dot) {
  225. // parse DOT file
  226. if(data && data.dot) {
  227. var dotData = dotparser.DOTToGraph(data.dot);
  228. this.setData(dotData);
  229. return;
  230. }
  231. }
  232. else if (data && data.gephi) {
  233. // parse DOT file
  234. if(data && data.gephi) {
  235. var gephiData = gephiParser.parseGephi(data.gephi);
  236. this.setData(gephiData);
  237. return;
  238. }
  239. }
  240. else {
  241. this.nodesHandler.setData(data && data.nodes, true);
  242. this.edgesHandler.setData(data && data.edges, true);
  243. }
  244. // emit change in data
  245. this.body.emitter.emit("_dataChanged");
  246. // find a stable position or start animating to a stable position
  247. this.body.emitter.emit("initPhysics");
  248. };
  249. /**
  250. * Cleans up all bindings of the network, removing it fully from the memory IF the variable is set to null after calling this function.
  251. * var network = new vis.Network(..);
  252. * network.destroy();
  253. * network = null;
  254. */
  255. Network.prototype.destroy = function() {
  256. this.body.emitter.emit("destroy");
  257. // clear events
  258. this.body.emitter.off();
  259. // remove the container and everything inside it recursively
  260. util.recursiveDOMDelete(this.body.container);
  261. };
  262. /**
  263. * Update the values of all object in the given array according to the current
  264. * value range of the objects in the array.
  265. * @param {Object} obj An object containing a set of Edges or Nodes
  266. * The objects must have a method getValue() and
  267. * setValueRange(min, max).
  268. * @private
  269. */
  270. Network.prototype._updateValueRange = function(obj) {
  271. var id;
  272. // determine the range of the objects
  273. var valueMin = undefined;
  274. var valueMax = undefined;
  275. var valueTotal = 0;
  276. for (id in obj) {
  277. if (obj.hasOwnProperty(id)) {
  278. var value = obj[id].getValue();
  279. if (value !== undefined) {
  280. valueMin = (valueMin === undefined) ? value : Math.min(value, valueMin);
  281. valueMax = (valueMax === undefined) ? value : Math.max(value, valueMax);
  282. valueTotal += value;
  283. }
  284. }
  285. }
  286. // adjust the range of all objects
  287. if (valueMin !== undefined && valueMax !== undefined) {
  288. for (id in obj) {
  289. if (obj.hasOwnProperty(id)) {
  290. obj[id].setValueRange(valueMin, valueMax, valueTotal);
  291. }
  292. }
  293. }
  294. };
  295. /**
  296. * Scale the network
  297. * @param {Number} scale Scaling factor 1.0 is unscaled
  298. * @private
  299. */
  300. Network.prototype._setScale = function(scale) {
  301. this.body.view.scale = scale;
  302. };
  303. /**
  304. * Get the current scale of the network
  305. * @return {Number} scale Scaling factor 1.0 is unscaled
  306. * @private
  307. */
  308. Network.prototype._getScale = function() {
  309. return this.body.view.scale;
  310. };
  311. /**
  312. * Load the XY positions of the nodes into the dataset.
  313. */
  314. Network.prototype.storePositions = function() {
  315. // todo: incorporate fixed instead of allowedtomove, add support for clusters and hierarchical.
  316. var dataArray = [];
  317. for (var nodeId in this.body.nodes) {
  318. if (this.body.nodes.hasOwnProperty(nodeId)) {
  319. var node = this.body.nodes[nodeId];
  320. var allowedToMoveX = !this.body.nodes.xFixed;
  321. var allowedToMoveY = !this.body.nodes.yFixed;
  322. if (this.body.data.nodes._data[nodeId].x != Math.round(node.x) || this.body.data.nodes._data[nodeId].y != Math.round(node.y)) {
  323. dataArray.push({id:nodeId,x:Math.round(node.x),y:Math.round(node.y),allowedToMoveX:allowedToMoveX,allowedToMoveY:allowedToMoveY});
  324. }
  325. }
  326. }
  327. this.body.data.nodes.update(dataArray);
  328. };
  329. /**
  330. * Return the positions of the nodes.
  331. */
  332. Network.prototype.getPositions = function(ids) {
  333. var dataArray = {};
  334. if (ids !== undefined) {
  335. if (Array.isArray(ids) == true) {
  336. for (var i = 0; i < ids.length; i++) {
  337. if (this.body.nodes[ids[i]] !== undefined) {
  338. var node = this.body.nodes[ids[i]];
  339. dataArray[ids[i]] = {x: Math.round(node.x), y: Math.round(node.y)};
  340. }
  341. }
  342. }
  343. else {
  344. if (this.body.nodes[ids] !== undefined) {
  345. var node = this.body.nodes[ids];
  346. dataArray[ids] = {x: Math.round(node.x), y: Math.round(node.y)};
  347. }
  348. }
  349. }
  350. else {
  351. for (var nodeId in this.body.nodes) {
  352. if (this.body.nodes.hasOwnProperty(nodeId)) {
  353. var node = this.body.nodes[nodeId];
  354. dataArray[nodeId] = {x: Math.round(node.x), y: Math.round(node.y)};
  355. }
  356. }
  357. }
  358. return dataArray;
  359. };
  360. /**
  361. * Returns true when the Network is active.
  362. * @returns {boolean}
  363. */
  364. Network.prototype.isActive = function () {
  365. return !this.activator || this.activator.active;
  366. };
  367. /**
  368. * Sets the scale
  369. * @returns {Number}
  370. */
  371. Network.prototype.setScale = function () {
  372. return this._setScale();
  373. };
  374. /**
  375. * Returns the scale
  376. * @returns {Number}
  377. */
  378. Network.prototype.getScale = function () {
  379. return this._getScale();
  380. };
  381. /**
  382. * Check if a node is a cluster.
  383. * @param nodeId
  384. * @returns {*}
  385. */
  386. Network.prototype.isCluster = function(nodeId) {
  387. if (this.body.nodes[nodeId] !== undefined) {
  388. return this.body.nodes[nodeId].isCluster;
  389. }
  390. else {
  391. console.log("Node does not exist.")
  392. return false;
  393. }
  394. };
  395. /**
  396. * Returns the scale
  397. * @returns {Number}
  398. */
  399. Network.prototype.getCenterCoordinates = function () {
  400. return this.DOMtoCanvas({x: 0.5 * this.frame.canvas.clientWidth, y: 0.5 * this.frame.canvas.clientHeight});
  401. };
  402. Network.prototype.getBoundingBox = function(nodeId) {
  403. if (this.body.nodes[nodeId] !== undefined) {
  404. return this.body.nodes[nodeId].boundingBox;
  405. }
  406. }
  407. Network.prototype.getConnectedNodes = function(nodeId) {
  408. var nodeList = [];
  409. if (this.body.nodes[nodeId] !== undefined) {
  410. var node = this.body.nodes[nodeId];
  411. var nodeObj = {nodeId : true}; // used to quickly check if node already exists
  412. for (var i = 0; i < node.edges.length; i++) {
  413. var edge = node.edges[i];
  414. if (edge.toId == nodeId) {
  415. if (nodeObj[edge.fromId] === undefined) {
  416. nodeList.push(edge.fromId);
  417. nodeObj[edge.fromId] = true;
  418. }
  419. }
  420. else if (edge.fromId == nodeId) {
  421. if (nodeObj[edge.toId] === undefined) {
  422. nodeList.push(edge.toId)
  423. nodeObj[edge.toId] = true;
  424. }
  425. }
  426. }
  427. }
  428. return nodeList;
  429. }
  430. Network.prototype.getEdgesFromNode = function(nodeId) {
  431. var edgesList = [];
  432. if (this.body.nodes[nodeId] !== undefined) {
  433. var node = this.body.nodes[nodeId];
  434. for (var i = 0; i < node.edges.length; i++) {
  435. edgesList.push(node.edges[i].id);
  436. }
  437. }
  438. return edgesList;
  439. }
  440. Network.prototype.generateColorObject = function(color) {
  441. return util.parseColor(color);
  442. }
  443. module.exports = Network;