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.

468 lines
20 KiB

9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
10 years ago
9 years ago
  1. // Load custom shapes into CanvasRenderingContext2D
  2. require('./shapes');
  3. let Emitter = require('emitter-component');
  4. let Hammer = require('../module/hammer');
  5. let util = require('../util');
  6. let DataSet = require('../DataSet');
  7. let DataView = require('../DataView');
  8. let dotparser = require('./dotparser');
  9. let gephiParser = require('./gephiParser');
  10. let Images = require('./Images');
  11. let Activator = require('../shared/Activator');
  12. let 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. import ManipulationSystem from "./modules/ManipulationSystem";
  25. import ConfigurationSystem from "./../shared/ConfigurationSystem";
  26. import Validator from "./../shared/Validator";
  27. import {printStyle} from "./../shared/Validator";
  28. import {allOptions, configureOptions} from './options.js';
  29. /**
  30. * @constructor Network
  31. * Create a network visualization, displaying nodes and edges.
  32. *
  33. * @param {Element} container The DOM element in which the Network will
  34. * be created. Normally a div element.
  35. * @param {Object} data An object containing parameters
  36. * {Array} nodes
  37. * {Array} edges
  38. * @param {Object} options Options
  39. */
  40. function Network(container, data, options) {
  41. if (!(this instanceof Network)) {
  42. throw new SyntaxError('Constructor must be called with the new operator');
  43. }
  44. // set constant values
  45. this.options = {};
  46. this.defaultOptions = {
  47. locale: 'en',
  48. locales: locales,
  49. clickToUse: false
  50. };
  51. util.extend(this.options, this.defaultOptions);
  52. // containers for nodes and edges
  53. this.body = {
  54. nodes: {},
  55. nodeIndices: [],
  56. edges: {},
  57. edgeIndices: [],
  58. data: {
  59. nodes: null, // A DataSet or DataView
  60. edges: null // A DataSet or DataView
  61. },
  62. functions: {
  63. createNode: function() {},
  64. createEdge: function() {},
  65. getPointer: function() {}
  66. },
  67. emitter: {
  68. on: this.on.bind(this),
  69. off: this.off.bind(this),
  70. emit: this.emit.bind(this),
  71. once: this.once.bind(this)
  72. },
  73. eventListeners: {
  74. onTap: function() {},
  75. onTouch: function() {},
  76. onDoubleTap: function() {},
  77. onHold: function() {},
  78. onDragStart: function() {},
  79. onDrag: function() {},
  80. onDragEnd: function() {},
  81. onMouseWheel: function() {},
  82. onPinch: function() {},
  83. onMouseMove: function() {},
  84. onRelease: function() {},
  85. onContext: function() {}
  86. },
  87. container: container,
  88. view: {
  89. scale: 1,
  90. translation: {x: 0, y: 0}
  91. }
  92. };
  93. // bind the event listeners
  94. this.bindEventListeners();
  95. // setting up all modules
  96. this.images = new Images(() => this.body.emitter.emit("_requestRedraw")); // object with images
  97. this.groups = new Groups(); // object with groups
  98. this.canvas = new Canvas(this.body); // DOM handler
  99. this.selectionHandler = new SelectionHandler(this.body, this.canvas); // Selection handler
  100. this.interactionHandler = new InteractionHandler(this.body, this.canvas, this.selectionHandler); // Interaction handler handles all the hammer bindings (that are bound by canvas), key
  101. this.view = new View(this.body, this.canvas); // camera handler, does animations and zooms
  102. this.renderer = new CanvasRenderer(this.body, this.canvas); // renderer, starts renderloop, has events that modules can hook into
  103. this.physics = new PhysicsEngine(this.body); // physics engine, does all the simulations
  104. this.layoutEngine = new LayoutEngine(this.body); // layout engine for inital layout and hierarchical layout
  105. this.clustering = new ClusterEngine(this.body); // clustering api
  106. this.manipulation = new ManipulationSystem(this.body, this.canvas, this.selectionHandler); // data manipulation system
  107. this.nodesHandler = new NodesHandler(this.body, this.images, this.groups, this.layoutEngine); // Handle adding, deleting and updating of nodes as well as global options
  108. this.edgesHandler = new EdgesHandler(this.body, this.images, this.groups); // Handle adding, deleting and updating of edges as well as global options
  109. // create the DOM elements
  110. this.canvas._create();
  111. // setup configuration system
  112. this.configurationSystem = new ConfigurationSystem(this, this.body.container, configureOptions, this.canvas.pixelRatio);
  113. // apply options
  114. this.setOptions(options);
  115. // load data (the disable start variable will be the same as the enabled clustering)
  116. this.setData(data);
  117. }
  118. // Extend Network with an Emitter mixin
  119. Emitter(Network.prototype);
  120. /**
  121. * Set options
  122. * @param {Object} options
  123. */
  124. Network.prototype.setOptions = function (options) {
  125. if (options !== undefined) {
  126. let errorFound = Validator.validate(options, allOptions);
  127. if (errorFound === true) {
  128. console.log('%cErrors have been found in the supplied options object.', printStyle);
  129. }
  130. // copy the global fields over
  131. let fields = ['locale','locales','clickToUse'];
  132. util.selectiveDeepExtend(fields,this.options, options);
  133. // the hierarchical system can adapt the edges and the physics to it's own options because not all combinations work with the hierarichical system.
  134. options = this.layoutEngine.setOptions(options.layout, options);
  135. this.canvas.setOptions(options); // options for canvas are in globals
  136. // pass the options to the modules
  137. this.groups.setOptions(options.groups);
  138. this.nodesHandler.setOptions(options.nodes);
  139. this.edgesHandler.setOptions(options.edges);
  140. this.physics.setOptions(options.physics);
  141. this.manipulation.setOptions(options.manipulation,options); // manipulation uses the locales in the globals
  142. this.interactionHandler.setOptions(options.interaction);
  143. this.renderer.setOptions(options.interaction); // options for rendering are in interaction
  144. this.selectionHandler.setOptions(options.interaction); // options for selection are in interaction
  145. // these two do not have options at the moment, here for completeness
  146. //this.view.setOptions(options.view);
  147. //this.clustering.setOptions(options.clustering);
  148. this.configurationSystem.setOptions(options.configure);
  149. // if the configuration system is enabled, copy all options and put them into the config system
  150. if (this.configurationSystem.options.enabled === true) {
  151. let networkOptions = {nodes:{},edges:{},layout:{},interaction:{},manipulation:{},physics:{},global:{}};
  152. util.deepExtend(networkOptions.nodes, this.nodesHandler.options);
  153. util.deepExtend(networkOptions.edges, this.edgesHandler.options);
  154. util.deepExtend(networkOptions.layout, this.layoutEngine.options);
  155. // load the selectionHandler and rendere default options in to the interaction group
  156. util.deepExtend(networkOptions.interaction, this.selectionHandler.options);
  157. util.deepExtend(networkOptions.interaction, this.renderer.options);
  158. util.deepExtend(networkOptions.interaction, this.interactionHandler.options);
  159. util.deepExtend(networkOptions.manipulation, this.manipulation.options);
  160. util.deepExtend(networkOptions.physics, this.physics.options);
  161. // load globals into the global object
  162. util.deepExtend(networkOptions.global, this.canvas.options);
  163. util.deepExtend(networkOptions.global, this.options);
  164. this.configurationSystem.setModuleOptions(networkOptions);
  165. }
  166. // handle network global options
  167. if (options.clickToUse !== undefined) {
  168. if (options.clickToUse === true) {
  169. if (this.activator === undefined) {
  170. this.activator = new Activator(this.frame);
  171. this.activator.on('change', this._createKeyBinds.bind(this));
  172. }
  173. }
  174. else {
  175. if (this.activator !== undefined) {
  176. this.activator.destroy();
  177. delete this.activator;
  178. }
  179. this.body.emitter.emit("activate");
  180. }
  181. }
  182. else {
  183. this.body.emitter.emit("activate");
  184. }
  185. this.canvas.setSize();
  186. // start the physics simulation. Can be safely called multiple times.
  187. this.body.emitter.emit("startSimulation");
  188. }
  189. };
  190. /**
  191. * Update the this.body.nodeIndices with the most recent node index list
  192. * @private
  193. */
  194. Network.prototype._updateVisibleIndices = function () {
  195. let nodes = this.body.nodes;
  196. let edges = this.body.edges;
  197. this.body.nodeIndices = [];
  198. this.body.edgeIndices = [];
  199. for (let nodeId in nodes) {
  200. if (nodes.hasOwnProperty(nodeId)) {
  201. if (nodes[nodeId].options.hidden === false) {
  202. this.body.nodeIndices.push(nodeId);
  203. }
  204. }
  205. }
  206. for (let edgeId in edges) {
  207. if (edges.hasOwnProperty(edgeId)) {
  208. if (edges[edgeId].options.hidden === false) {
  209. this.body.edgeIndices.push(edgeId);
  210. }
  211. }
  212. }
  213. };
  214. /**
  215. * Bind all events
  216. */
  217. Network.prototype.bindEventListeners = function () {
  218. // this event will trigger a rebuilding of the cache everything. Used when nodes or edges have been added or removed.
  219. this.body.emitter.on("_dataChanged", () => {
  220. // update shortcut lists
  221. this._updateVisibleIndices();
  222. this.physics.updatePhysicsIndices();
  223. // call the dataUpdated event because the only difference between the two is the updating of the indices
  224. this.body.emitter.emit("_dataUpdated");
  225. });
  226. // this is called when options of EXISTING nodes or edges have changed.
  227. this.body.emitter.on("_dataUpdated", () => {
  228. // update values
  229. this._updateValueRange(this.body.nodes);
  230. this._updateValueRange(this.body.edges);
  231. // start simulation (can be called safely, even if already running)
  232. this.body.emitter.emit("startSimulation");
  233. });
  234. };
  235. /**
  236. * Set nodes and edges, and optionally options as well.
  237. *
  238. * @param {Object} data Object containing parameters:
  239. * {Array | DataSet | DataView} [nodes] Array with nodes
  240. * {Array | DataSet | DataView} [edges] Array with edges
  241. * {String} [dot] String containing data in DOT format
  242. * {String} [gephi] String containing data in gephi JSON format
  243. * {Options} [options] Object with options
  244. */
  245. Network.prototype.setData = function (data) {
  246. // reset the physics engine.
  247. this.body.emitter.emit("resetPhysics");
  248. this.body.emitter.emit("_resetData");
  249. // unselect all to ensure no selections from old data are carried over.
  250. this.selectionHandler.unselectAll();
  251. if (data && data.dot && (data.nodes || data.edges)) {
  252. throw new SyntaxError('Data must contain either parameter "dot" or ' +
  253. ' parameter pair "nodes" and "edges", but not both.');
  254. }
  255. // set options
  256. this.setOptions(data && data.options);
  257. // set all data
  258. if (data && data.dot) {
  259. console.log('The dot property has been depricated. Please use the static convertDot method to convert DOT into vis.network format and use the normal data format with nodes and edges. This converter is used like this: var data = vis.network.convertDot(dotString);');
  260. // parse DOT file
  261. var dotData = dotparser.DOTToGraph(data.dot);
  262. this.setData(dotData);
  263. return;
  264. }
  265. else if (data && data.gephi) {
  266. // parse DOT file
  267. console.log('The gephi property has been depricated. Please use the static convertGephi method to convert gephi into vis.network format and use the normal data format with nodes and edges. This converter is used like this: var data = vis.network.convertGephi(gephiJson);');
  268. var gephiData = gephiParser.parseGephi(data.gephi);
  269. this.setData(gephiData);
  270. return;
  271. }
  272. else {
  273. this.nodesHandler.setData(data && data.nodes, true);
  274. this.edgesHandler.setData(data && data.edges, true);
  275. }
  276. // emit change in data
  277. this.body.emitter.emit("_dataChanged");
  278. // find a stable position or start animating to a stable position
  279. this.body.emitter.emit("initPhysics");
  280. };
  281. /**
  282. * Cleans up all bindings of the network, removing it fully from the memory IF the variable is set to null after calling this function.
  283. * var network = new vis.Network(..);
  284. * network.destroy();
  285. * network = null;
  286. */
  287. Network.prototype.destroy = function () {
  288. this.body.emitter.emit("destroy");
  289. // clear events
  290. this.body.emitter.off();
  291. this.off();
  292. // delete modules
  293. delete this.groups;
  294. delete this.canvas;
  295. delete this.selectionHandler;
  296. delete this.interactionHandler;
  297. delete this.view;
  298. delete this.renderer;
  299. delete this.physics;
  300. delete this.layoutEngine;
  301. delete this.clustering;
  302. delete this.manipulation;
  303. delete this.nodesHandler;
  304. delete this.edgesHandler;
  305. delete this.configurationSystem;
  306. delete this.images;
  307. // delete emitter bindings
  308. delete this.body.emitter.emit;
  309. delete this.body.emitter.on;
  310. delete this.body.emitter.off;
  311. delete this.body.emitter.once;
  312. delete this.body.emitter;
  313. for (var nodeId in this.body.nodes) {
  314. delete this.body.nodes[nodeId];
  315. }
  316. for (var edgeId in this.body.edges) {
  317. delete this.body.edges[edgeId];
  318. }
  319. // remove the container and everything inside it recursively
  320. util.recursiveDOMDelete(this.body.container);
  321. };
  322. /**
  323. * Update the values of all object in the given array according to the current
  324. * value range of the objects in the array.
  325. * @param {Object} obj An object containing a set of Edges or Nodes
  326. * The objects must have a method getValue() and
  327. * setValueRange(min, max).
  328. * @private
  329. */
  330. Network.prototype._updateValueRange = function (obj) {
  331. var id;
  332. // determine the range of the objects
  333. var valueMin = undefined;
  334. var valueMax = undefined;
  335. var valueTotal = 0;
  336. for (id in obj) {
  337. if (obj.hasOwnProperty(id)) {
  338. var value = obj[id].getValue();
  339. if (value !== undefined) {
  340. valueMin = (valueMin === undefined) ? value : Math.min(value, valueMin);
  341. valueMax = (valueMax === undefined) ? value : Math.max(value, valueMax);
  342. valueTotal += value;
  343. }
  344. }
  345. }
  346. // adjust the range of all objects
  347. if (valueMin !== undefined && valueMax !== undefined) {
  348. for (id in obj) {
  349. if (obj.hasOwnProperty(id)) {
  350. obj[id].setValueRange(valueMin, valueMax, valueTotal);
  351. }
  352. }
  353. }
  354. };
  355. /**
  356. * Returns true when the Network is active.
  357. * @returns {boolean}
  358. */
  359. Network.prototype.isActive = function () {
  360. return !this.activator || this.activator.active;
  361. };
  362. Network.prototype.setSize = function() {this.canvas.setSize.apply(this.canvas,arguments);};
  363. Network.prototype.canvasToDOM = function() {this.canvas.canvasToDOM.apply(this.canvas,arguments);};
  364. Network.prototype.DOMtoCanvas = function() {this.canvas.setSize.DOMtoCanvas(this.canvas,arguments);};
  365. Network.prototype.findNode = function() {this.clustering.findNode.apply(this.clustering,arguments);};
  366. Network.prototype.isCluster = function() {this.clustering.isCluster.apply(this.clustering,arguments);};
  367. Network.prototype.openCluster = function() {this.clustering.openCluster.apply(this.clustering,arguments);};
  368. Network.prototype.cluster = function() {this.clustering.cluster.apply(this.clustering,arguments);};
  369. Network.prototype.clusterByConnection = function() {this.clustering.clusterByConnection.apply(this.clustering,arguments);};
  370. Network.prototype.clusterByHubsize = function() {this.clustering.clusterByHubsize.apply(this.clustering,arguments);};
  371. Network.prototype.clusterOutliers = function() {this.clustering.clusterOutliers.apply(this.clustering,arguments);};
  372. Network.prototype.getSeed = function() {this.layoutEngine.getSeed.apply(this.layoutEngine,arguments);};
  373. Network.prototype.enableEditMode = function() {this.manipulation.enableEditMode.apply(this.manipulation,arguments);};
  374. Network.prototype.disableEditMode = function() {this.manipulation.disableEditMode.apply(this.manipulation,arguments);};
  375. Network.prototype.addNodeMode = function() {this.manipulation.addNodeMode.apply(this.manipulation,arguments);};
  376. Network.prototype.editNodeMode = function() {this.manipulation.editNodeMode.apply(this.manipulation,arguments);};
  377. Network.prototype.addEdgeMode = function() {this.manipulation.addEdgeMode.apply(this.manipulation,arguments);};
  378. Network.prototype.editEdgeMode = function() {this.manipulation.editEdgeMode.apply(this.manipulation,arguments);};
  379. Network.prototype.deleteSelected = function() {this.manipulation.deleteSelected.apply(this.manipulation,arguments);};
  380. Network.prototype.getPositions = function() {this.nodesHandler.getPositions.apply(this.nodesHandler,arguments);};
  381. Network.prototype.storePositions = function() {this.nodesHandler.storePositions.apply(this.nodesHandler,arguments);};
  382. Network.prototype.getBoundingBox = function() {this.nodesHandler.getBoundingBox.apply(this.nodesHandler,arguments);};
  383. Network.prototype.getConnectedNodes = function() {this.nodesHandler.getConnectedNodes.apply(this.nodesHandler,arguments);};
  384. Network.prototype.getEdges = function() {this.nodesHandler.getEdges.apply(this.nodesHandler,arguments);};
  385. Network.prototype.startSimulation = function() {this.physics.startSimulation.apply(this.physics,arguments);};
  386. Network.prototype.stopSimulation = function() {this.physics.stopSimulation.apply(this.physics,arguments);};
  387. Network.prototype.stabilize = function() {this.physics.stabilize.apply(this.physics,arguments);};
  388. Network.prototype.getSelection = function() {this.selectionHandler.getSelection.apply(this.selectionHandler,arguments);};
  389. Network.prototype.getSelectedNodes = function() {this.selectionHandler.getSelectedNodes.apply(this.selectionHandler,arguments);};
  390. Network.prototype.getSelectedEdges = function() {this.selectionHandler.getSelectedEdges.apply(this.selectionHandler,arguments);};
  391. Network.prototype.getNodeAt = function() {this.selectionHandler.getNodeAt.apply(this.selectionHandler,arguments);};
  392. Network.prototype.getEdgeAt = function() {this.selectionHandler.getEdgeAt.apply(this.selectionHandler,arguments);};
  393. Network.prototype.selectNodes = function() {this.selectionHandler.selectNodes.apply(this.selectionHandler,arguments);};
  394. Network.prototype.selectEdges = function() {this.selectionHandler.selectEdges.apply(this.selectionHandler,arguments);};
  395. Network.prototype.unselectAll = function() {this.selectionHandler.unselectAll.apply(this.selectionHandler,arguments);};
  396. Network.prototype.redraw = function() {this.renderer.redraw.apply(this.renderer,arguments);};
  397. Network.prototype.getScale = function() {this.view.getScale.apply(this.view,arguments);};
  398. Network.prototype.getPosition = function() {this.view.getPosition.apply(this.view,arguments);};
  399. Network.prototype.fit = function() {this.view.fit.apply(this.view,arguments);};
  400. Network.prototype.moveTo = function() {this.view.moveTo.apply(this.view,arguments);};
  401. Network.prototype.focus = function() {this.view.focus.apply(this.view,arguments);};
  402. Network.prototype.releaseNode = function() {this.view.releaseNode.apply(this.view,arguments);};
  403. module.exports = Network;