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.

510 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. }
  156. };
  157. /**
  158. * Update the this.body.nodeIndices with the most recent node index list
  159. * @private
  160. */
  161. Network.prototype._updateVisibleIndices = function() {
  162. let nodes = this.body.nodes;
  163. let edges = this.body.edges;
  164. this.body.nodeIndices = [];
  165. this.body.edgeIndices = [];
  166. for (let nodeId in nodes) {
  167. if (nodes.hasOwnProperty(nodeId)) {
  168. if (nodes[nodeId].options.hidden === false) {
  169. this.body.nodeIndices.push(nodeId);
  170. }
  171. }
  172. }
  173. for (let edgeId in edges) {
  174. if (edges.hasOwnProperty(edgeId)) {
  175. if (edges[edgeId].options.hidden === false) {
  176. this.body.edgeIndices.push(edgeId);
  177. }
  178. }
  179. }
  180. };
  181. Network.prototype.bindEventListeners = function() {
  182. // this event will trigger a rebuilding of the cache everything. Used when nodes or edges have been added or removed.
  183. this.body.emitter.on("_dataChanged", (params) => {
  184. // update shortcut lists
  185. this._updateVisibleIndices();
  186. this.physics.updatePhysicsIndices();
  187. // call the dataUpdated event because the only difference between the two is the updating of the indices
  188. this.body.emitter.emit("_dataUpdated");
  189. });
  190. // this is called when options of EXISTING nodes or edges have changed.
  191. this.body.emitter.on("_dataUpdated", () => {
  192. // update values
  193. this._updateValueRange(this.body.nodes);
  194. this._updateValueRange(this.body.edges);
  195. // start simulation (can be called safely, even if already running)
  196. this.body.emitter.emit("startSimulation");
  197. });
  198. }
  199. /**
  200. * Set nodes and edges, and optionally options as well.
  201. *
  202. * @param {Object} data Object containing parameters:
  203. * {Array | DataSet | DataView} [nodes] Array with nodes
  204. * {Array | DataSet | DataView} [edges] Array with edges
  205. * {String} [dot] String containing data in DOT format
  206. * {String} [gephi] String containing data in gephi JSON format
  207. * {Options} [options] Object with options
  208. * @param {Boolean} [disableStart] | optional: disable the calling of the start function.
  209. */
  210. Network.prototype.setData = function(data) {
  211. // reset the physics engine.
  212. this.body.emitter.emit("resetPhysics");
  213. this.body.emitter.emit("_resetData");
  214. // unselect all to ensure no selections from old data are carried over.
  215. this.selectionHandler.unselectAll();
  216. if (data && data.dot && (data.nodes || data.edges)) {
  217. throw new SyntaxError('Data must contain either parameter "dot" or ' +
  218. ' parameter pair "nodes" and "edges", but not both.');
  219. }
  220. // set options
  221. this.setOptions(data && data.options);
  222. // set all data
  223. if (data && data.dot) {
  224. // parse DOT file
  225. if(data && data.dot) {
  226. var dotData = dotparser.DOTToGraph(data.dot);
  227. this.setData(dotData);
  228. return;
  229. }
  230. }
  231. else if (data && data.gephi) {
  232. // parse DOT file
  233. if(data && data.gephi) {
  234. var gephiData = gephiParser.parseGephi(data.gephi);
  235. this.setData(gephiData);
  236. return;
  237. }
  238. }
  239. else {
  240. this.nodesHandler.setData(data && data.nodes, true);
  241. this.edgesHandler.setData(data && data.edges, true);
  242. }
  243. // emit change in data
  244. this.body.emitter.emit("_dataChanged");
  245. // find a stable position or start animating to a stable position
  246. this.body.emitter.emit("initPhysics");
  247. };
  248. /**
  249. * Cleans up all bindings of the network, removing it fully from the memory IF the variable is set to null after calling this function.
  250. * var network = new vis.Network(..);
  251. * network.destroy();
  252. * network = null;
  253. */
  254. Network.prototype.destroy = function() {
  255. this.body.emitter.emit("destroy");
  256. // clear events
  257. this.body.emitter.off();
  258. // remove the container and everything inside it recursively
  259. util.recursiveDOMDelete(this.body.container);
  260. };
  261. /**
  262. * Update the values of all object in the given array according to the current
  263. * value range of the objects in the array.
  264. * @param {Object} obj An object containing a set of Edges or Nodes
  265. * The objects must have a method getValue() and
  266. * setValueRange(min, max).
  267. * @private
  268. */
  269. Network.prototype._updateValueRange = function(obj) {
  270. var id;
  271. // determine the range of the objects
  272. var valueMin = undefined;
  273. var valueMax = undefined;
  274. var valueTotal = 0;
  275. for (id in obj) {
  276. if (obj.hasOwnProperty(id)) {
  277. var value = obj[id].getValue();
  278. if (value !== undefined) {
  279. valueMin = (valueMin === undefined) ? value : Math.min(value, valueMin);
  280. valueMax = (valueMax === undefined) ? value : Math.max(value, valueMax);
  281. valueTotal += value;
  282. }
  283. }
  284. }
  285. // adjust the range of all objects
  286. if (valueMin !== undefined && valueMax !== undefined) {
  287. for (id in obj) {
  288. if (obj.hasOwnProperty(id)) {
  289. obj[id].setValueRange(valueMin, valueMax, valueTotal);
  290. }
  291. }
  292. }
  293. };
  294. /**
  295. * Scale the network
  296. * @param {Number} scale Scaling factor 1.0 is unscaled
  297. * @private
  298. */
  299. Network.prototype._setScale = function(scale) {
  300. this.body.view.scale = scale;
  301. };
  302. /**
  303. * Get the current scale of the network
  304. * @return {Number} scale Scaling factor 1.0 is unscaled
  305. * @private
  306. */
  307. Network.prototype._getScale = function() {
  308. return this.body.view.scale;
  309. };
  310. /**
  311. * Load the XY positions of the nodes into the dataset.
  312. */
  313. Network.prototype.storePositions = function() {
  314. // todo: incorporate fixed instead of allowedtomove, add support for clusters and hierarchical.
  315. var dataArray = [];
  316. for (var nodeId in this.body.nodes) {
  317. if (this.body.nodes.hasOwnProperty(nodeId)) {
  318. var node = this.body.nodes[nodeId];
  319. var allowedToMoveX = !this.body.nodes.xFixed;
  320. var allowedToMoveY = !this.body.nodes.yFixed;
  321. if (this.body.data.nodes._data[nodeId].x != Math.round(node.x) || this.body.data.nodes._data[nodeId].y != Math.round(node.y)) {
  322. dataArray.push({id:nodeId,x:Math.round(node.x),y:Math.round(node.y),allowedToMoveX:allowedToMoveX,allowedToMoveY:allowedToMoveY});
  323. }
  324. }
  325. }
  326. this.body.data.nodes.update(dataArray);
  327. };
  328. /**
  329. * Return the positions of the nodes.
  330. */
  331. Network.prototype.getPositions = function(ids) {
  332. var dataArray = {};
  333. if (ids !== undefined) {
  334. if (Array.isArray(ids) === true) {
  335. for (var i = 0; i < ids.length; i++) {
  336. if (this.body.nodes[ids[i]] !== undefined) {
  337. var node = this.body.nodes[ids[i]];
  338. dataArray[ids[i]] = {x: Math.round(node.x), y: Math.round(node.y)};
  339. }
  340. }
  341. }
  342. else {
  343. if (this.body.nodes[ids] !== undefined) {
  344. var node = this.body.nodes[ids];
  345. dataArray[ids] = {x: Math.round(node.x), y: Math.round(node.y)};
  346. }
  347. }
  348. }
  349. else {
  350. for (var nodeId in this.body.nodes) {
  351. if (this.body.nodes.hasOwnProperty(nodeId)) {
  352. var node = this.body.nodes[nodeId];
  353. dataArray[nodeId] = {x: Math.round(node.x), y: Math.round(node.y)};
  354. }
  355. }
  356. }
  357. return dataArray;
  358. };
  359. /**
  360. * Returns true when the Network is active.
  361. * @returns {boolean}
  362. */
  363. Network.prototype.isActive = function () {
  364. return !this.activator || this.activator.active;
  365. };
  366. /**
  367. * Sets the scale
  368. * @returns {Number}
  369. */
  370. Network.prototype.setScale = function () {
  371. return this._setScale();
  372. };
  373. /**
  374. * Returns the scale
  375. * @returns {Number}
  376. */
  377. Network.prototype.getScale = function () {
  378. return this._getScale();
  379. };
  380. /**
  381. * Check if a node is a cluster.
  382. * @param nodeId
  383. * @returns {*}
  384. */
  385. Network.prototype.isCluster = function(nodeId) {
  386. if (this.body.nodes[nodeId] !== undefined) {
  387. return this.body.nodes[nodeId].isCluster;
  388. }
  389. else {
  390. console.log("Node does not exist.")
  391. return false;
  392. }
  393. };
  394. /**
  395. * Returns the scale
  396. * @returns {Number}
  397. */
  398. Network.prototype.getCenterCoordinates = function () {
  399. return this.DOMtoCanvas({x: 0.5 * this.frame.canvas.clientWidth, y: 0.5 * this.frame.canvas.clientHeight});
  400. };
  401. Network.prototype.getBoundingBox = function(nodeId) {
  402. if (this.body.nodes[nodeId] !== undefined) {
  403. return this.body.nodes[nodeId].boundingBox;
  404. }
  405. }
  406. Network.prototype.getConnectedNodes = function(nodeId) {
  407. var nodeList = [];
  408. if (this.body.nodes[nodeId] !== undefined) {
  409. var node = this.body.nodes[nodeId];
  410. var nodeObj = {nodeId : true}; // used to quickly check if node already exists
  411. for (var i = 0; i < node.edges.length; i++) {
  412. var edge = node.edges[i];
  413. if (edge.toId === nodeId) {
  414. if (nodeObj[edge.fromId] === undefined) {
  415. nodeList.push(edge.fromId);
  416. nodeObj[edge.fromId] = true;
  417. }
  418. }
  419. else if (edge.fromId === nodeId) {
  420. if (nodeObj[edge.toId] === undefined) {
  421. nodeList.push(edge.toId)
  422. nodeObj[edge.toId] = true;
  423. }
  424. }
  425. }
  426. }
  427. return nodeList;
  428. }
  429. Network.prototype.getEdgesFromNode = function(nodeId) {
  430. var edgesList = [];
  431. if (this.body.nodes[nodeId] !== undefined) {
  432. var node = this.body.nodes[nodeId];
  433. for (var i = 0; i < node.edges.length; i++) {
  434. edgesList.push(node.edges[i].id);
  435. }
  436. }
  437. return edgesList;
  438. }
  439. Network.prototype.generateColorObject = function(color) {
  440. return util.parseColor(color);
  441. }
  442. module.exports = Network;