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.

496 lines
21 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
  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. container: container,
  55. nodes: {},
  56. nodeIndices: [],
  57. edges: {},
  58. edgeIndices: [],
  59. emitter: {
  60. on: this.on.bind(this),
  61. off: this.off.bind(this),
  62. emit: this.emit.bind(this),
  63. once: this.once.bind(this)
  64. },
  65. eventListeners: {
  66. onTap: function() {},
  67. onTouch: function() {},
  68. onDoubleTap: function() {},
  69. onHold: function() {},
  70. onDragStart: function() {},
  71. onDrag: function() {},
  72. onDragEnd: function() {},
  73. onMouseWheel: function() {},
  74. onPinch: function() {},
  75. onMouseMove: function() {},
  76. onRelease: function() {},
  77. onContext: function() {}
  78. },
  79. data: {
  80. nodes: null, // A DataSet or DataView
  81. edges: null // A DataSet or DataView
  82. },
  83. functions: {
  84. createNode: function() {},
  85. createEdge: function() {},
  86. getPointer: function() {}
  87. },
  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. // apply options
  112. this.setOptions(options);
  113. // load data (the disable start variable will be the same as the enabled clustering)
  114. this.setData(data);
  115. }
  116. // Extend Network with an Emitter mixin
  117. Emitter(Network.prototype);
  118. /**
  119. * Set options
  120. * @param {Object} options
  121. */
  122. Network.prototype.setOptions = function (options) {
  123. if (options !== undefined) {
  124. let errorFound = Validator.validate(options, allOptions);
  125. if (errorFound === true) {
  126. console.log('%cErrors have been found in the supplied options object.', printStyle);
  127. }
  128. // copy the global fields over
  129. let fields = ['locale','locales','clickToUse'];
  130. util.selectiveDeepExtend(fields,this.options, options);
  131. // the hierarchical system can adapt the edges and the physics to it's own options because not all combinations work with the hierarichical system.
  132. options = this.layoutEngine.setOptions(options.layout, options);
  133. this.canvas.setOptions(options); // options for canvas are in globals
  134. // pass the options to the modules
  135. this.groups.setOptions(options.groups);
  136. this.nodesHandler.setOptions(options.nodes);
  137. this.edgesHandler.setOptions(options.edges);
  138. this.physics.setOptions(options.physics);
  139. this.manipulation.setOptions(options.manipulation, options, this.options); // manipulation uses the locales in the globals
  140. this.interactionHandler.setOptions(options.interaction);
  141. this.renderer.setOptions(options.interaction); // options for rendering are in interaction
  142. this.selectionHandler.setOptions(options.interaction); // options for selection are in interaction
  143. // reload the settings of the nodes to apply changes in groups that are not referenced by pointer.
  144. if (options.groups !== undefined) {
  145. this.body.emitter.emit("refreshNodes");
  146. }
  147. // these two do not have options at the moment, here for completeness
  148. //this.view.setOptions(options.view);
  149. //this.clustering.setOptions(options.clustering);
  150. if ('configure' in options) {
  151. if (!this.configurator) {
  152. this.configurator = new Configurator(this, this.body.container, configureOptions, this.canvas.pixelRatio);
  153. }
  154. this.configurator.setOptions(options.configure);
  155. }
  156. // if the configuration system is enabled, copy all options and put them into the config system
  157. if (this.configurator && this.configurator.options.enabled === true) {
  158. let networkOptions = {nodes:{},edges:{},layout:{},interaction:{},manipulation:{},physics:{},global:{}};
  159. util.deepExtend(networkOptions.nodes, this.nodesHandler.options);
  160. util.deepExtend(networkOptions.edges, this.edgesHandler.options);
  161. util.deepExtend(networkOptions.layout, this.layoutEngine.options);
  162. // load the selectionHandler and render default options in to the interaction group
  163. util.deepExtend(networkOptions.interaction, this.selectionHandler.options);
  164. util.deepExtend(networkOptions.interaction, this.renderer.options);
  165. util.deepExtend(networkOptions.interaction, this.interactionHandler.options);
  166. util.deepExtend(networkOptions.manipulation, this.manipulation.options);
  167. util.deepExtend(networkOptions.physics, this.physics.options);
  168. // load globals into the global object
  169. util.deepExtend(networkOptions.global, this.canvas.options);
  170. util.deepExtend(networkOptions.global, this.options);
  171. this.configurator.setModuleOptions(networkOptions);
  172. }
  173. // handle network global options
  174. if (options.clickToUse !== undefined) {
  175. if (options.clickToUse === true) {
  176. if (this.activator === undefined) {
  177. this.activator = new Activator(this.canvas.frame);
  178. this.activator.on('change', () => {this.body.emitter.emit("activate")});
  179. }
  180. }
  181. else {
  182. if (this.activator !== undefined) {
  183. this.activator.destroy();
  184. delete this.activator;
  185. }
  186. this.body.emitter.emit("activate");
  187. }
  188. }
  189. else {
  190. this.body.emitter.emit("activate");
  191. }
  192. this.canvas.setSize();
  193. // start the physics simulation. Can be safely called multiple times.
  194. this.body.emitter.emit("startSimulation");
  195. }
  196. };
  197. /**
  198. * Update the this.body.nodeIndices with the most recent node index list
  199. * @private
  200. */
  201. Network.prototype._updateVisibleIndices = function () {
  202. let nodes = this.body.nodes;
  203. let edges = this.body.edges;
  204. this.body.nodeIndices = [];
  205. this.body.edgeIndices = [];
  206. for (let nodeId in nodes) {
  207. if (nodes.hasOwnProperty(nodeId)) {
  208. if (nodes[nodeId].options.hidden === false) {
  209. this.body.nodeIndices.push(nodeId);
  210. }
  211. }
  212. }
  213. for (let edgeId in edges) {
  214. if (edges.hasOwnProperty(edgeId)) {
  215. if (edges[edgeId].options.hidden === false) {
  216. this.body.edgeIndices.push(edgeId);
  217. }
  218. }
  219. }
  220. };
  221. /**
  222. * Bind all events
  223. */
  224. Network.prototype.bindEventListeners = function () {
  225. // this event will trigger a rebuilding of the cache everything. Used when nodes or edges have been added or removed.
  226. this.body.emitter.on("_dataChanged", () => {
  227. // update shortcut lists
  228. this._updateVisibleIndices();
  229. this.physics.updatePhysicsData();
  230. this.body.emitter.emit("_requestRedraw");
  231. // call the dataUpdated event because the only difference between the two is the updating of the indices
  232. this.body.emitter.emit("_dataUpdated");
  233. });
  234. // this is called when options of EXISTING nodes or edges have changed.
  235. this.body.emitter.on("_dataUpdated", () => {
  236. // update values
  237. this._updateValueRange(this.body.nodes);
  238. this._updateValueRange(this.body.edges);
  239. // start simulation (can be called safely, even if already running)
  240. this.body.emitter.emit("startSimulation");
  241. this.body.emitter.emit("_requestRedraw");
  242. });
  243. };
  244. /**
  245. * Set nodes and edges, and optionally options as well.
  246. *
  247. * @param {Object} data Object containing parameters:
  248. * {Array | DataSet | DataView} [nodes] Array with nodes
  249. * {Array | DataSet | DataView} [edges] Array with edges
  250. * {String} [dot] String containing data in DOT format
  251. * {String} [gephi] String containing data in gephi JSON format
  252. * {Options} [options] Object with options
  253. */
  254. Network.prototype.setData = function (data) {
  255. // reset the physics engine.
  256. this.body.emitter.emit("resetPhysics");
  257. this.body.emitter.emit("_resetData");
  258. // unselect all to ensure no selections from old data are carried over.
  259. this.selectionHandler.unselectAll();
  260. if (data && data.dot && (data.nodes || data.edges)) {
  261. throw new SyntaxError('Data must contain either parameter "dot" or ' +
  262. ' parameter pair "nodes" and "edges", but not both.');
  263. }
  264. // set options
  265. this.setOptions(data && data.options);
  266. // set all data
  267. if (data && data.dot) {
  268. 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);');
  269. // parse DOT file
  270. var dotData = dotparser.DOTToGraph(data.dot);
  271. this.setData(dotData);
  272. return;
  273. }
  274. else if (data && data.gephi) {
  275. // parse DOT file
  276. 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);');
  277. var gephiData = gephiParser.parseGephi(data.gephi);
  278. this.setData(gephiData);
  279. return;
  280. }
  281. else {
  282. this.nodesHandler.setData(data && data.nodes, true);
  283. this.edgesHandler.setData(data && data.edges, true);
  284. }
  285. // emit change in data
  286. this.body.emitter.emit("_dataChanged");
  287. // find a stable position or start animating to a stable position
  288. this.body.emitter.emit("initPhysics");
  289. };
  290. /**
  291. * Cleans up all bindings of the network, removing it fully from the memory IF the variable is set to null after calling this function.
  292. * var network = new vis.Network(..);
  293. * network.destroy();
  294. * network = null;
  295. */
  296. Network.prototype.destroy = function () {
  297. this.body.emitter.emit("destroy");
  298. // clear events
  299. this.body.emitter.off();
  300. this.off();
  301. // delete modules
  302. delete this.groups;
  303. delete this.canvas;
  304. delete this.selectionHandler;
  305. delete this.interactionHandler;
  306. delete this.view;
  307. delete this.renderer;
  308. delete this.physics;
  309. delete this.layoutEngine;
  310. delete this.clustering;
  311. delete this.manipulation;
  312. delete this.nodesHandler;
  313. delete this.edgesHandler;
  314. delete this.configurator;
  315. delete this.images;
  316. for (var nodeId in this.body.nodes) {
  317. delete this.body.nodes[nodeId];
  318. }
  319. for (var edgeId in this.body.edges) {
  320. delete this.body.edges[edgeId];
  321. }
  322. // remove the container and everything inside it recursively
  323. util.recursiveDOMDelete(this.body.container);
  324. };
  325. /**
  326. * Update the values of all object in the given array according to the current
  327. * value range of the objects in the array.
  328. * @param {Object} obj An object containing a set of Edges or Nodes
  329. * The objects must have a method getValue() and
  330. * setValueRange(min, max).
  331. * @private
  332. */
  333. Network.prototype._updateValueRange = function (obj) {
  334. var id;
  335. // determine the range of the objects
  336. var valueMin = undefined;
  337. var valueMax = undefined;
  338. var valueTotal = 0;
  339. for (id in obj) {
  340. if (obj.hasOwnProperty(id)) {
  341. var value = obj[id].getValue();
  342. if (value !== undefined) {
  343. valueMin = (valueMin === undefined) ? value : Math.min(value, valueMin);
  344. valueMax = (valueMax === undefined) ? value : Math.max(value, valueMax);
  345. valueTotal += value;
  346. }
  347. }
  348. }
  349. // adjust the range of all objects
  350. if (valueMin !== undefined && valueMax !== undefined) {
  351. for (id in obj) {
  352. if (obj.hasOwnProperty(id)) {
  353. obj[id].setValueRange(valueMin, valueMax, valueTotal);
  354. }
  355. }
  356. }
  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. Network.prototype.setSize = function() {return this.canvas.setSize.apply(this.canvas,arguments);};
  366. Network.prototype.canvasToDOM = function() {return this.canvas.canvasToDOM.apply(this.canvas,arguments);};
  367. Network.prototype.DOMtoCanvas = function() {return this.canvas.DOMtoCanvas.apply(this.canvas,arguments);};
  368. Network.prototype.findNode = function() {return this.clustering.findNode.apply(this.clustering,arguments);};
  369. Network.prototype.isCluster = function() {return this.clustering.isCluster.apply(this.clustering,arguments);};
  370. Network.prototype.openCluster = function() {return this.clustering.openCluster.apply(this.clustering,arguments);};
  371. Network.prototype.cluster = function() {return this.clustering.cluster.apply(this.clustering,arguments);};
  372. Network.prototype.getNodesInCluster = function() {return this.clustering.getNodesInCluster.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.editNode = function() {return this.manipulation.editNode.apply(this.manipulation,arguments);};
  381. Network.prototype.editNodeMode = function() {console.log("Depricated: Please use editNode instead of editNodeMode."); return this.manipulation.editNode.apply(this.manipulation,arguments);};
  382. Network.prototype.addEdgeMode = function() {return this.manipulation.addEdgeMode.apply(this.manipulation,arguments);};
  383. Network.prototype.editEdgeMode = function() {return this.manipulation.editEdgeMode.apply(this.manipulation,arguments);};
  384. Network.prototype.deleteSelected = function() {return this.manipulation.deleteSelected.apply(this.manipulation,arguments);};
  385. Network.prototype.getPositions = function() {return this.nodesHandler.getPositions.apply(this.nodesHandler,arguments);};
  386. Network.prototype.storePositions = function() {return this.nodesHandler.storePositions.apply(this.nodesHandler,arguments);};
  387. Network.prototype.getBoundingBox = function() {return this.nodesHandler.getBoundingBox.apply(this.nodesHandler,arguments);};
  388. Network.prototype.getConnectedNodes = function(objectId) {
  389. if (this.body.nodes[objectId] !== undefined) {
  390. return this.nodesHandler.getConnectedNodes.apply(this.nodesHandler,arguments);
  391. }
  392. else {
  393. return this.edgesHandler.getConnectedNodes.apply(this.edgesHandler,arguments);
  394. }
  395. };
  396. Network.prototype.getConnectedEdges = function() {return this.nodesHandler.getConnectedEdges.apply(this.nodesHandler,arguments);};
  397. Network.prototype.startSimulation = function() {return this.physics.startSimulation.apply(this.physics,arguments);};
  398. Network.prototype.stopSimulation = function() {return this.physics.stopSimulation.apply(this.physics,arguments);};
  399. Network.prototype.stabilize = function() {return this.physics.stabilize.apply(this.physics,arguments);};
  400. Network.prototype.getSelection = function() {return this.selectionHandler.getSelection.apply(this.selectionHandler,arguments);};
  401. Network.prototype.getSelectedNodes = function() {return this.selectionHandler.getSelectedNodes.apply(this.selectionHandler,arguments);};
  402. Network.prototype.getSelectedEdges = function() {return this.selectionHandler.getSelectedEdges.apply(this.selectionHandler,arguments);};
  403. Network.prototype.getNodeAt = function() {
  404. var node = this.selectionHandler.getNodeAt.apply(this.selectionHandler,arguments);
  405. if (node !== undefined && node.id !== undefined) {
  406. return node.id;
  407. }
  408. return node;
  409. };
  410. Network.prototype.getEdgeAt = function() {
  411. var edge = this.selectionHandler.getEdgeAt.apply(this.selectionHandler,arguments);
  412. if (edge !== undefined && edge.id !== undefined) {
  413. return edge.id;
  414. }
  415. return edge;
  416. };
  417. Network.prototype.selectNodes = function() {return this.selectionHandler.selectNodes.apply(this.selectionHandler,arguments);};
  418. Network.prototype.selectEdges = function() {return this.selectionHandler.selectEdges.apply(this.selectionHandler,arguments);};
  419. Network.prototype.unselectAll = function() {return this.selectionHandler.unselectAll.apply(this.selectionHandler,arguments);};
  420. Network.prototype.redraw = function() {return this.renderer.redraw.apply(this.renderer,arguments);};
  421. Network.prototype.getScale = function() {return this.view.getScale.apply(this.view,arguments);};
  422. Network.prototype.getViewPosition = function() {return this.view.getViewPosition.apply(this.view,arguments);};
  423. Network.prototype.fit = function() {return this.view.fit.apply(this.view,arguments);};
  424. Network.prototype.moveTo = function() {return this.view.moveTo.apply(this.view,arguments);};
  425. Network.prototype.focus = function() {return this.view.focus.apply(this.view,arguments);};
  426. Network.prototype.releaseNode = function() {return this.view.releaseNode.apply(this.view,arguments);};
  427. Network.prototype.getOptionsFromConfigurator = function() {
  428. let options = {};
  429. if (this.configurator) {
  430. options = this.configurator.getOptions.apply(this.configurator);
  431. }
  432. return options;
  433. };
  434. module.exports = Network;