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.

465 lines
15 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. /**
  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. },
  80. container: container,
  81. view: {
  82. scale:1,
  83. translation:{x:0,y:0}
  84. }
  85. };
  86. // bind the event listeners
  87. this.bindEventListeners();
  88. // setting up all modules
  89. var images = new Images(() => this.body.emitter.emit("_requestRedraw")); // object with images
  90. this.groups = new Groups(); // object with groups
  91. this.canvas = new Canvas(this.body); // DOM handler
  92. this.selectionHandler = new SelectionHandler(this.body, this.canvas); // Selection handler
  93. this.interactionHandler = new InteractionHandler(this.body, this.canvas, this.selectionHandler); // Interaction handler handles all the hammer bindings (that are bound by canvas), key
  94. this.view = new View(this.body, this.canvas); // camera handler, does animations and zooms
  95. this.renderer = new CanvasRenderer(this.body, this.canvas); // renderer, starts renderloop, has events that modules can hook into
  96. this.physics = new PhysicsEngine(this.body); // physics engine, does all the simulations
  97. this.layoutEngine = new LayoutEngine(this.body); // layout engine for inital layout and hierarchical layout
  98. this.clustering = new ClusterEngine(this.body); // clustering api
  99. this.manipulation = new ManipulationSystem(this.body, this.canvas, this.selectionHandler); // data manipulation system
  100. this.nodesHandler = new NodesHandler(this.body, images, this.groups, this.layoutEngine); // Handle adding, deleting and updating of nodes as well as global options
  101. this.edgesHandler = new EdgesHandler(this.body, images, this.groups); // Handle adding, deleting and updating of edges as well as global options
  102. this.configurationSystem = new ConfigurationSystem(this);
  103. // create the DOM elements
  104. this.canvas._create();
  105. // apply options
  106. this.setOptions(options);
  107. // load data (the disable start variable will be the same as the enabled clustering)
  108. this.setData(data);
  109. }
  110. // Extend Network with an Emitter mixin
  111. Emitter(Network.prototype);
  112. /**
  113. * Set options
  114. * @param {Object} options
  115. */
  116. Network.prototype.setOptions = function (options) {
  117. if (options !== undefined) {
  118. // the hierarchical system can adapt the edges and the physics to it's own options because not all combinations work with the hierarichical system.
  119. options = this.layoutEngine.setOptions(options.layout, options);
  120. // pass the options to the modules
  121. this.groups.setOptions(options.groups);
  122. this.nodesHandler.setOptions(options.nodes);
  123. this.edgesHandler.setOptions(options.edges);
  124. this.physics.setOptions(options.physics);
  125. this.canvas.setOptions(options.canvas);
  126. this.renderer.setOptions(options.rendering);
  127. this.view.setOptions(options.view);
  128. this.interactionHandler.setOptions(options.interaction);
  129. this.selectionHandler.setOptions(options.selection);
  130. this.clustering.setOptions(options.clustering);
  131. this.manipulation.setOptions(options.manipulation);
  132. this.configurationSystem.setOptions(options);
  133. // handle network global options
  134. if (options.clickToUse !== undefined) {
  135. if (options.clickToUse === true) {
  136. if (this.activator === undefined) {
  137. this.activator = new Activator(this.frame);
  138. this.activator.on('change', this._createKeyBinds.bind(this));
  139. }
  140. }
  141. else {
  142. if (this.activator !== undefined) {
  143. this.activator.destroy();
  144. delete this.activator;
  145. }
  146. this.body.emitter.emit("activate");
  147. }
  148. }
  149. else {
  150. this.body.emitter.emit("activate");
  151. }
  152. this.canvas.setSize();
  153. // start the physics simulation. Can be safely called multiple times.
  154. this.body.emitter.emit("startSimulation");
  155. }
  156. };
  157. /**
  158. * Update the this.body.nodeIndices with the most recent node index list
  159. * @private
  160. */
  161. Network.prototype._updateVisibleIndices = function() {
  162. let nodes = this.body.nodes;
  163. let edges = this.body.edges;
  164. this.body.nodeIndices = [];
  165. this.body.edgeIndices = [];
  166. for (let nodeId in nodes) {
  167. if (nodes.hasOwnProperty(nodeId)) {
  168. if (nodes[nodeId].options.hidden === false) {
  169. this.body.nodeIndices.push(nodeId);
  170. }
  171. }
  172. }
  173. for (let edgeId in edges) {
  174. if (edges.hasOwnProperty(edgeId)) {
  175. if (edges[edgeId].options.hidden === false) {
  176. this.body.edgeIndices.push(edgeId);
  177. }
  178. }
  179. }
  180. };
  181. Network.prototype.bindEventListeners = function() {
  182. // this event will trigger a rebuilding of the cache everything. Used when nodes or edges have been added or removed.
  183. this.body.emitter.on("_dataChanged", (params) => {
  184. // update shortcut lists
  185. this._updateVisibleIndices();
  186. this.physics.updatePhysicsIndices();
  187. // call the dataUpdated event because the only difference between the two is the updating of the indices
  188. this.body.emitter.emit("_dataUpdated");
  189. });
  190. // this is called when options of EXISTING nodes or edges have changed.
  191. this.body.emitter.on("_dataUpdated", () => {
  192. // update values
  193. this._updateValueRange(this.body.nodes);
  194. this._updateValueRange(this.body.edges);
  195. // start simulation (can be called safely, even if already running)
  196. this.body.emitter.emit("startSimulation");
  197. });
  198. }
  199. /**
  200. * Set nodes and edges, and optionally options as well.
  201. *
  202. * @param {Object} data Object containing parameters:
  203. * {Array | DataSet | DataView} [nodes] Array with nodes
  204. * {Array | DataSet | DataView} [edges] Array with edges
  205. * {String} [dot] String containing data in DOT format
  206. * {String} [gephi] String containing data in gephi JSON format
  207. * {Options} [options] Object with options
  208. * @param {Boolean} [disableStart] | optional: disable the calling of the start function.
  209. */
  210. Network.prototype.setData = function(data) {
  211. // reset the physics engine.
  212. this.body.emitter.emit("resetPhysics");
  213. this.body.emitter.emit("_resetData");
  214. // unselect all to ensure no selections from old data are carried over.
  215. this.selectionHandler.unselectAll();
  216. if (data && data.dot && (data.nodes || data.edges)) {
  217. throw new SyntaxError('Data must contain either parameter "dot" or ' +
  218. ' parameter pair "nodes" and "edges", but not both.');
  219. }
  220. // set options
  221. this.setOptions(data && data.options);
  222. // set all data
  223. if (data && data.dot) {
  224. // parse DOT file
  225. if(data && data.dot) {
  226. var dotData = dotparser.DOTToGraph(data.dot);
  227. this.setData(dotData);
  228. return;
  229. }
  230. }
  231. else if (data && data.gephi) {
  232. // parse DOT file
  233. if(data && data.gephi) {
  234. var gephiData = gephiParser.parseGephi(data.gephi);
  235. this.setData(gephiData);
  236. return;
  237. }
  238. }
  239. else {
  240. this.nodesHandler.setData(data && data.nodes, true);
  241. this.edgesHandler.setData(data && data.edges, true);
  242. }
  243. // emit change in data
  244. this.body.emitter.emit("_dataChanged");
  245. // find a stable position or start animating to a stable position
  246. this.body.emitter.emit("initPhysics");
  247. };
  248. /**
  249. * Cleans up all bindings of the network, removing it fully from the memory IF the variable is set to null after calling this function.
  250. * var network = new vis.Network(..);
  251. * network.destroy();
  252. * network = null;
  253. */
  254. Network.prototype.destroy = function() {
  255. this.body.emitter.emit("destroy");
  256. // clear events
  257. this.body.emitter.off();
  258. // remove the container and everything inside it recursively
  259. util.recursiveDOMDelete(this.body.container);
  260. };
  261. /**
  262. * Update the values of all object in the given array according to the current
  263. * value range of the objects in the array.
  264. * @param {Object} obj An object containing a set of Edges or Nodes
  265. * The objects must have a method getValue() and
  266. * setValueRange(min, max).
  267. * @private
  268. */
  269. Network.prototype._updateValueRange = function(obj) {
  270. var id;
  271. // determine the range of the objects
  272. var valueMin = undefined;
  273. var valueMax = undefined;
  274. var valueTotal = 0;
  275. for (id in obj) {
  276. if (obj.hasOwnProperty(id)) {
  277. var value = obj[id].getValue();
  278. if (value !== undefined) {
  279. valueMin = (valueMin === undefined) ? value : Math.min(value, valueMin);
  280. valueMax = (valueMax === undefined) ? value : Math.max(value, valueMax);
  281. valueTotal += value;
  282. }
  283. }
  284. }
  285. // adjust the range of all objects
  286. if (valueMin !== undefined && valueMax !== undefined) {
  287. for (id in obj) {
  288. if (obj.hasOwnProperty(id)) {
  289. obj[id].setValueRange(valueMin, valueMax, valueTotal);
  290. }
  291. }
  292. }
  293. };
  294. /**
  295. * Load the XY positions of the nodes into the dataset.
  296. */
  297. Network.prototype.storePositions = function() {
  298. // todo: incorporate fixed instead of allowedtomove, add support for clusters and hierarchical.
  299. var dataArray = [];
  300. for (var nodeId in this.body.nodes) {
  301. if (this.body.nodes.hasOwnProperty(nodeId)) {
  302. var node = this.body.nodes[nodeId];
  303. var allowedToMoveX = !this.body.nodes.xFixed;
  304. var allowedToMoveY = !this.body.nodes.yFixed;
  305. if (this.body.data.nodes._data[nodeId].x != Math.round(node.x) || this.body.data.nodes._data[nodeId].y != Math.round(node.y)) {
  306. dataArray.push({id:nodeId,x:Math.round(node.x),y:Math.round(node.y),allowedToMoveX:allowedToMoveX,allowedToMoveY:allowedToMoveY});
  307. }
  308. }
  309. }
  310. this.body.data.nodes.update(dataArray);
  311. };
  312. /**
  313. * Return the positions of the nodes.
  314. */
  315. Network.prototype.getPositions = function(ids) {
  316. var dataArray = {};
  317. if (ids !== undefined) {
  318. if (Array.isArray(ids) === true) {
  319. for (var i = 0; i < ids.length; i++) {
  320. if (this.body.nodes[ids[i]] !== undefined) {
  321. var node = this.body.nodes[ids[i]];
  322. dataArray[ids[i]] = {x: Math.round(node.x), y: Math.round(node.y)};
  323. }
  324. }
  325. }
  326. else {
  327. if (this.body.nodes[ids] !== undefined) {
  328. var node = this.body.nodes[ids];
  329. dataArray[ids] = {x: Math.round(node.x), y: Math.round(node.y)};
  330. }
  331. }
  332. }
  333. else {
  334. for (var nodeId in this.body.nodes) {
  335. if (this.body.nodes.hasOwnProperty(nodeId)) {
  336. var node = this.body.nodes[nodeId];
  337. dataArray[nodeId] = {x: Math.round(node.x), y: Math.round(node.y)};
  338. }
  339. }
  340. }
  341. return dataArray;
  342. };
  343. /**
  344. * Returns true when the Network is active.
  345. * @returns {boolean}
  346. */
  347. Network.prototype.isActive = function () {
  348. return !this.activator || this.activator.active;
  349. };
  350. /**
  351. * Check if a node is a cluster.
  352. * @param nodeId
  353. * @returns {*}
  354. */
  355. Network.prototype.isCluster = function(nodeId) {
  356. if (this.body.nodes[nodeId] !== undefined) {
  357. return this.body.nodes[nodeId].isCluster;
  358. }
  359. else {
  360. console.log("Node does not exist.")
  361. return false;
  362. }
  363. };
  364. Network.prototype.getBoundingBox = function(nodeId) {
  365. if (this.body.nodes[nodeId] !== undefined) {
  366. return this.body.nodes[nodeId].boundingBox;
  367. }
  368. }
  369. Network.prototype.getConnectedNodes = function(nodeId) {
  370. var nodeList = [];
  371. if (this.body.nodes[nodeId] !== undefined) {
  372. var node = this.body.nodes[nodeId];
  373. var nodeObj = {nodeId : true}; // used to quickly check if node already exists
  374. for (var i = 0; i < node.edges.length; i++) {
  375. var edge = node.edges[i];
  376. if (edge.toId === nodeId) {
  377. if (nodeObj[edge.fromId] === undefined) {
  378. nodeList.push(edge.fromId);
  379. nodeObj[edge.fromId] = true;
  380. }
  381. }
  382. else if (edge.fromId === nodeId) {
  383. if (nodeObj[edge.toId] === undefined) {
  384. nodeList.push(edge.toId)
  385. nodeObj[edge.toId] = true;
  386. }
  387. }
  388. }
  389. }
  390. return nodeList;
  391. }
  392. Network.prototype.getEdgesFromNode = function(nodeId) {
  393. var edgesList = [];
  394. if (this.body.nodes[nodeId] !== undefined) {
  395. var node = this.body.nodes[nodeId];
  396. for (var i = 0; i < node.edges.length; i++) {
  397. edgesList.push(node.edges[i].id);
  398. }
  399. }
  400. return edgesList;
  401. }
  402. Network.prototype.generateColorObject = function(color) {
  403. return util.parseColor(color);
  404. }
  405. module.exports = Network;