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.

472 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
10 years ago
9 years ago
9 years ago
9 years ago
9 years ago
10 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 Configurator from "./../shared/Configurator";
  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.configurator = new Configurator(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, this.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. // reload the settings of the nodes to apply changes in groups that are not referenced by pointer.
  146. if (options.groups !== undefined) {
  147. this.body.emitter.emit("refreshNodes");
  148. }
  149. // these two do not have options at the moment, here for completeness
  150. //this.view.setOptions(options.view);
  151. //this.clustering.setOptions(options.clustering);
  152. this.configurator.setOptions(options.configure);
  153. // if the configuration system is enabled, copy all options and put them into the config system
  154. if (this.configurator.options.enabled === true) {
  155. let networkOptions = {nodes:{},edges:{},layout:{},interaction:{},manipulation:{},physics:{},global:{}};
  156. util.deepExtend(networkOptions.nodes, this.nodesHandler.options);
  157. util.deepExtend(networkOptions.edges, this.edgesHandler.options);
  158. util.deepExtend(networkOptions.layout, this.layoutEngine.options);
  159. // load the selectionHandler and rendere default options in to the interaction group
  160. util.deepExtend(networkOptions.interaction, this.selectionHandler.options);
  161. util.deepExtend(networkOptions.interaction, this.renderer.options);
  162. util.deepExtend(networkOptions.interaction, this.interactionHandler.options);
  163. util.deepExtend(networkOptions.manipulation, this.manipulation.options);
  164. util.deepExtend(networkOptions.physics, this.physics.options);
  165. // load globals into the global object
  166. util.deepExtend(networkOptions.global, this.canvas.options);
  167. util.deepExtend(networkOptions.global, this.options);
  168. this.configurator.setModuleOptions(networkOptions);
  169. }
  170. // handle network global options
  171. if (options.clickToUse !== undefined) {
  172. if (options.clickToUse === true) {
  173. if (this.activator === undefined) {
  174. this.activator = new Activator(this.frame);
  175. this.activator.on('change', this._createKeyBinds.bind(this));
  176. }
  177. }
  178. else {
  179. if (this.activator !== undefined) {
  180. this.activator.destroy();
  181. delete this.activator;
  182. }
  183. this.body.emitter.emit("activate");
  184. }
  185. }
  186. else {
  187. this.body.emitter.emit("activate");
  188. }
  189. this.canvas.setSize();
  190. // start the physics simulation. Can be safely called multiple times.
  191. this.body.emitter.emit("startSimulation");
  192. }
  193. };
  194. /**
  195. * Update the this.body.nodeIndices with the most recent node index list
  196. * @private
  197. */
  198. Network.prototype._updateVisibleIndices = function () {
  199. let nodes = this.body.nodes;
  200. let edges = this.body.edges;
  201. this.body.nodeIndices = [];
  202. this.body.edgeIndices = [];
  203. for (let nodeId in nodes) {
  204. if (nodes.hasOwnProperty(nodeId)) {
  205. if (nodes[nodeId].options.hidden === false) {
  206. this.body.nodeIndices.push(nodeId);
  207. }
  208. }
  209. }
  210. for (let edgeId in edges) {
  211. if (edges.hasOwnProperty(edgeId)) {
  212. if (edges[edgeId].options.hidden === false) {
  213. this.body.edgeIndices.push(edgeId);
  214. }
  215. }
  216. }
  217. };
  218. /**
  219. * Bind all events
  220. */
  221. Network.prototype.bindEventListeners = function () {
  222. // this event will trigger a rebuilding of the cache everything. Used when nodes or edges have been added or removed.
  223. this.body.emitter.on("_dataChanged", () => {
  224. // update shortcut lists
  225. this._updateVisibleIndices();
  226. this.physics.updatePhysicsData();
  227. // call the dataUpdated event because the only difference between the two is the updating of the indices
  228. this.body.emitter.emit("_dataUpdated");
  229. });
  230. // this is called when options of EXISTING nodes or edges have changed.
  231. this.body.emitter.on("_dataUpdated", () => {
  232. // update values
  233. this._updateValueRange(this.body.nodes);
  234. this._updateValueRange(this.body.edges);
  235. // start simulation (can be called safely, even if already running)
  236. this.body.emitter.emit("startSimulation");
  237. });
  238. };
  239. /**
  240. * Set nodes and edges, and optionally options as well.
  241. *
  242. * @param {Object} data Object containing parameters:
  243. * {Array | DataSet | DataView} [nodes] Array with nodes
  244. * {Array | DataSet | DataView} [edges] Array with edges
  245. * {String} [dot] String containing data in DOT format
  246. * {String} [gephi] String containing data in gephi JSON format
  247. * {Options} [options] Object with options
  248. */
  249. Network.prototype.setData = function (data) {
  250. // reset the physics engine.
  251. this.body.emitter.emit("resetPhysics");
  252. this.body.emitter.emit("_resetData");
  253. // unselect all to ensure no selections from old data are carried over.
  254. this.selectionHandler.unselectAll();
  255. if (data && data.dot && (data.nodes || data.edges)) {
  256. throw new SyntaxError('Data must contain either parameter "dot" or ' +
  257. ' parameter pair "nodes" and "edges", but not both.');
  258. }
  259. // set options
  260. this.setOptions(data && data.options);
  261. // set all data
  262. if (data && data.dot) {
  263. 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);');
  264. // parse DOT file
  265. var dotData = dotparser.DOTToGraph(data.dot);
  266. this.setData(dotData);
  267. return;
  268. }
  269. else if (data && data.gephi) {
  270. // parse DOT file
  271. 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);');
  272. var gephiData = gephiParser.parseGephi(data.gephi);
  273. this.setData(gephiData);
  274. return;
  275. }
  276. else {
  277. this.nodesHandler.setData(data && data.nodes, true);
  278. this.edgesHandler.setData(data && data.edges, true);
  279. }
  280. // emit change in data
  281. this.body.emitter.emit("_dataChanged");
  282. // find a stable position or start animating to a stable position
  283. this.body.emitter.emit("initPhysics");
  284. };
  285. /**
  286. * Cleans up all bindings of the network, removing it fully from the memory IF the variable is set to null after calling this function.
  287. * var network = new vis.Network(..);
  288. * network.destroy();
  289. * network = null;
  290. */
  291. Network.prototype.destroy = function () {
  292. this.body.emitter.emit("destroy");
  293. // clear events
  294. this.body.emitter.off();
  295. this.off();
  296. // delete modules
  297. delete this.groups;
  298. delete this.canvas;
  299. delete this.selectionHandler;
  300. delete this.interactionHandler;
  301. delete this.view;
  302. delete this.renderer;
  303. delete this.physics;
  304. delete this.layoutEngine;
  305. delete this.clustering;
  306. delete this.manipulation;
  307. delete this.nodesHandler;
  308. delete this.edgesHandler;
  309. delete this.configurator;
  310. delete this.images;
  311. // delete emitter bindings
  312. delete this.body.emitter.emit;
  313. delete this.body.emitter.on;
  314. delete this.body.emitter.off;
  315. delete this.body.emitter.once;
  316. delete this.body.emitter;
  317. for (var nodeId in this.body.nodes) {
  318. delete this.body.nodes[nodeId];
  319. }
  320. for (var edgeId in this.body.edges) {
  321. delete this.body.edges[edgeId];
  322. }
  323. // remove the container and everything inside it recursively
  324. util.recursiveDOMDelete(this.body.container);
  325. };
  326. /**
  327. * Update the values of all object in the given array according to the current
  328. * value range of the objects in the array.
  329. * @param {Object} obj An object containing a set of Edges or Nodes
  330. * The objects must have a method getValue() and
  331. * setValueRange(min, max).
  332. * @private
  333. */
  334. Network.prototype._updateValueRange = function (obj) {
  335. var id;
  336. // determine the range of the objects
  337. var valueMin = undefined;
  338. var valueMax = undefined;
  339. var valueTotal = 0;
  340. for (id in obj) {
  341. if (obj.hasOwnProperty(id)) {
  342. var value = obj[id].getValue();
  343. if (value !== undefined) {
  344. valueMin = (valueMin === undefined) ? value : Math.min(value, valueMin);
  345. valueMax = (valueMax === undefined) ? value : Math.max(value, valueMax);
  346. valueTotal += value;
  347. }
  348. }
  349. }
  350. // adjust the range of all objects
  351. if (valueMin !== undefined && valueMax !== undefined) {
  352. for (id in obj) {
  353. if (obj.hasOwnProperty(id)) {
  354. obj[id].setValueRange(valueMin, valueMax, valueTotal);
  355. }
  356. }
  357. }
  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. Network.prototype.setSize = function() {return this.canvas.setSize.apply(this.canvas,arguments);};
  367. Network.prototype.canvasToDOM = function() {return this.canvas.canvasToDOM.apply(this.canvas,arguments);};
  368. Network.prototype.DOMtoCanvas = function() {return this.canvas.setSize.DOMtoCanvas(this.canvas,arguments);};
  369. Network.prototype.findNode = function() {return this.clustering.findNode.apply(this.clustering,arguments);};
  370. Network.prototype.isCluster = function() {return this.clustering.isCluster.apply(this.clustering,arguments);};
  371. Network.prototype.openCluster = function() {return this.clustering.openCluster.apply(this.clustering,arguments);};
  372. Network.prototype.cluster = function() {return this.clustering.cluster.apply(this.clustering,arguments);};
  373. Network.prototype.clusterByConnection = function() {return this.clustering.clusterByConnection.apply(this.clustering,arguments);};
  374. Network.prototype.clusterByHubsize = function() {return this.clustering.clusterByHubsize.apply(this.clustering,arguments);};
  375. Network.prototype.clusterOutliers = function() {return this.clustering.clusterOutliers.apply(this.clustering,arguments);};
  376. Network.prototype.getSeed = function() {return this.layoutEngine.getSeed.apply(this.layoutEngine,arguments);};
  377. Network.prototype.enableEditMode = function() {return this.manipulation.enableEditMode.apply(this.manipulation,arguments);};
  378. Network.prototype.disableEditMode = function() {return this.manipulation.disableEditMode.apply(this.manipulation,arguments);};
  379. Network.prototype.addNodeMode = function() {return this.manipulation.addNodeMode.apply(this.manipulation,arguments);};
  380. Network.prototype.editNodeMode = function() {return this.manipulation.editNodeMode.apply(this.manipulation,arguments);};
  381. Network.prototype.addEdgeMode = function() {return this.manipulation.addEdgeMode.apply(this.manipulation,arguments);};
  382. Network.prototype.editEdgeMode = function() {return this.manipulation.editEdgeMode.apply(this.manipulation,arguments);};
  383. Network.prototype.deleteSelected = function() {return this.manipulation.deleteSelected.apply(this.manipulation,arguments);};
  384. Network.prototype.getPositions = function() {return this.nodesHandler.getPositions.apply(this.nodesHandler,arguments);};
  385. Network.prototype.storePositions = function() {return this.nodesHandler.storePositions.apply(this.nodesHandler,arguments);};
  386. Network.prototype.getBoundingBox = function() {return this.nodesHandler.getBoundingBox.apply(this.nodesHandler,arguments);};
  387. Network.prototype.getConnectedNodes = function() {return this.nodesHandler.getConnectedNodes.apply(this.nodesHandler,arguments);};
  388. Network.prototype.getEdges = function() {return this.nodesHandler.getEdges.apply(this.nodesHandler,arguments);};
  389. Network.prototype.startSimulation = function() {return this.physics.startSimulation.apply(this.physics,arguments);};
  390. Network.prototype.stopSimulation = function() {return this.physics.stopSimulation.apply(this.physics,arguments);};
  391. Network.prototype.stabilize = function() {return this.physics.stabilize.apply(this.physics,arguments);};
  392. Network.prototype.getSelection = function() {return this.selectionHandler.getSelection.apply(this.selectionHandler,arguments);};
  393. Network.prototype.getSelectedNodes = function() {return this.selectionHandler.getSelectedNodes.apply(this.selectionHandler,arguments);};
  394. Network.prototype.getSelectedEdges = function() {return this.selectionHandler.getSelectedEdges.apply(this.selectionHandler,arguments);};
  395. Network.prototype.getNodeAt = function() {return this.selectionHandler.getNodeAt.apply(this.selectionHandler,arguments);};
  396. Network.prototype.getEdgeAt = function() {return this.selectionHandler.getEdgeAt.apply(this.selectionHandler,arguments);};
  397. Network.prototype.selectNodes = function() {return this.selectionHandler.selectNodes.apply(this.selectionHandler,arguments);};
  398. Network.prototype.selectEdges = function() {return this.selectionHandler.selectEdges.apply(this.selectionHandler,arguments);};
  399. Network.prototype.unselectAll = function() {return this.selectionHandler.unselectAll.apply(this.selectionHandler,arguments);};
  400. Network.prototype.redraw = function() {return this.renderer.redraw.apply(this.renderer,arguments);};
  401. Network.prototype.getScale = function() {return this.view.getScale.apply(this.view,arguments);};
  402. Network.prototype.getViewPosition = function() {return this.view.getViewPosition.apply(this.view,arguments);};
  403. Network.prototype.fit = function() {return this.view.fit.apply(this.view,arguments);};
  404. Network.prototype.moveTo = function() {return this.view.moveTo.apply(this.view,arguments);};
  405. Network.prototype.focus = function() {return this.view.focus.apply(this.view,arguments);};
  406. Network.prototype.releaseNode = function() {return this.view.releaseNode.apply(this.view,arguments);};
  407. module.exports = Network;