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.

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