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.

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