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.

359 lines
12 KiB

9 years ago
10 years ago
  1. // Load custom shapes into CanvasRenderingContext2D
  2. require('./shapes');
  3. var Emitter = require('emitter-component');
  4. var Hammer = require('../module/hammer');
  5. var util = require('../util');
  6. var DataSet = require('../DataSet');
  7. var DataView = require('../DataView');
  8. var dotparser = require('./dotparser');
  9. var gephiParser = require('./gephiParser');
  10. var Images = require('./Images');
  11. var Activator = require('../shared/Activator');
  12. import Groups from './modules/Groups';
  13. import NodesHandler from './modules/NodesHandler';
  14. import EdgesHandler from './modules/EdgesHandler';
  15. import PhysicsEngine from './modules/PhysicsEngine';
  16. import ClusterEngine from './modules/Clustering';
  17. import CanvasRenderer from './modules/CanvasRenderer';
  18. import Canvas from './modules/Canvas';
  19. import View from './modules/View';
  20. import InteractionHandler from './modules/InteractionHandler';
  21. import SelectionHandler from "./modules/SelectionHandler";
  22. import LayoutEngine from "./modules/LayoutEngine";
  23. import ManipulationSystem from "./modules/ManipulationSystem";
  24. import ConfigurationSystem from "./modules/ConfigurationSystem";
  25. import Validator from "./modules/Validator";
  26. import {printStyle} from "./modules/Validator";
  27. import allOptions from './modules/components/AllOptions.js';
  28. /**
  29. * @constructor Network
  30. * Create a network visualization, displaying nodes and edges.
  31. *
  32. * @param {Element} container The DOM element in which the Network will
  33. * be created. Normally a div element.
  34. * @param {Object} data An object containing parameters
  35. * {Array} nodes
  36. * {Array} edges
  37. * @param {Object} options Options
  38. */
  39. function Network (container, data, options) {
  40. if (!(this instanceof Network)) {
  41. throw new SyntaxError('Constructor must be called with the new operator');
  42. }
  43. // set constant values
  44. this.options = {};
  45. this.defaultOptions = {
  46. clickToUse: false
  47. };
  48. util.extend(this.options, this.defaultOptions);
  49. // containers for nodes and edges
  50. this.body = {
  51. nodes: {},
  52. nodeIndices: [],
  53. edges: {},
  54. edgeIndices: [],
  55. data: {
  56. nodes: null, // A DataSet or DataView
  57. edges: null // A DataSet or DataView
  58. },
  59. functions:{
  60. createNode: () => {},
  61. createEdge: () => {},
  62. getPointer: () => {}
  63. },
  64. emitter: {
  65. on: this.on.bind(this),
  66. off: this.off.bind(this),
  67. emit: this.emit.bind(this),
  68. once: this.once.bind(this)
  69. },
  70. eventListeners: {
  71. onTap: function() {},
  72. onTouch: function() {},
  73. onDoubleTap: function() {},
  74. onHold: function() {},
  75. onDragStart: function() {},
  76. onDrag: function() {},
  77. onDragEnd: function() {},
  78. onMouseWheel: function() {},
  79. onPinch: function() {},
  80. onMouseMove: function() {},
  81. onRelease: function() {},
  82. onContext: function() {}
  83. },
  84. container: container,
  85. view: {
  86. scale:1,
  87. translation:{x:0,y:0}
  88. }
  89. };
  90. // bind the event listeners
  91. this.bindEventListeners();
  92. // setting up all modules
  93. var images = new Images(() => this.body.emitter.emit("_requestRedraw")); // object with images
  94. this.groups = new Groups(); // object with groups
  95. this.canvas = new Canvas(this.body); // DOM handler
  96. this.selectionHandler = new SelectionHandler(this.body, this.canvas); // Selection handler
  97. this.interactionHandler = new InteractionHandler(this.body, this.canvas, this.selectionHandler); // Interaction handler handles all the hammer bindings (that are bound by canvas), key
  98. this.view = new View(this.body, this.canvas); // camera handler, does animations and zooms
  99. this.renderer = new CanvasRenderer(this.body, this.canvas); // renderer, starts renderloop, has events that modules can hook into
  100. this.physics = new PhysicsEngine(this.body); // physics engine, does all the simulations
  101. this.layoutEngine = new LayoutEngine(this.body); // layout engine for inital layout and hierarchical layout
  102. this.clustering = new ClusterEngine(this.body); // clustering api
  103. this.manipulation = new ManipulationSystem(this.body, this.canvas, this.selectionHandler); // data manipulation system
  104. this.nodesHandler = new NodesHandler(this.body, images, this.groups, this.layoutEngine); // Handle adding, deleting and updating of nodes as well as global options
  105. this.edgesHandler = new EdgesHandler(this.body, images, this.groups); // Handle adding, deleting and updating of edges as well as global options
  106. this.configurationSystem = new ConfigurationSystem(this);
  107. // create the DOM elements
  108. this.canvas._create();
  109. // apply options
  110. this.setOptions(options);
  111. // load data (the disable start variable will be the same as the enabled clustering)
  112. this.setData(data);
  113. }
  114. // Extend Network with an Emitter mixin
  115. Emitter(Network.prototype);
  116. /**
  117. * Set options
  118. * @param {Object} options
  119. */
  120. Network.prototype.setOptions = function (options) {
  121. if (options !== undefined) {
  122. let errorFound = Validator.validate(options,allOptions);
  123. if (errorFound === true) {
  124. options = {};
  125. console.log('%cErrors have been found in the supplied options object. None of the options will be used.', printStyle);
  126. }
  127. // the hierarchical system can adapt the edges and the physics to it's own options because not all combinations work with the hierarichical system.
  128. options = this.layoutEngine.setOptions(options.layout, options);
  129. // pass the options to the modules
  130. this.groups.setOptions(options.groups);
  131. this.nodesHandler.setOptions(options.nodes);
  132. this.edgesHandler.setOptions(options.edges);
  133. this.physics.setOptions(options.physics);
  134. this.canvas.setOptions(options.canvas);
  135. this.renderer.setOptions(options.rendering);
  136. this.view.setOptions(options.view);
  137. this.interactionHandler.setOptions(options.interaction);
  138. this.selectionHandler.setOptions(options.selection);
  139. this.clustering.setOptions(options.clustering);
  140. this.manipulation.setOptions(options.manipulation);
  141. this.configurationSystem.setOptions(options);
  142. // handle network global options
  143. if (options.clickToUse !== undefined) {
  144. if (options.clickToUse === true) {
  145. if (this.activator === undefined) {
  146. this.activator = new Activator(this.frame);
  147. this.activator.on('change', this._createKeyBinds.bind(this));
  148. }
  149. }
  150. else {
  151. if (this.activator !== undefined) {
  152. this.activator.destroy();
  153. delete this.activator;
  154. }
  155. this.body.emitter.emit("activate");
  156. }
  157. }
  158. else {
  159. this.body.emitter.emit("activate");
  160. }
  161. this.canvas.setSize();
  162. // start the physics simulation. Can be safely called multiple times.
  163. this.body.emitter.emit("startSimulation");
  164. }
  165. };
  166. /**
  167. * Update the this.body.nodeIndices with the most recent node index list
  168. * @private
  169. */
  170. Network.prototype._updateVisibleIndices = function() {
  171. let nodes = this.body.nodes;
  172. let edges = this.body.edges;
  173. this.body.nodeIndices = [];
  174. this.body.edgeIndices = [];
  175. for (let nodeId in nodes) {
  176. if (nodes.hasOwnProperty(nodeId)) {
  177. if (nodes[nodeId].options.hidden === false) {
  178. this.body.nodeIndices.push(nodeId);
  179. }
  180. }
  181. }
  182. for (let edgeId in edges) {
  183. if (edges.hasOwnProperty(edgeId)) {
  184. if (edges[edgeId].options.hidden === false) {
  185. this.body.edgeIndices.push(edgeId);
  186. }
  187. }
  188. }
  189. };
  190. Network.prototype.bindEventListeners = function() {
  191. // this event will trigger a rebuilding of the cache everything. Used when nodes or edges have been added or removed.
  192. this.body.emitter.on("_dataChanged", (params) => {
  193. // update shortcut lists
  194. this._updateVisibleIndices();
  195. this.physics.updatePhysicsIndices();
  196. // call the dataUpdated event because the only difference between the two is the updating of the indices
  197. this.body.emitter.emit("_dataUpdated");
  198. });
  199. // this is called when options of EXISTING nodes or edges have changed.
  200. this.body.emitter.on("_dataUpdated", () => {
  201. // update values
  202. this._updateValueRange(this.body.nodes);
  203. this._updateValueRange(this.body.edges);
  204. // start simulation (can be called safely, even if already running)
  205. this.body.emitter.emit("startSimulation");
  206. });
  207. }
  208. /**
  209. * Set nodes and edges, and optionally options as well.
  210. *
  211. * @param {Object} data Object containing parameters:
  212. * {Array | DataSet | DataView} [nodes] Array with nodes
  213. * {Array | DataSet | DataView} [edges] Array with edges
  214. * {String} [dot] String containing data in DOT format
  215. * {String} [gephi] String containing data in gephi JSON format
  216. * {Options} [options] Object with options
  217. * @param {Boolean} [disableStart] | optional: disable the calling of the start function.
  218. */
  219. Network.prototype.setData = function(data) {
  220. // reset the physics engine.
  221. this.body.emitter.emit("resetPhysics");
  222. this.body.emitter.emit("_resetData");
  223. // unselect all to ensure no selections from old data are carried over.
  224. this.selectionHandler.unselectAll();
  225. if (data && data.dot && (data.nodes || data.edges)) {
  226. throw new SyntaxError('Data must contain either parameter "dot" or ' +
  227. ' parameter pair "nodes" and "edges", but not both.');
  228. }
  229. // set options
  230. this.setOptions(data && data.options);
  231. // set all data
  232. if (data && data.dot) {
  233. // parse DOT file
  234. if(data && data.dot) {
  235. var dotData = dotparser.DOTToGraph(data.dot);
  236. this.setData(dotData);
  237. return;
  238. }
  239. }
  240. else if (data && data.gephi) {
  241. // parse DOT file
  242. if(data && data.gephi) {
  243. var gephiData = gephiParser.parseGephi(data.gephi);
  244. this.setData(gephiData);
  245. return;
  246. }
  247. }
  248. else {
  249. this.nodesHandler.setData(data && data.nodes, true);
  250. this.edgesHandler.setData(data && data.edges, true);
  251. }
  252. // emit change in data
  253. this.body.emitter.emit("_dataChanged");
  254. // find a stable position or start animating to a stable position
  255. this.body.emitter.emit("initPhysics");
  256. };
  257. /**
  258. * Cleans up all bindings of the network, removing it fully from the memory IF the variable is set to null after calling this function.
  259. * var network = new vis.Network(..);
  260. * network.destroy();
  261. * network = null;
  262. */
  263. Network.prototype.destroy = function() {
  264. this.body.emitter.emit("destroy");
  265. // clear events
  266. this.body.emitter.off();
  267. this.off();
  268. // remove the container and everything inside it recursively
  269. util.recursiveDOMDelete(this.body.container);
  270. };
  271. /**
  272. * Update the values of all object in the given array according to the current
  273. * value range of the objects in the array.
  274. * @param {Object} obj An object containing a set of Edges or Nodes
  275. * The objects must have a method getValue() and
  276. * setValueRange(min, max).
  277. * @private
  278. */
  279. Network.prototype._updateValueRange = function(obj) {
  280. var id;
  281. // determine the range of the objects
  282. var valueMin = undefined;
  283. var valueMax = undefined;
  284. var valueTotal = 0;
  285. for (id in obj) {
  286. if (obj.hasOwnProperty(id)) {
  287. var value = obj[id].getValue();
  288. if (value !== undefined) {
  289. valueMin = (valueMin === undefined) ? value : Math.min(value, valueMin);
  290. valueMax = (valueMax === undefined) ? value : Math.max(value, valueMax);
  291. valueTotal += value;
  292. }
  293. }
  294. }
  295. // adjust the range of all objects
  296. if (valueMin !== undefined && valueMax !== undefined) {
  297. for (id in obj) {
  298. if (obj.hasOwnProperty(id)) {
  299. obj[id].setValueRange(valueMin, valueMax, valueTotal);
  300. }
  301. }
  302. }
  303. };
  304. /**
  305. * Returns true when the Network is active.
  306. * @returns {boolean}
  307. */
  308. Network.prototype.isActive = function () {
  309. return !this.activator || this.activator.active;
  310. };
  311. module.exports = Network;