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.

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