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.

532 lines
23 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 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 visible nodes and edges list with the most recent node state.
  214. *
  215. * Visible nodes are stored in this.body.nodeIndices.
  216. * Visible edges are stored in this.body.edgeIndices.
  217. * A node or edges is visible if it is not hidden or clustered.
  218. *
  219. * @private
  220. */
  221. Network.prototype._updateVisibleIndices = function () {
  222. let nodes = this.body.nodes;
  223. let edges = this.body.edges;
  224. this.body.nodeIndices = [];
  225. this.body.edgeIndices = [];
  226. for (let nodeId in nodes) {
  227. if (nodes.hasOwnProperty(nodeId)) {
  228. if (!this.clustering._isClusteredNode(nodeId) && nodes[nodeId].options.hidden === false) {
  229. this.body.nodeIndices.push(nodes[nodeId].id);
  230. }
  231. }
  232. }
  233. for (let edgeId in edges) {
  234. if (edges.hasOwnProperty(edgeId)) {
  235. let edge = edges[edgeId];
  236. if (!this.clustering._isClusteredEdge(edgeId)
  237. && edge.options.hidden === false
  238. // Also hidden if any of its connecting nodes are hidden
  239. && nodes[edge.fromId].options.hidden === false
  240. && nodes[edge.toId ].options.hidden === false) {
  241. this.body.edgeIndices.push(edge.id);
  242. }
  243. }
  244. }
  245. };
  246. /**
  247. * Bind all events
  248. */
  249. Network.prototype.bindEventListeners = function () {
  250. // this event will trigger a rebuilding of the cache everything. Used when nodes or edges have been added or removed.
  251. this.body.emitter.on("_dataChanged", () => {
  252. // update shortcut lists
  253. this._updateVisibleIndices();
  254. this.body.emitter.emit("_requestRedraw");
  255. // call the dataUpdated event because the only difference between the two is the updating of the indices
  256. this.body.emitter.emit("_dataUpdated");
  257. });
  258. // this is called when options of EXISTING nodes or edges have changed.
  259. this.body.emitter.on("_dataUpdated", () => {
  260. // update values
  261. this._updateValueRange(this.body.nodes);
  262. this._updateValueRange(this.body.edges);
  263. // start simulation (can be called safely, even if already running)
  264. this.body.emitter.emit("startSimulation");
  265. this.body.emitter.emit("_requestRedraw");
  266. });
  267. };
  268. /**
  269. * Set nodes and edges, and optionally options as well.
  270. *
  271. * @param {Object} data Object containing parameters:
  272. * {Array | DataSet | DataView} [nodes] Array with nodes
  273. * {Array | DataSet | DataView} [edges] Array with edges
  274. * {String} [dot] String containing data in DOT format
  275. * {String} [gephi] String containing data in gephi JSON format
  276. * {Options} [options] Object with options
  277. */
  278. Network.prototype.setData = function (data) {
  279. // reset the physics engine.
  280. this.body.emitter.emit("resetPhysics");
  281. this.body.emitter.emit("_resetData");
  282. // unselect all to ensure no selections from old data are carried over.
  283. this.selectionHandler.unselectAll();
  284. if (data && data.dot && (data.nodes || data.edges)) {
  285. throw new SyntaxError('Data must contain either parameter "dot" or ' +
  286. ' parameter pair "nodes" and "edges", but not both.');
  287. }
  288. // set options
  289. this.setOptions(data && data.options);
  290. // set all data
  291. if (data && data.dot) {
  292. 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);');
  293. // parse DOT file
  294. var dotData = dotparser.DOTToGraph(data.dot);
  295. this.setData(dotData);
  296. return;
  297. }
  298. else if (data && data.gephi) {
  299. // parse DOT file
  300. 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);');
  301. var gephiData = gephiParser.parseGephi(data.gephi);
  302. this.setData(gephiData);
  303. return;
  304. }
  305. else {
  306. this.nodesHandler.setData(data && data.nodes, true);
  307. this.edgesHandler.setData(data && data.edges, true);
  308. }
  309. // emit change in data
  310. this.body.emitter.emit("_dataChanged");
  311. // emit data loaded
  312. this.body.emitter.emit("_dataLoaded");
  313. // find a stable position or start animating to a stable position
  314. this.body.emitter.emit("initPhysics");
  315. };
  316. /**
  317. * Cleans up all bindings of the network, removing it fully from the memory IF the variable is set to null after calling this function.
  318. * var network = new vis.Network(..);
  319. * network.destroy();
  320. * network = null;
  321. */
  322. Network.prototype.destroy = function () {
  323. this.body.emitter.emit("destroy");
  324. // clear events
  325. this.body.emitter.off();
  326. this.off();
  327. // delete modules
  328. delete this.groups;
  329. delete this.canvas;
  330. delete this.selectionHandler;
  331. delete this.interactionHandler;
  332. delete this.view;
  333. delete this.renderer;
  334. delete this.physics;
  335. delete this.layoutEngine;
  336. delete this.clustering;
  337. delete this.manipulation;
  338. delete this.nodesHandler;
  339. delete this.edgesHandler;
  340. delete this.configurator;
  341. delete this.images;
  342. for (var nodeId in this.body.nodes) {
  343. delete this.body.nodes[nodeId];
  344. }
  345. for (var edgeId in this.body.edges) {
  346. delete this.body.edges[edgeId];
  347. }
  348. // remove the container and everything inside it recursively
  349. util.recursiveDOMDelete(this.body.container);
  350. };
  351. /**
  352. * Update the values of all object in the given array according to the current
  353. * value range of the objects in the array.
  354. * @param {Object} obj An object containing a set of Edges or Nodes
  355. * The objects must have a method getValue() and
  356. * setValueRange(min, max).
  357. * @private
  358. */
  359. Network.prototype._updateValueRange = function (obj) {
  360. var id;
  361. // determine the range of the objects
  362. var valueMin = undefined;
  363. var valueMax = undefined;
  364. var valueTotal = 0;
  365. for (id in obj) {
  366. if (obj.hasOwnProperty(id)) {
  367. var value = obj[id].getValue();
  368. if (value !== undefined) {
  369. valueMin = (valueMin === undefined) ? value : Math.min(value, valueMin);
  370. valueMax = (valueMax === undefined) ? value : Math.max(value, valueMax);
  371. valueTotal += value;
  372. }
  373. }
  374. }
  375. // adjust the range of all objects
  376. if (valueMin !== undefined && valueMax !== undefined) {
  377. for (id in obj) {
  378. if (obj.hasOwnProperty(id)) {
  379. obj[id].setValueRange(valueMin, valueMax, valueTotal);
  380. }
  381. }
  382. }
  383. };
  384. /**
  385. * Returns true when the Network is active.
  386. * @returns {boolean}
  387. */
  388. Network.prototype.isActive = function () {
  389. return !this.activator || this.activator.active;
  390. };
  391. Network.prototype.setSize = function() {return this.canvas.setSize.apply(this.canvas,arguments);};
  392. Network.prototype.canvasToDOM = function() {return this.canvas.canvasToDOM.apply(this.canvas,arguments);};
  393. Network.prototype.DOMtoCanvas = function() {return this.canvas.DOMtoCanvas.apply(this.canvas,arguments);};
  394. Network.prototype.findNode = function() {return this.clustering.findNode.apply(this.clustering,arguments);};
  395. Network.prototype.isCluster = function() {return this.clustering.isCluster.apply(this.clustering,arguments);};
  396. Network.prototype.openCluster = function() {return this.clustering.openCluster.apply(this.clustering,arguments);};
  397. Network.prototype.cluster = function() {return this.clustering.cluster.apply(this.clustering,arguments);};
  398. Network.prototype.getNodesInCluster = function() {return this.clustering.getNodesInCluster.apply(this.clustering,arguments);};
  399. Network.prototype.clusterByConnection = function() {return this.clustering.clusterByConnection.apply(this.clustering,arguments);};
  400. Network.prototype.clusterByHubsize = function() {return this.clustering.clusterByHubsize.apply(this.clustering,arguments);};
  401. Network.prototype.clusterOutliers = function() {return this.clustering.clusterOutliers.apply(this.clustering,arguments);};
  402. Network.prototype.getSeed = function() {return this.layoutEngine.getSeed.apply(this.layoutEngine,arguments);};
  403. Network.prototype.enableEditMode = function() {return this.manipulation.enableEditMode.apply(this.manipulation,arguments);};
  404. Network.prototype.disableEditMode = function() {return this.manipulation.disableEditMode.apply(this.manipulation,arguments);};
  405. Network.prototype.addNodeMode = function() {return this.manipulation.addNodeMode.apply(this.manipulation,arguments);};
  406. Network.prototype.editNode = function() {return this.manipulation.editNode.apply(this.manipulation,arguments);};
  407. Network.prototype.editNodeMode = function() {console.log("Deprecated: Please use editNode instead of editNodeMode."); return this.manipulation.editNode.apply(this.manipulation,arguments);};
  408. Network.prototype.addEdgeMode = function() {return this.manipulation.addEdgeMode.apply(this.manipulation,arguments);};
  409. Network.prototype.editEdgeMode = function() {return this.manipulation.editEdgeMode.apply(this.manipulation,arguments);};
  410. Network.prototype.deleteSelected = function() {return this.manipulation.deleteSelected.apply(this.manipulation,arguments);};
  411. Network.prototype.getPositions = function() {return this.nodesHandler.getPositions.apply(this.nodesHandler,arguments);};
  412. Network.prototype.storePositions = function() {return this.nodesHandler.storePositions.apply(this.nodesHandler,arguments);};
  413. Network.prototype.moveNode = function() {return this.nodesHandler.moveNode.apply(this.nodesHandler,arguments);};
  414. Network.prototype.getBoundingBox = function() {return this.nodesHandler.getBoundingBox.apply(this.nodesHandler,arguments);};
  415. Network.prototype.getConnectedNodes = function(objectId) {
  416. if (this.body.nodes[objectId] !== undefined) {
  417. return this.nodesHandler.getConnectedNodes.apply(this.nodesHandler,arguments);
  418. }
  419. else {
  420. return this.edgesHandler.getConnectedNodes.apply(this.edgesHandler,arguments);
  421. }
  422. };
  423. Network.prototype.getConnectedEdges = function() {return this.nodesHandler.getConnectedEdges.apply(this.nodesHandler,arguments);};
  424. Network.prototype.startSimulation = function() {return this.physics.startSimulation.apply(this.physics,arguments);};
  425. Network.prototype.stopSimulation = function() {return this.physics.stopSimulation.apply(this.physics,arguments);};
  426. Network.prototype.stabilize = function() {return this.physics.stabilize.apply(this.physics,arguments);};
  427. Network.prototype.getSelection = function() {return this.selectionHandler.getSelection.apply(this.selectionHandler,arguments);};
  428. Network.prototype.setSelection = function() {return this.selectionHandler.setSelection.apply(this.selectionHandler,arguments);};
  429. Network.prototype.getSelectedNodes = function() {return this.selectionHandler.getSelectedNodes.apply(this.selectionHandler,arguments);};
  430. Network.prototype.getSelectedEdges = function() {return this.selectionHandler.getSelectedEdges.apply(this.selectionHandler,arguments);};
  431. Network.prototype.getNodeAt = function() {
  432. var node = this.selectionHandler.getNodeAt.apply(this.selectionHandler,arguments);
  433. if (node !== undefined && node.id !== undefined) {
  434. return node.id;
  435. }
  436. return node;
  437. };
  438. Network.prototype.getEdgeAt = function() {
  439. var edge = this.selectionHandler.getEdgeAt.apply(this.selectionHandler,arguments);
  440. if (edge !== undefined && edge.id !== undefined) {
  441. return edge.id;
  442. }
  443. return edge;
  444. };
  445. Network.prototype.selectNodes = function() {return this.selectionHandler.selectNodes.apply(this.selectionHandler,arguments);};
  446. Network.prototype.selectEdges = function() {return this.selectionHandler.selectEdges.apply(this.selectionHandler,arguments);};
  447. Network.prototype.unselectAll = function() {
  448. this.selectionHandler.unselectAll.apply(this.selectionHandler,arguments);
  449. this.redraw();
  450. };
  451. Network.prototype.redraw = function() {return this.renderer.redraw.apply(this.renderer,arguments);};
  452. Network.prototype.getScale = function() {return this.view.getScale.apply(this.view,arguments);};
  453. Network.prototype.getViewPosition = function() {return this.view.getViewPosition.apply(this.view,arguments);};
  454. Network.prototype.fit = function() {return this.view.fit.apply(this.view,arguments);};
  455. Network.prototype.moveTo = function() {return this.view.moveTo.apply(this.view,arguments);};
  456. Network.prototype.focus = function() {return this.view.focus.apply(this.view,arguments);};
  457. Network.prototype.releaseNode = function() {return this.view.releaseNode.apply(this.view,arguments);};
  458. Network.prototype.getOptionsFromConfigurator = function() {
  459. let options = {};
  460. if (this.configurator) {
  461. options = this.configurator.getOptions.apply(this.configurator);
  462. }
  463. return options;
  464. };
  465. module.exports = Network;