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.

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