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.

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