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.

508 lines
22 KiB

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