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.

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