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.

516 lines
16 KiB

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