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.

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