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.

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