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.

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