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.

567 lines
24 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
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 === null) {
  137. options = undefined; // This ensures that options handling doesn't crash in the handling
  138. }
  139. if (options !== undefined) {
  140. let errorFound = Validator.validate(options, allOptions);
  141. if (errorFound === true) {
  142. console.log('%cErrors have been found in the supplied options object.', printStyle);
  143. }
  144. // copy the global fields over
  145. let fields = ['locale','locales','clickToUse'];
  146. util.selectiveDeepExtend(fields,this.options, options);
  147. // the hierarchical system can adapt the edges and the physics to it's own options because not all combinations work with the hierarichical system.
  148. options = this.layoutEngine.setOptions(options.layout, options);
  149. this.canvas.setOptions(options); // options for canvas are in globals
  150. // pass the options to the modules
  151. this.groups.setOptions(options.groups);
  152. this.nodesHandler.setOptions(options.nodes);
  153. this.edgesHandler.setOptions(options.edges);
  154. this.physics.setOptions(options.physics);
  155. this.manipulation.setOptions(options.manipulation, options, this.options); // manipulation uses the locales in the globals
  156. this.interactionHandler.setOptions(options.interaction);
  157. this.renderer.setOptions(options.interaction); // options for rendering are in interaction
  158. this.selectionHandler.setOptions(options.interaction); // options for selection are in interaction
  159. // reload the settings of the nodes to apply changes in groups that are not referenced by pointer.
  160. if (options.groups !== undefined) {
  161. this.body.emitter.emit("refreshNodes");
  162. }
  163. // these two do not have options at the moment, here for completeness
  164. //this.view.setOptions(options.view);
  165. //this.clustering.setOptions(options.clustering);
  166. if ('configure' in options) {
  167. if (!this.configurator) {
  168. this.configurator = new Configurator(this, this.body.container, configureOptions, this.canvas.pixelRatio);
  169. }
  170. this.configurator.setOptions(options.configure);
  171. }
  172. // if the configuration system is enabled, copy all options and put them into the config system
  173. if (this.configurator && this.configurator.options.enabled === true) {
  174. let networkOptions = {nodes:{},edges:{},layout:{},interaction:{},manipulation:{},physics:{},global:{}};
  175. util.deepExtend(networkOptions.nodes, this.nodesHandler.options);
  176. util.deepExtend(networkOptions.edges, this.edgesHandler.options);
  177. util.deepExtend(networkOptions.layout, this.layoutEngine.options);
  178. // load the selectionHandler and render default options in to the interaction group
  179. util.deepExtend(networkOptions.interaction, this.selectionHandler.options);
  180. util.deepExtend(networkOptions.interaction, this.renderer.options);
  181. util.deepExtend(networkOptions.interaction, this.interactionHandler.options);
  182. util.deepExtend(networkOptions.manipulation, this.manipulation.options);
  183. util.deepExtend(networkOptions.physics, this.physics.options);
  184. // load globals into the global object
  185. util.deepExtend(networkOptions.global, this.canvas.options);
  186. util.deepExtend(networkOptions.global, this.options);
  187. this.configurator.setModuleOptions(networkOptions);
  188. }
  189. // handle network global options
  190. if (options.clickToUse !== undefined) {
  191. if (options.clickToUse === true) {
  192. if (this.activator === undefined) {
  193. this.activator = new Activator(this.canvas.frame);
  194. this.activator.on('change', () => {this.body.emitter.emit("activate")});
  195. }
  196. }
  197. else {
  198. if (this.activator !== undefined) {
  199. this.activator.destroy();
  200. delete this.activator;
  201. }
  202. this.body.emitter.emit("activate");
  203. }
  204. }
  205. else {
  206. this.body.emitter.emit("activate");
  207. }
  208. this.canvas.setSize();
  209. // start the physics simulation. Can be safely called multiple times.
  210. this.body.emitter.emit("startSimulation");
  211. }
  212. };
  213. /**
  214. * Update the visible nodes and edges list with the most recent node state.
  215. *
  216. * Visible nodes are stored in this.body.nodeIndices.
  217. * Visible edges are stored in this.body.edgeIndices.
  218. * A node or edges is visible if it is not hidden or clustered.
  219. *
  220. * @private
  221. */
  222. Network.prototype._updateVisibleIndices = function () {
  223. let nodes = this.body.nodes;
  224. let edges = this.body.edges;
  225. this.body.nodeIndices = [];
  226. this.body.edgeIndices = [];
  227. for (let nodeId in nodes) {
  228. if (nodes.hasOwnProperty(nodeId)) {
  229. if (!this.clustering._isClusteredNode(nodeId) && nodes[nodeId].options.hidden === false) {
  230. this.body.nodeIndices.push(nodes[nodeId].id);
  231. }
  232. }
  233. }
  234. for (let edgeId in edges) {
  235. if (edges.hasOwnProperty(edgeId)) {
  236. let edge = edges[edgeId];
  237. // It can happen that this is executed *after* a node edge has been removed,
  238. // but *before* the edge itself has been removed. Taking this into account.
  239. let fromNode = nodes[edge.fromId];
  240. let toNode = nodes[edge.toId];
  241. let edgeNodesPresent = (fromNode !== undefined) && (toNode !== undefined);
  242. let isVisible =
  243. !this.clustering._isClusteredEdge(edgeId)
  244. && edge.options.hidden === false
  245. && edgeNodesPresent
  246. && fromNode.options.hidden === false // Also hidden if any of its connecting nodes are hidden
  247. && toNode.options.hidden === false; // idem
  248. if (isVisible) {
  249. this.body.edgeIndices.push(edge.id);
  250. }
  251. }
  252. }
  253. };
  254. /**
  255. * Bind all events
  256. */
  257. Network.prototype.bindEventListeners = function () {
  258. // This event will trigger a rebuilding of the cache everything.
  259. // Used when nodes or edges have been added or removed.
  260. this.body.emitter.on("_dataChanged", () => {
  261. this.edgesHandler._updateState();
  262. this.body.emitter.emit("_dataUpdated");
  263. });
  264. // this is called when options of EXISTING nodes or edges have changed.
  265. this.body.emitter.on("_dataUpdated", () => {
  266. // Order important in following block
  267. this.clustering._updateState();
  268. this._updateVisibleIndices();
  269. this._updateValueRange(this.body.nodes);
  270. this._updateValueRange(this.body.edges);
  271. // start simulation (can be called safely, even if already running)
  272. this.body.emitter.emit("startSimulation");
  273. this.body.emitter.emit("_requestRedraw");
  274. });
  275. };
  276. /**
  277. * Set nodes and edges, and optionally options as well.
  278. *
  279. * @param {Object} data Object containing parameters:
  280. * {Array | DataSet | DataView} [nodes] Array with nodes
  281. * {Array | DataSet | DataView} [edges] Array with edges
  282. * {String} [dot] String containing data in DOT format
  283. * {String} [gephi] String containing data in gephi JSON format
  284. * {Options} [options] Object with options
  285. */
  286. Network.prototype.setData = function (data) {
  287. // reset the physics engine.
  288. this.body.emitter.emit("resetPhysics");
  289. this.body.emitter.emit("_resetData");
  290. // unselect all to ensure no selections from old data are carried over.
  291. this.selectionHandler.unselectAll();
  292. if (data && data.dot && (data.nodes || data.edges)) {
  293. throw new SyntaxError('Data must contain either parameter "dot" or ' +
  294. ' parameter pair "nodes" and "edges", but not both.');
  295. }
  296. // set options
  297. this.setOptions(data && data.options);
  298. // set all data
  299. if (data && data.dot) {
  300. 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);');
  301. // parse DOT file
  302. var dotData = dotparser.DOTToGraph(data.dot);
  303. this.setData(dotData);
  304. return;
  305. }
  306. else if (data && data.gephi) {
  307. // parse DOT file
  308. 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);');
  309. var gephiData = gephiParser.parseGephi(data.gephi);
  310. this.setData(gephiData);
  311. return;
  312. }
  313. else {
  314. this.nodesHandler.setData(data && data.nodes, true);
  315. this.edgesHandler.setData(data && data.edges, true);
  316. }
  317. // emit change in data
  318. this.body.emitter.emit("_dataChanged");
  319. // emit data loaded
  320. this.body.emitter.emit("_dataLoaded");
  321. // find a stable position or start animating to a stable position
  322. this.body.emitter.emit("initPhysics");
  323. };
  324. /**
  325. * Cleans up all bindings of the network, removing it fully from the memory IF the variable is set to null after calling this function.
  326. * var network = new vis.Network(..);
  327. * network.destroy();
  328. * network = null;
  329. */
  330. Network.prototype.destroy = function () {
  331. this.body.emitter.emit("destroy");
  332. // clear events
  333. this.body.emitter.off();
  334. this.off();
  335. // delete modules
  336. delete this.groups;
  337. delete this.canvas;
  338. delete this.selectionHandler;
  339. delete this.interactionHandler;
  340. delete this.view;
  341. delete this.renderer;
  342. delete this.physics;
  343. delete this.layoutEngine;
  344. delete this.clustering;
  345. delete this.manipulation;
  346. delete this.nodesHandler;
  347. delete this.edgesHandler;
  348. delete this.configurator;
  349. delete this.images;
  350. for (var nodeId in this.body.nodes) {
  351. if (!this.body.nodes.hasOwnProperty(nodeId)) continue;
  352. delete this.body.nodes[nodeId];
  353. }
  354. for (var edgeId in this.body.edges) {
  355. if (!this.body.edges.hasOwnProperty(edgeId)) continue;
  356. delete this.body.edges[edgeId];
  357. }
  358. // remove the container and everything inside it recursively
  359. util.recursiveDOMDelete(this.body.container);
  360. };
  361. /**
  362. * Update the values of all object in the given array according to the current
  363. * value range of the objects in the array.
  364. * @param {Object} obj An object containing a set of Edges or Nodes
  365. * The objects must have a method getValue() and
  366. * setValueRange(min, max).
  367. * @private
  368. */
  369. Network.prototype._updateValueRange = function (obj) {
  370. var id;
  371. // determine the range of the objects
  372. var valueMin = undefined;
  373. var valueMax = undefined;
  374. var valueTotal = 0;
  375. for (id in obj) {
  376. if (obj.hasOwnProperty(id)) {
  377. var value = obj[id].getValue();
  378. if (value !== undefined) {
  379. valueMin = (valueMin === undefined) ? value : Math.min(value, valueMin);
  380. valueMax = (valueMax === undefined) ? value : Math.max(value, valueMax);
  381. valueTotal += value;
  382. }
  383. }
  384. }
  385. // adjust the range of all objects
  386. if (valueMin !== undefined && valueMax !== undefined) {
  387. for (id in obj) {
  388. if (obj.hasOwnProperty(id)) {
  389. obj[id].setValueRange(valueMin, valueMax, valueTotal);
  390. }
  391. }
  392. }
  393. };
  394. /**
  395. * Returns true when the Network is active.
  396. * @returns {boolean}
  397. */
  398. Network.prototype.isActive = function () {
  399. return !this.activator || this.activator.active;
  400. };
  401. Network.prototype.setSize = function() {return this.canvas.setSize.apply(this.canvas,arguments);};
  402. Network.prototype.canvasToDOM = function() {return this.canvas.canvasToDOM.apply(this.canvas,arguments);};
  403. Network.prototype.DOMtoCanvas = function() {return this.canvas.DOMtoCanvas.apply(this.canvas,arguments);};
  404. /**
  405. * Nodes can be in clusters. Clusters can also be in clusters. This function returns and array of
  406. * nodeIds showing where the node is.
  407. *
  408. * If any nodeId in the chain, especially the first passed in as a parameter, is not present in
  409. * the current nodes list, an empty array is returned.
  410. *
  411. * Example:
  412. * cluster 'A' contains cluster 'B',
  413. * cluster 'B' contains cluster 'C',
  414. * cluster 'C' contains node 'fred'.
  415. * `jsnetwork.clustering.findNode('fred')` will return `['A','B','C','fred']`.
  416. *
  417. * @param {string|number} nodeId
  418. * @returns {Array}
  419. */
  420. Network.prototype.findNode = function() {return this.clustering.findNode.apply(this.clustering,arguments);};
  421. Network.prototype.isCluster = function() {return this.clustering.isCluster.apply(this.clustering,arguments);};
  422. Network.prototype.openCluster = function() {return this.clustering.openCluster.apply(this.clustering,arguments);};
  423. Network.prototype.cluster = function() {return this.clustering.cluster.apply(this.clustering,arguments);};
  424. Network.prototype.getNodesInCluster = function() {return this.clustering.getNodesInCluster.apply(this.clustering,arguments);};
  425. Network.prototype.clusterByConnection = function() {return this.clustering.clusterByConnection.apply(this.clustering,arguments);};
  426. Network.prototype.clusterByHubsize = function() {return this.clustering.clusterByHubsize.apply(this.clustering,arguments);};
  427. Network.prototype.clusterOutliers = function() {return this.clustering.clusterOutliers.apply(this.clustering,arguments);};
  428. Network.prototype.getSeed = function() {return this.layoutEngine.getSeed.apply(this.layoutEngine,arguments);};
  429. Network.prototype.enableEditMode = function() {return this.manipulation.enableEditMode.apply(this.manipulation,arguments);};
  430. Network.prototype.disableEditMode = function() {return this.manipulation.disableEditMode.apply(this.manipulation,arguments);};
  431. Network.prototype.addNodeMode = function() {return this.manipulation.addNodeMode.apply(this.manipulation,arguments);};
  432. Network.prototype.editNode = function() {return this.manipulation.editNode.apply(this.manipulation,arguments);};
  433. Network.prototype.editNodeMode = function() {console.log("Deprecated: Please use editNode instead of editNodeMode."); return this.manipulation.editNode.apply(this.manipulation,arguments);};
  434. Network.prototype.addEdgeMode = function() {return this.manipulation.addEdgeMode.apply(this.manipulation,arguments);};
  435. Network.prototype.editEdgeMode = function() {return this.manipulation.editEdgeMode.apply(this.manipulation,arguments);};
  436. Network.prototype.deleteSelected = function() {return this.manipulation.deleteSelected.apply(this.manipulation,arguments);};
  437. Network.prototype.getPositions = function() {return this.nodesHandler.getPositions.apply(this.nodesHandler,arguments);};
  438. Network.prototype.storePositions = function() {return this.nodesHandler.storePositions.apply(this.nodesHandler,arguments);};
  439. Network.prototype.moveNode = function() {return this.nodesHandler.moveNode.apply(this.nodesHandler,arguments);};
  440. Network.prototype.getBoundingBox = function() {return this.nodesHandler.getBoundingBox.apply(this.nodesHandler,arguments);};
  441. Network.prototype.getConnectedNodes = function(objectId) {
  442. if (this.body.nodes[objectId] !== undefined) {
  443. return this.nodesHandler.getConnectedNodes.apply(this.nodesHandler,arguments);
  444. }
  445. else {
  446. return this.edgesHandler.getConnectedNodes.apply(this.edgesHandler,arguments);
  447. }
  448. };
  449. Network.prototype.getConnectedEdges = function() {return this.nodesHandler.getConnectedEdges.apply(this.nodesHandler,arguments);};
  450. Network.prototype.startSimulation = function() {return this.physics.startSimulation.apply(this.physics,arguments);};
  451. Network.prototype.stopSimulation = function() {return this.physics.stopSimulation.apply(this.physics,arguments);};
  452. Network.prototype.stabilize = function() {return this.physics.stabilize.apply(this.physics,arguments);};
  453. Network.prototype.getSelection = function() {return this.selectionHandler.getSelection.apply(this.selectionHandler,arguments);};
  454. Network.prototype.setSelection = function() {return this.selectionHandler.setSelection.apply(this.selectionHandler,arguments);};
  455. Network.prototype.getSelectedNodes = function() {return this.selectionHandler.getSelectedNodes.apply(this.selectionHandler,arguments);};
  456. Network.prototype.getSelectedEdges = function() {return this.selectionHandler.getSelectedEdges.apply(this.selectionHandler,arguments);};
  457. Network.prototype.getNodeAt = function() {
  458. var node = this.selectionHandler.getNodeAt.apply(this.selectionHandler,arguments);
  459. if (node !== undefined && node.id !== undefined) {
  460. return node.id;
  461. }
  462. return node;
  463. };
  464. Network.prototype.getEdgeAt = function() {
  465. var edge = this.selectionHandler.getEdgeAt.apply(this.selectionHandler,arguments);
  466. if (edge !== undefined && edge.id !== undefined) {
  467. return edge.id;
  468. }
  469. return edge;
  470. };
  471. Network.prototype.selectNodes = function() {return this.selectionHandler.selectNodes.apply(this.selectionHandler,arguments);};
  472. Network.prototype.selectEdges = function() {return this.selectionHandler.selectEdges.apply(this.selectionHandler,arguments);};
  473. Network.prototype.unselectAll = function() {
  474. this.selectionHandler.unselectAll.apply(this.selectionHandler,arguments);
  475. this.redraw();
  476. };
  477. Network.prototype.redraw = function() {return this.renderer.redraw.apply(this.renderer,arguments);};
  478. Network.prototype.getScale = function() {return this.view.getScale.apply(this.view,arguments);};
  479. Network.prototype.getViewPosition = function() {return this.view.getViewPosition.apply(this.view,arguments);};
  480. Network.prototype.fit = function() {return this.view.fit.apply(this.view,arguments);};
  481. Network.prototype.moveTo = function() {return this.view.moveTo.apply(this.view,arguments);};
  482. Network.prototype.focus = function() {return this.view.focus.apply(this.view,arguments);};
  483. Network.prototype.releaseNode = function() {return this.view.releaseNode.apply(this.view,arguments);};
  484. Network.prototype.getOptionsFromConfigurator = function() {
  485. let options = {};
  486. if (this.configurator) {
  487. options = this.configurator.getOptions.apply(this.configurator);
  488. }
  489. return options;
  490. };
  491. module.exports = Network;