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.

349 lines
12 KiB

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