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.

2740 lines
82 KiB

10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
  1. var Emitter = require('emitter-component');
  2. var Hammer = require('../module/hammer');
  3. var keycharm = require('keycharm');
  4. var util = require('../util');
  5. var hammerUtil = require('../hammerUtil');
  6. var DataSet = require('../DataSet');
  7. var DataView = require('../DataView');
  8. var dotparser = require('./dotparser');
  9. var gephiParser = require('./gephiParser');
  10. var Groups = require('./Groups');
  11. var Images = require('./Images');
  12. var Node = require('./Node');
  13. var Edge = require('./Edge');
  14. var Popup = require('./Popup');
  15. var MixinLoader = require('./mixins/MixinLoader');
  16. var Activator = require('../shared/Activator');
  17. var locales = require('./locales');
  18. // Load custom shapes into CanvasRenderingContext2D
  19. require('./shapes');
  20. /**
  21. * @constructor Network
  22. * Create a network visualization, displaying nodes and edges.
  23. *
  24. * @param {Element} container The DOM element in which the Network will
  25. * be created. Normally a div element.
  26. * @param {Object} data An object containing parameters
  27. * {Array} nodes
  28. * {Array} edges
  29. * @param {Object} options Options
  30. */
  31. function Network (container, data, options) {
  32. if (!(this instanceof Network)) {
  33. throw new SyntaxError('Constructor must be called with the new operator');
  34. }
  35. this._determineBrowserMethod();
  36. this._initializeMixinLoaders();
  37. // create variables and set default values
  38. this.containerElement = container;
  39. // render and calculation settings
  40. this.renderRefreshRate = 60; // hz (fps)
  41. this.renderTimestep = 1000 / this.renderRefreshRate; // ms -- saves calculation later on
  42. this.renderTime = 0; // measured time it takes to render a frame
  43. this.physicsTime = 0; // measured time it takes to render a frame
  44. this.runDoubleSpeed = false;
  45. this.physicsDiscreteStepsize = 0.50; // discrete stepsize of the simulation
  46. this.initializing = true;
  47. this.triggerFunctions = {add:null,edit:null,editEdge:null,connect:null,del:null};
  48. // set constant values
  49. this.defaultOptions = {
  50. nodes: {
  51. mass: 1,
  52. radiusMin: 10,
  53. radiusMax: 30,
  54. radius: 10,
  55. shape: 'ellipse',
  56. image: undefined,
  57. widthMin: 16, // px
  58. widthMax: 64, // px
  59. fontColor: 'black',
  60. fontSize: 14, // px
  61. fontFace: 'verdana',
  62. fontFill: undefined,
  63. fontStrokeWidth: 0, // px
  64. fontStrokeColor: 'white',
  65. level: -1,
  66. color: {
  67. border: '#2B7CE9',
  68. background: '#97C2FC',
  69. highlight: {
  70. border: '#2B7CE9',
  71. background: '#D2E5FF'
  72. },
  73. hover: {
  74. border: '#2B7CE9',
  75. background: '#D2E5FF'
  76. }
  77. },
  78. group: undefined,
  79. borderWidth: 1,
  80. borderWidthSelected: undefined
  81. },
  82. edges: {
  83. widthMin: 1, //
  84. widthMax: 15,//
  85. width: 1,
  86. widthSelectionMultiplier: 2,
  87. hoverWidth: 1.5,
  88. style: 'line',
  89. color: {
  90. color:'#848484',
  91. highlight:'#848484',
  92. hover: '#848484'
  93. },
  94. fontColor: '#343434',
  95. fontSize: 14, // px
  96. fontFace: 'arial',
  97. fontFill: 'white',
  98. fontStrokeWidth: 0, // px
  99. fontStrokeColor: 'white',
  100. labelAlignment:'horizontal',
  101. arrowScaleFactor: 1,
  102. dash: {
  103. length: 10,
  104. gap: 5,
  105. altLength: undefined
  106. },
  107. inheritColor: "from" // to, from, false, true (== from)
  108. },
  109. configurePhysics:false,
  110. physics: {
  111. barnesHut: {
  112. enabled: true,
  113. thetaInverted: 1 / 0.5, // inverted to save time during calculation
  114. gravitationalConstant: -2000,
  115. centralGravity: 0.3,
  116. springLength: 95,
  117. springConstant: 0.04,
  118. damping: 0.09
  119. },
  120. repulsion: {
  121. centralGravity: 0.0,
  122. springLength: 200,
  123. springConstant: 0.05,
  124. nodeDistance: 100,
  125. damping: 0.09
  126. },
  127. hierarchicalRepulsion: {
  128. enabled: false,
  129. centralGravity: 0.0,
  130. springLength: 100,
  131. springConstant: 0.01,
  132. nodeDistance: 150,
  133. damping: 0.09
  134. },
  135. damping: null,
  136. centralGravity: null,
  137. springLength: null,
  138. springConstant: null
  139. },
  140. clustering: { // Per Node in Cluster = PNiC
  141. enabled: false, // (Boolean) | global on/off switch for clustering.
  142. initialMaxNodes: 100, // (# nodes) | if the initial amount of nodes is larger than this, we cluster until the total number is less than this threshold.
  143. clusterThreshold:500, // (# nodes) | during calculate forces, we check if the total number of nodes is larger than this. If it is, cluster until reduced to reduceToNodes
  144. reduceToNodes:300, // (# nodes) | during calculate forces, we check if the total number of nodes is larger than clusterThreshold. If it is, cluster until reduced to this
  145. chainThreshold: 0.4, // (% of all drawn nodes)| maximum percentage of allowed chainnodes (long strings of connected nodes) within all nodes. (lower means less chains).
  146. clusterEdgeThreshold: 20, // (px) | edge length threshold. if smaller, this node is clustered.
  147. sectorThreshold: 100, // (# nodes in cluster) | cluster size threshold. If larger, expanding in own sector.
  148. screenSizeThreshold: 0.2, // (% of canvas) | relative size threshold. If the width or height of a clusternode takes up this much of the screen, decluster node.
  149. fontSizeMultiplier: 4.0, // (px PNiC) | how much the cluster font size grows per node in cluster (in px).
  150. maxFontSize: 1000,
  151. forceAmplification: 0.1, // (multiplier PNiC) | factor of increase fo the repulsion force of a cluster (per node in cluster).
  152. distanceAmplification: 0.1, // (multiplier PNiC) | factor how much the repulsion distance of a cluster increases (per node in cluster).
  153. edgeGrowth: 20, // (px PNiC) | amount of clusterSize connected to the edge is multiplied with this and added to edgeLength.
  154. nodeScaling: {width: 1, // (px PNiC) | growth of the width per node in cluster.
  155. height: 1, // (px PNiC) | growth of the height per node in cluster.
  156. radius: 1}, // (px PNiC) | growth of the radius per node in cluster.
  157. maxNodeSizeIncrements: 600, // (# increments) | max growth of the width per node in cluster.
  158. activeAreaBoxSize: 80, // (px) | box area around the curser where clusters are popped open.
  159. clusterLevelDifference: 2
  160. },
  161. navigation: {
  162. enabled: false
  163. },
  164. keyboard: {
  165. enabled: false,
  166. speed: {x: 10, y: 10, zoom: 0.02},
  167. bindToWindow: true
  168. },
  169. dataManipulation: {
  170. enabled: false,
  171. initiallyVisible: false
  172. },
  173. hierarchicalLayout: {
  174. enabled:false,
  175. levelSeparation: 150,
  176. nodeSpacing: 100,
  177. direction: "UD", // UD, DU, LR, RL
  178. layout: "hubsize" // hubsize, directed
  179. },
  180. freezeForStabilization: false,
  181. smoothCurves: {
  182. enabled: true,
  183. dynamic: true,
  184. type: "continuous",
  185. roundness: 0.5
  186. },
  187. maxVelocity: 30,
  188. minVelocity: 0.1, // px/s
  189. stabilize: true, // stabilize before displaying the network
  190. stabilizationIterations: 1000, // maximum number of iteration to stabilize
  191. zoomExtentOnStabilize: true,
  192. locale: 'en',
  193. locales: locales,
  194. tooltip: {
  195. delay: 300,
  196. fontColor: 'black',
  197. fontSize: 14, // px
  198. fontFace: 'verdana',
  199. color: {
  200. border: '#666',
  201. background: '#FFFFC6'
  202. }
  203. },
  204. dragNetwork: true,
  205. dragNodes: true,
  206. zoomable: true,
  207. hover: false,
  208. hideEdgesOnDrag: false,
  209. hideNodesOnDrag: false,
  210. width : '100%',
  211. height : '100%',
  212. selectable: true
  213. };
  214. this.constants = util.extend({}, this.defaultOptions);
  215. this.pixelRatio = 1;
  216. this.hoverObj = {nodes:{},edges:{}};
  217. this.controlNodesActive = false;
  218. this.navigationHammers = {existing:[], _new: []};
  219. // animation properties
  220. this.animationSpeed = 1/this.renderRefreshRate;
  221. this.animationEasingFunction = "easeInOutQuint";
  222. this.animating = false;
  223. this.easingTime = 0;
  224. this.sourceScale = 0;
  225. this.targetScale = 0;
  226. this.sourceTranslation = 0;
  227. this.targetTranslation = 0;
  228. this.lockedOnNodeId = null;
  229. this.lockedOnNodeOffset = null;
  230. this.touchTime = 0;
  231. // Node variables
  232. var network = this;
  233. this.groups = new Groups(); // object with groups
  234. this.images = new Images(); // object with images
  235. this.images.setOnloadCallback(function (status) {
  236. network._redraw();
  237. });
  238. // keyboard navigation variables
  239. this.xIncrement = 0;
  240. this.yIncrement = 0;
  241. this.zoomIncrement = 0;
  242. // loading all the mixins:
  243. // load the force calculation functions, grouped under the physics system.
  244. this._loadPhysicsSystem();
  245. // create a frame and canvas
  246. this._create();
  247. // load the sector system. (mandatory, fully integrated with Network)
  248. this._loadSectorSystem();
  249. // load the cluster system. (mandatory, even when not using the cluster system, there are function calls to it)
  250. this._loadClusterSystem();
  251. // load the selection system. (mandatory, required by Network)
  252. this._loadSelectionSystem();
  253. // load the selection system. (mandatory, required by Network)
  254. this._loadHierarchySystem();
  255. // apply options
  256. this._setTranslation(this.frame.clientWidth / 2, this.frame.clientHeight / 2);
  257. this._setScale(1);
  258. this.setOptions(options);
  259. // other vars
  260. this.freezeSimulation = false;// freeze the simulation
  261. this.cachedFunctions = {};
  262. this.startedStabilization = false;
  263. this.stabilized = false;
  264. this.stabilizationIterations = null;
  265. this.draggingNodes = false;
  266. // containers for nodes and edges
  267. this.calculationNodes = {};
  268. this.calculationNodeIndices = [];
  269. this.nodeIndices = []; // array with all the indices of the nodes. Used to speed up forces calculation
  270. this.nodes = {}; // object with Node objects
  271. this.edges = {}; // object with Edge objects
  272. // position and scale variables and objects
  273. this.canvasTopLeft = {"x": 0,"y": 0}; // coordinates of the top left of the canvas. they will be set during _redraw.
  274. this.canvasBottomRight = {"x": 0,"y": 0}; // coordinates of the bottom right of the canvas. they will be set during _redraw
  275. this.pointerPosition = {"x": 0,"y": 0}; // coordinates of the bottom right of the canvas. they will be set during _redraw
  276. this.areaCenter = {}; // object with x and y elements used for determining the center of the zoom action
  277. this.scale = 1; // defining the global scale variable in the constructor
  278. this.previousScale = this.scale; // this is used to check if the zoom operation is zooming in or out
  279. // datasets or dataviews
  280. this.nodesData = null; // A DataSet or DataView
  281. this.edgesData = null; // A DataSet or DataView
  282. // create event listeners used to subscribe on the DataSets of the nodes and edges
  283. this.nodesListeners = {
  284. 'add': function (event, params) {
  285. network._addNodes(params.items);
  286. network.start();
  287. },
  288. 'update': function (event, params) {
  289. network._updateNodes(params.items, params.data);
  290. network.start();
  291. },
  292. 'remove': function (event, params) {
  293. network._removeNodes(params.items);
  294. network.start();
  295. }
  296. };
  297. this.edgesListeners = {
  298. 'add': function (event, params) {
  299. network._addEdges(params.items);
  300. network.start();
  301. },
  302. 'update': function (event, params) {
  303. network._updateEdges(params.items);
  304. network.start();
  305. },
  306. 'remove': function (event, params) {
  307. network._removeEdges(params.items);
  308. network.start();
  309. }
  310. };
  311. // properties for the animation
  312. this.moving = true;
  313. this.timer = undefined; // Scheduling function. Is definded in this.start();
  314. // load data (the disable start variable will be the same as the enabled clustering)
  315. this.setData(data,this.constants.clustering.enabled || this.constants.hierarchicalLayout.enabled);
  316. // hierarchical layout
  317. this.initializing = false;
  318. if (this.constants.hierarchicalLayout.enabled == true) {
  319. this._setupHierarchicalLayout();
  320. }
  321. else {
  322. // zoom so all data will fit on the screen, if clustering is enabled, we do not want start to be called here.
  323. if (this.constants.stabilize == false) {
  324. this.zoomExtent(undefined, true,this.constants.clustering.enabled);
  325. }
  326. }
  327. // if clustering is disabled, the simulation will have started in the setData function
  328. if (this.constants.clustering.enabled) {
  329. this.startWithClustering();
  330. }
  331. }
  332. // Extend Network with an Emitter mixin
  333. Emitter(Network.prototype);
  334. /**
  335. * Determine if the browser requires a setTimeout or a requestAnimationFrame. This was required because
  336. * some implementations (safari and IE9) did not support requestAnimationFrame
  337. * @private
  338. */
  339. Network.prototype._determineBrowserMethod = function() {
  340. var browserType = navigator.userAgent.toLowerCase();
  341. this.requiresTimeout = false;
  342. if (browserType.indexOf('msie 9.0') != -1) { // IE 9
  343. this.requiresTimeout = true;
  344. }
  345. else if (browserType.indexOf('safari') != -1) { // safari
  346. if (browserType.indexOf('chrome') <= -1) {
  347. this.requiresTimeout = true;
  348. }
  349. }
  350. }
  351. /**
  352. * Get the script path where the vis.js library is located
  353. *
  354. * @returns {string | null} path Path or null when not found. Path does not
  355. * end with a slash.
  356. * @private
  357. */
  358. Network.prototype._getScriptPath = function() {
  359. var scripts = document.getElementsByTagName( 'script' );
  360. // find script named vis.js or vis.min.js
  361. for (var i = 0; i < scripts.length; i++) {
  362. var src = scripts[i].src;
  363. var match = src && /\/?vis(.min)?\.js$/.exec(src);
  364. if (match) {
  365. // return path without the script name
  366. return src.substring(0, src.length - match[0].length);
  367. }
  368. }
  369. return null;
  370. };
  371. /**
  372. * Find the center position of the network
  373. * @private
  374. */
  375. Network.prototype._getRange = function() {
  376. var minY = 1e9, maxY = -1e9, minX = 1e9, maxX = -1e9, node;
  377. for (var nodeId in this.nodes) {
  378. if (this.nodes.hasOwnProperty(nodeId)) {
  379. node = this.nodes[nodeId];
  380. if (minX > (node.boundingBox.left)) {minX = node.boundingBox.left;}
  381. if (maxX < (node.boundingBox.right)) {maxX = node.boundingBox.right;}
  382. if (minY > (node.boundingBox.bottom)) {minY = node.boundingBox.top;} // top is negative, bottom is positive
  383. if (maxY < (node.boundingBox.top)) {maxY = node.boundingBox.bottom;} // top is negative, bottom is positive
  384. }
  385. }
  386. if (minX == 1e9 && maxX == -1e9 && minY == 1e9 && maxY == -1e9) {
  387. minY = 0, maxY = 0, minX = 0, maxX = 0;
  388. }
  389. return {minX: minX, maxX: maxX, minY: minY, maxY: maxY};
  390. };
  391. /**
  392. * @param {object} range = {minX: minX, maxX: maxX, minY: minY, maxY: maxY};
  393. * @returns {{x: number, y: number}}
  394. * @private
  395. */
  396. Network.prototype._findCenter = function(range) {
  397. return {x: (0.5 * (range.maxX + range.minX)),
  398. y: (0.5 * (range.maxY + range.minY))};
  399. };
  400. /**
  401. * This function zooms out to fit all data on screen based on amount of nodes
  402. *
  403. * @param {Boolean} [initialZoom] | zoom based on fitted formula or range, true = fitted, default = false;
  404. * @param {Boolean} [disableStart] | If true, start is not called.
  405. */
  406. Network.prototype.zoomExtent = function(animationOptions, initialZoom, disableStart) {
  407. this._redraw(true);
  408. if (initialZoom === undefined) {initialZoom = false;}
  409. if (disableStart === undefined) {disableStart = false;}
  410. if (animationOptions === undefined) {animationOptions = false;}
  411. var range = this._getRange();
  412. var zoomLevel;
  413. if (initialZoom == true) {
  414. var numberOfNodes = this.nodeIndices.length;
  415. if (this.constants.smoothCurves == true) {
  416. if (this.constants.clustering.enabled == true &&
  417. numberOfNodes >= this.constants.clustering.initialMaxNodes) {
  418. zoomLevel = 49.07548 / (numberOfNodes + 142.05338) + 9.1444e-04; // this is obtained from fitting a dataset from 5 points with scale levels that looked good.
  419. }
  420. else {
  421. zoomLevel = 12.662 / (numberOfNodes + 7.4147) + 0.0964822; // this is obtained from fitting a dataset from 5 points with scale levels that looked good.
  422. }
  423. }
  424. else {
  425. if (this.constants.clustering.enabled == true &&
  426. numberOfNodes >= this.constants.clustering.initialMaxNodes) {
  427. zoomLevel = 77.5271985 / (numberOfNodes + 187.266146) + 4.76710517e-05; // this is obtained from fitting a dataset from 5 points with scale levels that looked good.
  428. }
  429. else {
  430. zoomLevel = 30.5062972 / (numberOfNodes + 19.93597763) + 0.08413486; // this is obtained from fitting a dataset from 5 points with scale levels that looked good.
  431. }
  432. }
  433. // correct for larger canvasses.
  434. var factor = Math.min(this.frame.canvas.clientWidth / 600, this.frame.canvas.clientHeight / 600);
  435. zoomLevel *= factor;
  436. }
  437. else {
  438. var xDistance = Math.abs(range.maxX - range.minX) * 1.1;
  439. var yDistance = Math.abs(range.maxY - range.minY) * 1.1;
  440. var xZoomLevel = this.frame.canvas.clientWidth / xDistance;
  441. var yZoomLevel = this.frame.canvas.clientHeight / yDistance;
  442. zoomLevel = (xZoomLevel <= yZoomLevel) ? xZoomLevel : yZoomLevel;
  443. }
  444. if (zoomLevel > 1.0) {
  445. zoomLevel = 1.0;
  446. }
  447. var center = this._findCenter(range);
  448. if (disableStart == false) {
  449. var options = {position: center, scale: zoomLevel, animation: animationOptions};
  450. this.moveTo(options);
  451. this.moving = true;
  452. this.start();
  453. }
  454. else {
  455. center.x *= zoomLevel;
  456. center.y *= zoomLevel;
  457. center.x -= 0.5 * this.frame.canvas.clientWidth;
  458. center.y -= 0.5 * this.frame.canvas.clientHeight;
  459. this._setScale(zoomLevel);
  460. this._setTranslation(-center.x,-center.y);
  461. }
  462. };
  463. /**
  464. * Update the this.nodeIndices with the most recent node index list
  465. * @private
  466. */
  467. Network.prototype._updateNodeIndexList = function() {
  468. this._clearNodeIndexList();
  469. for (var idx in this.nodes) {
  470. if (this.nodes.hasOwnProperty(idx)) {
  471. this.nodeIndices.push(idx);
  472. }
  473. }
  474. };
  475. /**
  476. * Set nodes and edges, and optionally options as well.
  477. *
  478. * @param {Object} data Object containing parameters:
  479. * {Array | DataSet | DataView} [nodes] Array with nodes
  480. * {Array | DataSet | DataView} [edges] Array with edges
  481. * {String} [dot] String containing data in DOT format
  482. * {String} [gephi] String containing data in gephi JSON format
  483. * {Options} [options] Object with options
  484. * @param {Boolean} [disableStart] | optional: disable the calling of the start function.
  485. */
  486. Network.prototype.setData = function(data, disableStart) {
  487. if (disableStart === undefined) {
  488. disableStart = false;
  489. }
  490. // we set initializing to true to ensure that the hierarchical layout is not performed until both nodes and edges are added.
  491. this.initializing = true;
  492. if (data && data.dot && (data.nodes || data.edges)) {
  493. throw new SyntaxError('Data must contain either parameter "dot" or ' +
  494. ' parameter pair "nodes" and "edges", but not both.');
  495. }
  496. // clean up in case there is anyone in an active mode of the manipulation. This is the same option as bound to the escape button.
  497. if (this.constants.dataManipulation.enabled == true) {
  498. this._createManipulatorBar();
  499. }
  500. // set options
  501. this.setOptions(data && data.options);
  502. // set all data
  503. if (data && data.dot) {
  504. // parse DOT file
  505. if(data && data.dot) {
  506. var dotData = dotparser.DOTToGraph(data.dot);
  507. this.setData(dotData);
  508. return;
  509. }
  510. }
  511. else if (data && data.gephi) {
  512. // parse DOT file
  513. if(data && data.gephi) {
  514. var gephiData = gephiParser.parseGephi(data.gephi);
  515. this.setData(gephiData);
  516. return;
  517. }
  518. }
  519. else {
  520. this._setNodes(data && data.nodes);
  521. this._setEdges(data && data.edges);
  522. }
  523. this._putDataInSector();
  524. if (disableStart == false) {
  525. if (this.constants.hierarchicalLayout.enabled == true) {
  526. this._resetLevels();
  527. this._setupHierarchicalLayout();
  528. }
  529. else {
  530. // find a stable position or start animating to a stable position
  531. if (this.constants.stabilize) {
  532. this._stabilize();
  533. }
  534. }
  535. this.start();
  536. }
  537. this.initializing = false;
  538. };
  539. /**
  540. * Set options
  541. * @param {Object} options
  542. */
  543. Network.prototype.setOptions = function (options) {
  544. if (options) {
  545. var prop;
  546. var fields = ['nodes','edges','smoothCurves','hierarchicalLayout','clustering','navigation',
  547. 'keyboard','dataManipulation','onAdd','onEdit','onEditEdge','onConnect','onDelete','clickToUse'
  548. ];
  549. // extend all but the values in fields
  550. util.selectiveNotDeepExtend(fields,this.constants, options);
  551. util.selectiveNotDeepExtend(['color'],this.constants.nodes, options.nodes);
  552. util.selectiveNotDeepExtend(['color','length'],this.constants.edges, options.edges);
  553. if (options.physics) {
  554. util.mergeOptions(this.constants.physics, options.physics,'barnesHut');
  555. util.mergeOptions(this.constants.physics, options.physics,'repulsion');
  556. if (options.physics.hierarchicalRepulsion) {
  557. this.constants.hierarchicalLayout.enabled = true;
  558. this.constants.physics.hierarchicalRepulsion.enabled = true;
  559. this.constants.physics.barnesHut.enabled = false;
  560. for (prop in options.physics.hierarchicalRepulsion) {
  561. if (options.physics.hierarchicalRepulsion.hasOwnProperty(prop)) {
  562. this.constants.physics.hierarchicalRepulsion[prop] = options.physics.hierarchicalRepulsion[prop];
  563. }
  564. }
  565. }
  566. }
  567. if (options.onAdd) {this.triggerFunctions.add = options.onAdd;}
  568. if (options.onEdit) {this.triggerFunctions.edit = options.onEdit;}
  569. if (options.onEditEdge) {this.triggerFunctions.editEdge = options.onEditEdge;}
  570. if (options.onConnect) {this.triggerFunctions.connect = options.onConnect;}
  571. if (options.onDelete) {this.triggerFunctions.del = options.onDelete;}
  572. util.mergeOptions(this.constants, options,'smoothCurves');
  573. util.mergeOptions(this.constants, options,'hierarchicalLayout');
  574. util.mergeOptions(this.constants, options,'clustering');
  575. util.mergeOptions(this.constants, options,'navigation');
  576. util.mergeOptions(this.constants, options,'keyboard');
  577. util.mergeOptions(this.constants, options,'dataManipulation');
  578. if (options.dataManipulation) {
  579. this.editMode = this.constants.dataManipulation.initiallyVisible;
  580. }
  581. // TODO: work out these options and document them
  582. if (options.edges) {
  583. if (options.edges.color !== undefined) {
  584. if (util.isString(options.edges.color)) {
  585. this.constants.edges.color = {};
  586. this.constants.edges.color.color = options.edges.color;
  587. this.constants.edges.color.highlight = options.edges.color;
  588. this.constants.edges.color.hover = options.edges.color;
  589. }
  590. else {
  591. if (options.edges.color.color !== undefined) {this.constants.edges.color.color = options.edges.color.color;}
  592. if (options.edges.color.highlight !== undefined) {this.constants.edges.color.highlight = options.edges.color.highlight;}
  593. if (options.edges.color.hover !== undefined) {this.constants.edges.color.hover = options.edges.color.hover;}
  594. }
  595. this.constants.edges.inheritColor = false;
  596. }
  597. if (!options.edges.fontColor) {
  598. if (options.edges.color !== undefined) {
  599. if (util.isString(options.edges.color)) {this.constants.edges.fontColor = options.edges.color;}
  600. else if (options.edges.color.color !== undefined) {this.constants.edges.fontColor = options.edges.color.color;}
  601. }
  602. }
  603. }
  604. if (options.nodes) {
  605. if (options.nodes.color) {
  606. var newColorObj = util.parseColor(options.nodes.color);
  607. this.constants.nodes.color.background = newColorObj.background;
  608. this.constants.nodes.color.border = newColorObj.border;
  609. this.constants.nodes.color.highlight.background = newColorObj.highlight.background;
  610. this.constants.nodes.color.highlight.border = newColorObj.highlight.border;
  611. this.constants.nodes.color.hover.background = newColorObj.hover.background;
  612. this.constants.nodes.color.hover.border = newColorObj.hover.border;
  613. }
  614. }
  615. if (options.groups) {
  616. for (var groupname in options.groups) {
  617. if (options.groups.hasOwnProperty(groupname)) {
  618. var group = options.groups[groupname];
  619. this.groups.add(groupname, group);
  620. }
  621. }
  622. }
  623. if (options.tooltip) {
  624. for (prop in options.tooltip) {
  625. if (options.tooltip.hasOwnProperty(prop)) {
  626. this.constants.tooltip[prop] = options.tooltip[prop];
  627. }
  628. }
  629. if (options.tooltip.color) {
  630. this.constants.tooltip.color = util.parseColor(options.tooltip.color);
  631. }
  632. }
  633. if ('clickToUse' in options) {
  634. if (options.clickToUse) {
  635. if (!this.activator) {
  636. this.activator = new Activator(this.frame);
  637. this.activator.on('change', this._createKeyBinds.bind(this));
  638. }
  639. }
  640. else {
  641. if (this.activator) {
  642. this.activator.destroy();
  643. delete this.activator;
  644. }
  645. }
  646. }
  647. if (options.labels) {
  648. throw new Error('Option "labels" is deprecated. Use options "locale" and "locales" instead.');
  649. }
  650. // (Re)loading the mixins that can be enabled or disabled in the options.
  651. // load the force calculation functions, grouped under the physics system.
  652. this._loadPhysicsSystem();
  653. // load the navigation system.
  654. this._loadNavigationControls();
  655. // load the data manipulation system
  656. this._loadManipulationSystem();
  657. // configure the smooth curves
  658. this._configureSmoothCurves();
  659. // bind hammer
  660. this._bindHammer();
  661. // bind keys. If disabled, this will not do anything;
  662. this._createKeyBinds();
  663. this.setSize(this.constants.width, this.constants.height);
  664. this.moving = true;
  665. this.start();
  666. }
  667. };
  668. /**
  669. * Create the main frame for the Network.
  670. * This function is executed once when a Network object is created. The frame
  671. * contains a canvas, and this canvas contains all objects like the axis and
  672. * nodes.
  673. * @private
  674. */
  675. Network.prototype._create = function () {
  676. // remove all elements from the container element.
  677. while (this.containerElement.hasChildNodes()) {
  678. this.containerElement.removeChild(this.containerElement.firstChild);
  679. }
  680. this.frame = document.createElement('div');
  681. this.frame.className = 'vis network-frame';
  682. this.frame.style.position = 'relative';
  683. this.frame.style.overflow = 'hidden';
  684. this.frame.tabIndex = 900;
  685. //////////////////////////////////////////////////////////////////
  686. this.frame.canvas = document.createElement("canvas");
  687. this.frame.canvas.style.position = 'relative';
  688. this.frame.appendChild(this.frame.canvas);
  689. if (!this.frame.canvas.getContext) {
  690. var noCanvas = document.createElement( 'DIV' );
  691. noCanvas.style.color = 'red';
  692. noCanvas.style.fontWeight = 'bold' ;
  693. noCanvas.style.padding = '10px';
  694. noCanvas.innerHTML = 'Error: your browser does not support HTML canvas';
  695. this.frame.canvas.appendChild(noCanvas);
  696. }
  697. else {
  698. var ctx = this.frame.canvas.getContext("2d");
  699. this.pixelRatio = (window.devicePixelRatio || 1) / (ctx.webkitBackingStorePixelRatio ||
  700. ctx.mozBackingStorePixelRatio ||
  701. ctx.msBackingStorePixelRatio ||
  702. ctx.oBackingStorePixelRatio ||
  703. ctx.backingStorePixelRatio || 1);
  704. this.frame.canvas.getContext("2d").setTransform(this.pixelRatio, 0, 0, this.pixelRatio, 0, 0);
  705. }
  706. this._bindHammer();
  707. };
  708. /**
  709. * This function binds hammer, it can be repeated over and over due to the uniqueness check.
  710. * @private
  711. */
  712. Network.prototype._bindHammer = function() {
  713. var me = this;
  714. if (this.hammer !== undefined) {
  715. this.hammer.dispose();
  716. }
  717. this.drag = {};
  718. this.pinch = {};
  719. this.hammer = Hammer(this.frame.canvas, {
  720. prevent_default: true
  721. });
  722. this.hammer.on('tap', me._onTap.bind(me) );
  723. this.hammer.on('doubletap', me._onDoubleTap.bind(me) );
  724. this.hammer.on('hold', me._onHold.bind(me) );
  725. this.hammer.on('touch', me._onTouch.bind(me) );
  726. this.hammer.on('dragstart', me._onDragStart.bind(me) );
  727. this.hammer.on('drag', me._onDrag.bind(me) );
  728. this.hammer.on('dragend', me._onDragEnd.bind(me) );
  729. if (this.constants.zoomable == true) {
  730. this.hammer.on('mousewheel', me._onMouseWheel.bind(me));
  731. this.hammer.on('DOMMouseScroll', me._onMouseWheel.bind(me)); // for FF
  732. this.hammer.on('pinch', me._onPinch.bind(me) );
  733. }
  734. this.hammer.on('mousemove', me._onMouseMoveTitle.bind(me) );
  735. this.hammerFrame = Hammer(this.frame, {
  736. prevent_default: true
  737. });
  738. this.hammerFrame.on('release', me._onRelease.bind(me) );
  739. // add the frame to the container element
  740. this.containerElement.appendChild(this.frame);
  741. }
  742. /**
  743. * Binding the keys for keyboard navigation. These functions are defined in the NavigationMixin
  744. * @private
  745. */
  746. Network.prototype._createKeyBinds = function() {
  747. var me = this;
  748. if (this.keycharm !== undefined) {
  749. this.keycharm.destroy();
  750. }
  751. if (this.constants.keyboard.bindToWindow == true) {
  752. this.keycharm = keycharm({container: window, preventDefault: false});
  753. }
  754. else {
  755. this.keycharm = keycharm({container: this.frame, preventDefault: false});
  756. }
  757. this.keycharm.reset();
  758. if (this.constants.keyboard.enabled && this.isActive()) {
  759. this.keycharm.bind("up", this._moveUp.bind(me) , "keydown");
  760. this.keycharm.bind("up", this._yStopMoving.bind(me), "keyup");
  761. this.keycharm.bind("down", this._moveDown.bind(me) , "keydown");
  762. this.keycharm.bind("down", this._yStopMoving.bind(me), "keyup");
  763. this.keycharm.bind("left", this._moveLeft.bind(me) , "keydown");
  764. this.keycharm.bind("left", this._xStopMoving.bind(me), "keyup");
  765. this.keycharm.bind("right",this._moveRight.bind(me), "keydown");
  766. this.keycharm.bind("right",this._xStopMoving.bind(me), "keyup");
  767. this.keycharm.bind("=", this._zoomIn.bind(me), "keydown");
  768. this.keycharm.bind("=", this._stopZoom.bind(me), "keyup");
  769. this.keycharm.bind("num+", this._zoomIn.bind(me), "keydown");
  770. this.keycharm.bind("num+", this._stopZoom.bind(me), "keyup");
  771. this.keycharm.bind("num-", this._zoomOut.bind(me), "keydown");
  772. this.keycharm.bind("num-", this._stopZoom.bind(me), "keyup");
  773. this.keycharm.bind("-", this._zoomOut.bind(me), "keydown");
  774. this.keycharm.bind("-", this._stopZoom.bind(me), "keyup");
  775. this.keycharm.bind("[", this._zoomIn.bind(me), "keydown");
  776. this.keycharm.bind("[", this._stopZoom.bind(me), "keyup");
  777. this.keycharm.bind("]", this._zoomOut.bind(me), "keydown");
  778. this.keycharm.bind("]", this._stopZoom.bind(me), "keyup");
  779. this.keycharm.bind("pageup",this._zoomIn.bind(me), "keydown");
  780. this.keycharm.bind("pageup",this._stopZoom.bind(me), "keyup");
  781. this.keycharm.bind("pagedown",this._zoomOut.bind(me),"keydown");
  782. this.keycharm.bind("pagedown",this._stopZoom.bind(me), "keyup");
  783. }
  784. if (this.constants.dataManipulation.enabled == true) {
  785. this.keycharm.bind("esc",this._createManipulatorBar.bind(me));
  786. this.keycharm.bind("delete",this._deleteSelected.bind(me));
  787. }
  788. };
  789. /**
  790. * Cleans up all bindings of the network, removing it fully from the memory IF the variable is set to null after calling this function.
  791. * var network = new vis.Network(..);
  792. * network.destroy();
  793. * network = null;
  794. */
  795. Network.prototype.destroy = function() {
  796. this.start = function () {};
  797. this.redraw = function () {};
  798. this.timer = false;
  799. // cleanup physicsConfiguration if it exists
  800. this._cleanupPhysicsConfiguration();
  801. // remove keybindings
  802. this.keycharm.reset();
  803. // clear hammer bindings
  804. this.hammer.dispose();
  805. // clear events
  806. this.off();
  807. this._recursiveDOMDelete(this.containerElement);
  808. }
  809. Network.prototype._recursiveDOMDelete = function(DOMobject) {
  810. while (DOMobject.hasChildNodes() == true) {
  811. this._recursiveDOMDelete(DOMobject.firstChild);
  812. DOMobject.removeChild(DOMobject.firstChild);
  813. }
  814. }
  815. /**
  816. * Get the pointer location from a touch location
  817. * @param {{pageX: Number, pageY: Number}} touch
  818. * @return {{x: Number, y: Number}} pointer
  819. * @private
  820. */
  821. Network.prototype._getPointer = function (touch) {
  822. return {
  823. x: touch.pageX - util.getAbsoluteLeft(this.frame.canvas),
  824. y: touch.pageY - util.getAbsoluteTop(this.frame.canvas)
  825. };
  826. };
  827. /**
  828. * On start of a touch gesture, store the pointer
  829. * @param event
  830. * @private
  831. */
  832. Network.prototype._onTouch = function (event) {
  833. if (new Date().valueOf() - this.touchTime > 100) {
  834. this.drag.pointer = this._getPointer(event.gesture.center);
  835. this.drag.pinched = false;
  836. this.pinch.scale = this._getScale();
  837. // to avoid double fireing of this event because we have two hammer instances. (on canvas and on frame)
  838. this.touchTime = new Date().valueOf();
  839. this._handleTouch(this.drag.pointer);
  840. }
  841. };
  842. /**
  843. * handle drag start event
  844. * @private
  845. */
  846. Network.prototype._onDragStart = function (event) {
  847. this._handleDragStart(event);
  848. };
  849. /**
  850. * This function is called by _onDragStart.
  851. * It is separated out because we can then overload it for the datamanipulation system.
  852. *
  853. * @private
  854. */
  855. Network.prototype._handleDragStart = function(event) {
  856. // in case the touch event was triggered on an external div, do the initial touch now.
  857. if (this.drag.pointer === undefined) {
  858. this._onTouch(event);
  859. }
  860. var node = this._getNodeAt(this.drag.pointer);
  861. // note: drag.pointer is set in _onTouch to get the initial touch location
  862. this.drag.dragging = true;
  863. this.drag.selection = [];
  864. this.drag.translation = this._getTranslation();
  865. this.drag.nodeId = null;
  866. this.draggingNodes = false;
  867. if (node != null && this.constants.dragNodes == true) {
  868. this.draggingNodes = true;
  869. this.drag.nodeId = node.id;
  870. // select the clicked node if not yet selected
  871. if (!node.isSelected()) {
  872. this._selectObject(node,false);
  873. }
  874. this.emit("dragStart",{nodeIds:this.getSelection().nodes});
  875. // create an array with the selected nodes and their original location and status
  876. for (var objectId in this.selectionObj.nodes) {
  877. if (this.selectionObj.nodes.hasOwnProperty(objectId)) {
  878. var object = this.selectionObj.nodes[objectId];
  879. var s = {
  880. id: object.id,
  881. node: object,
  882. // store original x, y, xFixed and yFixed, make the node temporarily Fixed
  883. x: object.x,
  884. y: object.y,
  885. xFixed: object.xFixed,
  886. yFixed: object.yFixed
  887. };
  888. object.xFixed = true;
  889. object.yFixed = true;
  890. this.drag.selection.push(s);
  891. }
  892. }
  893. }
  894. };
  895. /**
  896. * handle drag event
  897. * @private
  898. */
  899. Network.prototype._onDrag = function (event) {
  900. this._handleOnDrag(event)
  901. };
  902. /**
  903. * This function is called by _onDrag.
  904. * It is separated out because we can then overload it for the datamanipulation system.
  905. *
  906. * @private
  907. */
  908. Network.prototype._handleOnDrag = function(event) {
  909. if (this.drag.pinched) {
  910. return;
  911. }
  912. // remove the focus on node if it is focussed on by the focusOnNode
  913. this.releaseNode();
  914. var pointer = this._getPointer(event.gesture.center);
  915. var me = this;
  916. var drag = this.drag;
  917. var selection = drag.selection;
  918. if (selection && selection.length && this.constants.dragNodes == true) {
  919. // calculate delta's and new location
  920. var deltaX = pointer.x - drag.pointer.x;
  921. var deltaY = pointer.y - drag.pointer.y;
  922. // update position of all selected nodes
  923. selection.forEach(function (s) {
  924. var node = s.node;
  925. if (!s.xFixed) {
  926. node.x = me._XconvertDOMtoCanvas(me._XconvertCanvasToDOM(s.x) + deltaX);
  927. }
  928. if (!s.yFixed) {
  929. node.y = me._YconvertDOMtoCanvas(me._YconvertCanvasToDOM(s.y) + deltaY);
  930. }
  931. });
  932. // start _animationStep if not yet running
  933. if (!this.moving) {
  934. this.moving = true;
  935. this.start();
  936. }
  937. }
  938. else {
  939. // move the network
  940. if (this.constants.dragNetwork == true) {
  941. // if the drag was not started properly because the click started outside the network div, start it now.
  942. if (this.drag.pointer === undefined) {
  943. this._handleDragStart(event);
  944. return;
  945. }
  946. var diffX = pointer.x - this.drag.pointer.x;
  947. var diffY = pointer.y - this.drag.pointer.y;
  948. this._setTranslation(
  949. this.drag.translation.x + diffX,
  950. this.drag.translation.y + diffY
  951. );
  952. this._redraw();
  953. }
  954. }
  955. };
  956. /**
  957. * handle drag start event
  958. * @private
  959. */
  960. Network.prototype._onDragEnd = function (event) {
  961. this._handleDragEnd(event);
  962. };
  963. Network.prototype._handleDragEnd = function(event) {
  964. this.drag.dragging = false;
  965. var selection = this.drag.selection;
  966. if (selection && selection.length) {
  967. selection.forEach(function (s) {
  968. // restore original xFixed and yFixed
  969. s.node.xFixed = s.xFixed;
  970. s.node.yFixed = s.yFixed;
  971. });
  972. this.moving = true;
  973. this.start();
  974. }
  975. else {
  976. this._redraw();
  977. }
  978. if (this.draggingNodes == false) {
  979. this.emit("dragEnd",{nodeIds:[]});
  980. }
  981. else {
  982. this.emit("dragEnd",{nodeIds:this.getSelection().nodes});
  983. }
  984. }
  985. /**
  986. * handle tap/click event: select/unselect a node
  987. * @private
  988. */
  989. Network.prototype._onTap = function (event) {
  990. var pointer = this._getPointer(event.gesture.center);
  991. this.pointerPosition = pointer;
  992. this._handleTap(pointer);
  993. };
  994. /**
  995. * handle doubletap event
  996. * @private
  997. */
  998. Network.prototype._onDoubleTap = function (event) {
  999. var pointer = this._getPointer(event.gesture.center);
  1000. this._handleDoubleTap(pointer);
  1001. };
  1002. /**
  1003. * handle long tap event: multi select nodes
  1004. * @private
  1005. */
  1006. Network.prototype._onHold = function (event) {
  1007. var pointer = this._getPointer(event.gesture.center);
  1008. this.pointerPosition = pointer;
  1009. this._handleOnHold(pointer);
  1010. };
  1011. /**
  1012. * handle the release of the screen
  1013. *
  1014. * @private
  1015. */
  1016. Network.prototype._onRelease = function (event) {
  1017. var pointer = this._getPointer(event.gesture.center);
  1018. this._handleOnRelease(pointer);
  1019. };
  1020. /**
  1021. * Handle pinch event
  1022. * @param event
  1023. * @private
  1024. */
  1025. Network.prototype._onPinch = function (event) {
  1026. var pointer = this._getPointer(event.gesture.center);
  1027. this.drag.pinched = true;
  1028. if (!('scale' in this.pinch)) {
  1029. this.pinch.scale = 1;
  1030. }
  1031. // TODO: enabled moving while pinching?
  1032. var scale = this.pinch.scale * event.gesture.scale;
  1033. this._zoom(scale, pointer)
  1034. };
  1035. /**
  1036. * Zoom the network in or out
  1037. * @param {Number} scale a number around 1, and between 0.01 and 10
  1038. * @param {{x: Number, y: Number}} pointer Position on screen
  1039. * @return {Number} appliedScale scale is limited within the boundaries
  1040. * @private
  1041. */
  1042. Network.prototype._zoom = function(scale, pointer) {
  1043. if (this.constants.zoomable == true) {
  1044. var scaleOld = this._getScale();
  1045. if (scale < 0.00001) {
  1046. scale = 0.00001;
  1047. }
  1048. if (scale > 10) {
  1049. scale = 10;
  1050. }
  1051. var preScaleDragPointer = null;
  1052. if (this.drag !== undefined) {
  1053. if (this.drag.dragging == true) {
  1054. preScaleDragPointer = this.DOMtoCanvas(this.drag.pointer);
  1055. }
  1056. }
  1057. // + this.frame.canvas.clientHeight / 2
  1058. var translation = this._getTranslation();
  1059. var scaleFrac = scale / scaleOld;
  1060. var tx = (1 - scaleFrac) * pointer.x + translation.x * scaleFrac;
  1061. var ty = (1 - scaleFrac) * pointer.y + translation.y * scaleFrac;
  1062. this.areaCenter = {"x" : this._XconvertDOMtoCanvas(pointer.x),
  1063. "y" : this._YconvertDOMtoCanvas(pointer.y)};
  1064. this._setScale(scale);
  1065. this._setTranslation(tx, ty);
  1066. this.updateClustersDefault();
  1067. if (preScaleDragPointer != null) {
  1068. var postScaleDragPointer = this.canvasToDOM(preScaleDragPointer);
  1069. this.drag.pointer.x = postScaleDragPointer.x;
  1070. this.drag.pointer.y = postScaleDragPointer.y;
  1071. }
  1072. this._redraw();
  1073. if (scaleOld < scale) {
  1074. this.emit("zoom", {direction:"+"});
  1075. }
  1076. else {
  1077. this.emit("zoom", {direction:"-"});
  1078. }
  1079. return scale;
  1080. }
  1081. };
  1082. /**
  1083. * Event handler for mouse wheel event, used to zoom the timeline
  1084. * See http://adomas.org/javascript-mouse-wheel/
  1085. * https://github.com/EightMedia/hammer.js/issues/256
  1086. * @param {MouseEvent} event
  1087. * @private
  1088. */
  1089. Network.prototype._onMouseWheel = function(event) {
  1090. // retrieve delta
  1091. var delta = 0;
  1092. if (event.wheelDelta) { /* IE/Opera. */
  1093. delta = event.wheelDelta/120;
  1094. } else if (event.detail) { /* Mozilla case. */
  1095. // In Mozilla, sign of delta is different than in IE.
  1096. // Also, delta is multiple of 3.
  1097. delta = -event.detail/3;
  1098. }
  1099. // If delta is nonzero, handle it.
  1100. // Basically, delta is now positive if wheel was scrolled up,
  1101. // and negative, if wheel was scrolled down.
  1102. if (delta) {
  1103. // calculate the new scale
  1104. var scale = this._getScale();
  1105. var zoom = delta / 10;
  1106. if (delta < 0) {
  1107. zoom = zoom / (1 - zoom);
  1108. }
  1109. scale *= (1 + zoom);
  1110. // calculate the pointer location
  1111. var gesture = hammerUtil.fakeGesture(this, event);
  1112. var pointer = this._getPointer(gesture.center);
  1113. // apply the new scale
  1114. this._zoom(scale, pointer);
  1115. }
  1116. // Prevent default actions caused by mouse wheel.
  1117. event.preventDefault();
  1118. };
  1119. /**
  1120. * Mouse move handler for checking whether the title moves over a node with a title.
  1121. * @param {Event} event
  1122. * @private
  1123. */
  1124. Network.prototype._onMouseMoveTitle = function (event) {
  1125. var gesture = hammerUtil.fakeGesture(this, event);
  1126. var pointer = this._getPointer(gesture.center);
  1127. // check if the previously selected node is still selected
  1128. if (this.popupObj) {
  1129. this._checkHidePopup(pointer);
  1130. }
  1131. // if we bind the keyboard to the div, we have to highlight it to use it. This highlights it on mouse over
  1132. if (this.constants.keyboard.bindToWindow == false && this.constants.keyboard.enabled == true) {
  1133. this.frame.focus();
  1134. }
  1135. // start a timeout that will check if the mouse is positioned above
  1136. // an element
  1137. var me = this;
  1138. var checkShow = function() {
  1139. me._checkShowPopup(pointer);
  1140. };
  1141. if (this.popupTimer) {
  1142. clearInterval(this.popupTimer); // stop any running calculationTimer
  1143. }
  1144. if (!this.drag.dragging) {
  1145. this.popupTimer = setTimeout(checkShow, this.constants.tooltip.delay);
  1146. }
  1147. /**
  1148. * Adding hover highlights
  1149. */
  1150. if (this.constants.hover == true) {
  1151. // removing all hover highlights
  1152. for (var edgeId in this.hoverObj.edges) {
  1153. if (this.hoverObj.edges.hasOwnProperty(edgeId)) {
  1154. this.hoverObj.edges[edgeId].hover = false;
  1155. delete this.hoverObj.edges[edgeId];
  1156. }
  1157. }
  1158. // adding hover highlights
  1159. var obj = this._getNodeAt(pointer);
  1160. if (obj == null) {
  1161. obj = this._getEdgeAt(pointer);
  1162. }
  1163. if (obj != null) {
  1164. this._hoverObject(obj);
  1165. }
  1166. // removing all node hover highlights except for the selected one.
  1167. for (var nodeId in this.hoverObj.nodes) {
  1168. if (this.hoverObj.nodes.hasOwnProperty(nodeId)) {
  1169. if (obj instanceof Node && obj.id != nodeId || obj instanceof Edge || obj == null) {
  1170. this._blurObject(this.hoverObj.nodes[nodeId]);
  1171. delete this.hoverObj.nodes[nodeId];
  1172. }
  1173. }
  1174. }
  1175. this.redraw();
  1176. }
  1177. };
  1178. /**
  1179. * Check if there is an element on the given position in the network
  1180. * (a node or edge). If so, and if this element has a title,
  1181. * show a popup window with its title.
  1182. *
  1183. * @param {{x:Number, y:Number}} pointer
  1184. * @private
  1185. */
  1186. Network.prototype._checkShowPopup = function (pointer) {
  1187. var obj = {
  1188. left: this._XconvertDOMtoCanvas(pointer.x),
  1189. top: this._YconvertDOMtoCanvas(pointer.y),
  1190. right: this._XconvertDOMtoCanvas(pointer.x),
  1191. bottom: this._YconvertDOMtoCanvas(pointer.y)
  1192. };
  1193. var id;
  1194. var lastPopupNode = this.popupObj;
  1195. var nodeUnderCursor = false;
  1196. if (this.popupObj == undefined) {
  1197. // search the nodes for overlap, select the top one in case of multiple nodes
  1198. var nodes = this.nodes;
  1199. var overlappingNodes = [];
  1200. for (id in nodes) {
  1201. if (nodes.hasOwnProperty(id)) {
  1202. var node = nodes[id];
  1203. if (node.isOverlappingWith(obj)) {
  1204. if (node.getTitle() !== undefined) {
  1205. overlappingNodes.push(id);
  1206. }
  1207. }
  1208. }
  1209. }
  1210. if (overlappingNodes.length > 0) {
  1211. // if there are overlapping nodes, select the last one, this is the
  1212. // one which is drawn on top of the others
  1213. this.popupObj = this.nodes[overlappingNodes[overlappingNodes.length - 1]];
  1214. // if you hover over a node, the title of the edge is not supposed to be shown.
  1215. nodeUnderCursor = true;
  1216. }
  1217. }
  1218. if (this.popupObj === undefined && nodeUnderCursor == false) {
  1219. // search the edges for overlap
  1220. var edges = this.edges;
  1221. var overlappingEdges = [];
  1222. for (id in edges) {
  1223. if (edges.hasOwnProperty(id)) {
  1224. var edge = edges[id];
  1225. if (edge.connected && (edge.getTitle() !== undefined) &&
  1226. edge.isOverlappingWith(obj)) {
  1227. overlappingEdges.push(id);
  1228. }
  1229. }
  1230. }
  1231. if (overlappingEdges.length > 0) {
  1232. this.popupObj = this.edges[overlappingEdges[overlappingEdges.length - 1]];
  1233. }
  1234. }
  1235. if (this.popupObj) {
  1236. // show popup message window
  1237. if (this.popupObj != lastPopupNode) {
  1238. var me = this;
  1239. if (!me.popup) {
  1240. me.popup = new Popup(me.frame, me.constants.tooltip);
  1241. }
  1242. // adjust a small offset such that the mouse cursor is located in the
  1243. // bottom left location of the popup, and you can easily move over the
  1244. // popup area
  1245. me.popup.setPosition(pointer.x - 3, pointer.y - 3);
  1246. me.popup.setText(me.popupObj.getTitle());
  1247. me.popup.show();
  1248. }
  1249. }
  1250. else {
  1251. if (this.popup) {
  1252. this.popup.hide();
  1253. }
  1254. }
  1255. };
  1256. /**
  1257. * Check if the popup must be hided, which is the case when the mouse is no
  1258. * longer hovering on the object
  1259. * @param {{x:Number, y:Number}} pointer
  1260. * @private
  1261. */
  1262. Network.prototype._checkHidePopup = function (pointer) {
  1263. if (!this.popupObj || !this._getNodeAt(pointer) ) {
  1264. this.popupObj = undefined;
  1265. if (this.popup) {
  1266. this.popup.hide();
  1267. }
  1268. }
  1269. };
  1270. /**
  1271. * Set a new size for the network
  1272. * @param {string} width Width in pixels or percentage (for example '800px'
  1273. * or '50%')
  1274. * @param {string} height Height in pixels or percentage (for example '400px'
  1275. * or '30%')
  1276. */
  1277. Network.prototype.setSize = function(width, height) {
  1278. var emitEvent = false;
  1279. var oldWidth = this.frame.canvas.width;
  1280. var oldHeight = this.frame.canvas.height;
  1281. if (width != this.constants.width || height != this.constants.height || this.frame.style.width != width || this.frame.style.height != height) {
  1282. this.frame.style.width = width;
  1283. this.frame.style.height = height;
  1284. this.frame.canvas.style.width = '100%';
  1285. this.frame.canvas.style.height = '100%';
  1286. this.frame.canvas.width = this.frame.canvas.clientWidth * this.pixelRatio;
  1287. this.frame.canvas.height = this.frame.canvas.clientHeight * this.pixelRatio;
  1288. this.constants.width = width;
  1289. this.constants.height = height;
  1290. emitEvent = true;
  1291. }
  1292. else {
  1293. // this would adapt the width of the canvas to the width from 100% if and only if
  1294. // there is a change.
  1295. if (this.frame.canvas.width != this.frame.canvas.clientWidth * this.pixelRatio) {
  1296. this.frame.canvas.width = this.frame.canvas.clientWidth * this.pixelRatio;
  1297. emitEvent = true;
  1298. }
  1299. if (this.frame.canvas.height != this.frame.canvas.clientHeight * this.pixelRatio) {
  1300. this.frame.canvas.height = this.frame.canvas.clientHeight * this.pixelRatio;
  1301. emitEvent = true;
  1302. }
  1303. }
  1304. if (emitEvent == true) {
  1305. this.emit('resize', {width:this.frame.canvas.width * this.pixelRatio,height:this.frame.canvas.height * this.pixelRatio, oldWidth: oldWidth * this.pixelRatio, oldHeight: oldHeight * this.pixelRatio});
  1306. }
  1307. };
  1308. /**
  1309. * Set a data set with nodes for the network
  1310. * @param {Array | DataSet | DataView} nodes The data containing the nodes.
  1311. * @private
  1312. */
  1313. Network.prototype._setNodes = function(nodes) {
  1314. var oldNodesData = this.nodesData;
  1315. if (nodes instanceof DataSet || nodes instanceof DataView) {
  1316. this.nodesData = nodes;
  1317. }
  1318. else if (Array.isArray(nodes)) {
  1319. this.nodesData = new DataSet();
  1320. this.nodesData.add(nodes);
  1321. }
  1322. else if (!nodes) {
  1323. this.nodesData = new DataSet();
  1324. }
  1325. else {
  1326. throw new TypeError('Array or DataSet expected');
  1327. }
  1328. if (oldNodesData) {
  1329. // unsubscribe from old dataset
  1330. util.forEach(this.nodesListeners, function (callback, event) {
  1331. oldNodesData.off(event, callback);
  1332. });
  1333. }
  1334. // remove drawn nodes
  1335. this.nodes = {};
  1336. if (this.nodesData) {
  1337. // subscribe to new dataset
  1338. var me = this;
  1339. util.forEach(this.nodesListeners, function (callback, event) {
  1340. me.nodesData.on(event, callback);
  1341. });
  1342. // draw all new nodes
  1343. var ids = this.nodesData.getIds();
  1344. this._addNodes(ids);
  1345. }
  1346. this._updateSelection();
  1347. };
  1348. /**
  1349. * Add nodes
  1350. * @param {Number[] | String[]} ids
  1351. * @private
  1352. */
  1353. Network.prototype._addNodes = function(ids) {
  1354. var id;
  1355. for (var i = 0, len = ids.length; i < len; i++) {
  1356. id = ids[i];
  1357. var data = this.nodesData.get(id);
  1358. var node = new Node(data, this.images, this.groups, this.constants);
  1359. this.nodes[id] = node; // note: this may replace an existing node
  1360. if ((node.xFixed == false || node.yFixed == false) && (node.x === null || node.y === null)) {
  1361. var radius = 10 * 0.1*ids.length + 10;
  1362. var angle = 2 * Math.PI * Math.random();
  1363. if (node.xFixed == false) {node.x = radius * Math.cos(angle);}
  1364. if (node.yFixed == false) {node.y = radius * Math.sin(angle);}
  1365. }
  1366. this.moving = true;
  1367. }
  1368. this._updateNodeIndexList();
  1369. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  1370. this._resetLevels();
  1371. this._setupHierarchicalLayout();
  1372. }
  1373. this._updateCalculationNodes();
  1374. this._reconnectEdges();
  1375. this._updateValueRange(this.nodes);
  1376. this.updateLabels();
  1377. };
  1378. /**
  1379. * Update existing nodes, or create them when not yet existing
  1380. * @param {Number[] | String[]} ids
  1381. * @private
  1382. */
  1383. Network.prototype._updateNodes = function(ids,changedData) {
  1384. var nodes = this.nodes;
  1385. for (var i = 0, len = ids.length; i < len; i++) {
  1386. var id = ids[i];
  1387. var node = nodes[id];
  1388. var data = changedData[i];
  1389. if (node) {
  1390. // update node
  1391. node.setProperties(data, this.constants);
  1392. }
  1393. else {
  1394. // create node
  1395. node = new Node(properties, this.images, this.groups, this.constants);
  1396. nodes[id] = node;
  1397. }
  1398. }
  1399. this.moving = true;
  1400. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  1401. this._resetLevels();
  1402. this._setupHierarchicalLayout();
  1403. }
  1404. this._updateNodeIndexList();
  1405. this._updateValueRange(nodes);
  1406. };
  1407. /**
  1408. * Remove existing nodes. If nodes do not exist, the method will just ignore it.
  1409. * @param {Number[] | String[]} ids
  1410. * @private
  1411. */
  1412. Network.prototype._removeNodes = function(ids) {
  1413. var nodes = this.nodes;
  1414. for (var i = 0, len = ids.length; i < len; i++) {
  1415. var id = ids[i];
  1416. delete nodes[id];
  1417. }
  1418. this._updateNodeIndexList();
  1419. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  1420. this._resetLevels();
  1421. this._setupHierarchicalLayout();
  1422. }
  1423. this._updateCalculationNodes();
  1424. this._reconnectEdges();
  1425. this._updateSelection();
  1426. this._updateValueRange(nodes);
  1427. };
  1428. /**
  1429. * Load edges by reading the data table
  1430. * @param {Array | DataSet | DataView} edges The data containing the edges.
  1431. * @private
  1432. * @private
  1433. */
  1434. Network.prototype._setEdges = function(edges) {
  1435. var oldEdgesData = this.edgesData;
  1436. if (edges instanceof DataSet || edges instanceof DataView) {
  1437. this.edgesData = edges;
  1438. }
  1439. else if (Array.isArray(edges)) {
  1440. this.edgesData = new DataSet();
  1441. this.edgesData.add(edges);
  1442. }
  1443. else if (!edges) {
  1444. this.edgesData = new DataSet();
  1445. }
  1446. else {
  1447. throw new TypeError('Array or DataSet expected');
  1448. }
  1449. if (oldEdgesData) {
  1450. // unsubscribe from old dataset
  1451. util.forEach(this.edgesListeners, function (callback, event) {
  1452. oldEdgesData.off(event, callback);
  1453. });
  1454. }
  1455. // remove drawn edges
  1456. this.edges = {};
  1457. if (this.edgesData) {
  1458. // subscribe to new dataset
  1459. var me = this;
  1460. util.forEach(this.edgesListeners, function (callback, event) {
  1461. me.edgesData.on(event, callback);
  1462. });
  1463. // draw all new nodes
  1464. var ids = this.edgesData.getIds();
  1465. this._addEdges(ids);
  1466. }
  1467. this._reconnectEdges();
  1468. };
  1469. /**
  1470. * Add edges
  1471. * @param {Number[] | String[]} ids
  1472. * @private
  1473. */
  1474. Network.prototype._addEdges = function (ids) {
  1475. var edges = this.edges,
  1476. edgesData = this.edgesData;
  1477. for (var i = 0, len = ids.length; i < len; i++) {
  1478. var id = ids[i];
  1479. var oldEdge = edges[id];
  1480. if (oldEdge) {
  1481. oldEdge.disconnect();
  1482. }
  1483. var data = edgesData.get(id, {"showInternalIds" : true});
  1484. edges[id] = new Edge(data, this, this.constants);
  1485. }
  1486. this.moving = true;
  1487. this._updateValueRange(edges);
  1488. this._createBezierNodes();
  1489. this._updateCalculationNodes();
  1490. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  1491. this._resetLevels();
  1492. this._setupHierarchicalLayout();
  1493. }
  1494. };
  1495. /**
  1496. * Update existing edges, or create them when not yet existing
  1497. * @param {Number[] | String[]} ids
  1498. * @private
  1499. */
  1500. Network.prototype._updateEdges = function (ids) {
  1501. var edges = this.edges,
  1502. edgesData = this.edgesData;
  1503. for (var i = 0, len = ids.length; i < len; i++) {
  1504. var id = ids[i];
  1505. var data = edgesData.get(id);
  1506. var edge = edges[id];
  1507. if (edge) {
  1508. // update edge
  1509. edge.disconnect();
  1510. edge.setProperties(data, this.constants);
  1511. edge.connect();
  1512. }
  1513. else {
  1514. // create edge
  1515. edge = new Edge(data, this, this.constants);
  1516. this.edges[id] = edge;
  1517. }
  1518. }
  1519. this._createBezierNodes();
  1520. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  1521. this._resetLevels();
  1522. this._setupHierarchicalLayout();
  1523. }
  1524. this.moving = true;
  1525. this._updateValueRange(edges);
  1526. };
  1527. /**
  1528. * Remove existing edges. Non existing ids will be ignored
  1529. * @param {Number[] | String[]} ids
  1530. * @private
  1531. */
  1532. Network.prototype._removeEdges = function (ids) {
  1533. var edges = this.edges;
  1534. for (var i = 0, len = ids.length; i < len; i++) {
  1535. var id = ids[i];
  1536. var edge = edges[id];
  1537. if (edge) {
  1538. if (edge.via != null) {
  1539. delete this.sectors['support']['nodes'][edge.via.id];
  1540. }
  1541. edge.disconnect();
  1542. delete edges[id];
  1543. }
  1544. }
  1545. this.moving = true;
  1546. this._updateValueRange(edges);
  1547. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  1548. this._resetLevels();
  1549. this._setupHierarchicalLayout();
  1550. }
  1551. this._updateCalculationNodes();
  1552. };
  1553. /**
  1554. * Reconnect all edges
  1555. * @private
  1556. */
  1557. Network.prototype._reconnectEdges = function() {
  1558. var id,
  1559. nodes = this.nodes,
  1560. edges = this.edges;
  1561. for (id in nodes) {
  1562. if (nodes.hasOwnProperty(id)) {
  1563. nodes[id].edges = [];
  1564. nodes[id].dynamicEdges = [];
  1565. }
  1566. }
  1567. for (id in edges) {
  1568. if (edges.hasOwnProperty(id)) {
  1569. var edge = edges[id];
  1570. edge.from = null;
  1571. edge.to = null;
  1572. edge.connect();
  1573. }
  1574. }
  1575. };
  1576. /**
  1577. * Update the values of all object in the given array according to the current
  1578. * value range of the objects in the array.
  1579. * @param {Object} obj An object containing a set of Edges or Nodes
  1580. * The objects must have a method getValue() and
  1581. * setValueRange(min, max).
  1582. * @private
  1583. */
  1584. Network.prototype._updateValueRange = function(obj) {
  1585. var id;
  1586. // determine the range of the objects
  1587. var valueMin = undefined;
  1588. var valueMax = undefined;
  1589. for (id in obj) {
  1590. if (obj.hasOwnProperty(id)) {
  1591. var value = obj[id].getValue();
  1592. if (value !== undefined) {
  1593. valueMin = (valueMin === undefined) ? value : Math.min(value, valueMin);
  1594. valueMax = (valueMax === undefined) ? value : Math.max(value, valueMax);
  1595. }
  1596. }
  1597. }
  1598. // adjust the range of all objects
  1599. if (valueMin !== undefined && valueMax !== undefined) {
  1600. for (id in obj) {
  1601. if (obj.hasOwnProperty(id)) {
  1602. obj[id].setValueRange(valueMin, valueMax);
  1603. }
  1604. }
  1605. }
  1606. };
  1607. /**
  1608. * Redraw the network with the current data
  1609. * chart will be resized too.
  1610. */
  1611. Network.prototype.redraw = function() {
  1612. this.setSize(this.constants.width, this.constants.height);
  1613. this._redraw();
  1614. };
  1615. /**
  1616. * Redraw the network with the current data
  1617. * @param hidden | used to get the first estimate of the node sizes. only the nodes are drawn after which they are quickly drawn over.
  1618. * @private
  1619. */
  1620. Network.prototype._redraw = function(hidden) {
  1621. var ctx = this.frame.canvas.getContext('2d');
  1622. ctx.setTransform(this.pixelRatio, 0, 0, this.pixelRatio, 0, 0);
  1623. // clear the canvas
  1624. var w = this.frame.canvas.width * this.pixelRatio;
  1625. var h = this.frame.canvas.height * this.pixelRatio;
  1626. ctx.clearRect(0, 0, w, h);
  1627. // set scaling and translation
  1628. ctx.save();
  1629. ctx.translate(this.translation.x, this.translation.y);
  1630. ctx.scale(this.scale, this.scale);
  1631. this.canvasTopLeft = {
  1632. "x": this._XconvertDOMtoCanvas(0),
  1633. "y": this._YconvertDOMtoCanvas(0)
  1634. };
  1635. this.canvasBottomRight = {
  1636. "x": this._XconvertDOMtoCanvas(this.frame.canvas.clientWidth * this.pixelRatio),
  1637. "y": this._YconvertDOMtoCanvas(this.frame.canvas.clientHeight * this.pixelRatio)
  1638. };
  1639. if (!(hidden == true)) {
  1640. this._doInAllSectors("_drawAllSectorNodes", ctx);
  1641. if (this.drag.dragging == false || this.drag.dragging === undefined || this.constants.hideEdgesOnDrag == false) {
  1642. this._doInAllSectors("_drawEdges", ctx);
  1643. }
  1644. }
  1645. if (this.drag.dragging == false || this.drag.dragging === undefined || this.constants.hideNodesOnDrag == false) {
  1646. this._doInAllSectors("_drawNodes",ctx,false);
  1647. }
  1648. if (!(hidden == true)) {
  1649. if (this.controlNodesActive == true) {
  1650. this._doInAllSectors("_drawControlNodes", ctx);
  1651. }
  1652. }
  1653. // this._doInSupportSector("_drawNodes",ctx,true);
  1654. // this._drawTree(ctx,"#F00F0F");
  1655. // restore original scaling and translation
  1656. ctx.restore();
  1657. if (hidden == true) {
  1658. ctx.clearRect(0, 0, w, h);
  1659. }
  1660. };
  1661. /**
  1662. * Set the translation of the network
  1663. * @param {Number} offsetX Horizontal offset
  1664. * @param {Number} offsetY Vertical offset
  1665. * @private
  1666. */
  1667. Network.prototype._setTranslation = function(offsetX, offsetY) {
  1668. if (this.translation === undefined) {
  1669. this.translation = {
  1670. x: 0,
  1671. y: 0
  1672. };
  1673. }
  1674. if (offsetX !== undefined) {
  1675. this.translation.x = offsetX;
  1676. }
  1677. if (offsetY !== undefined) {
  1678. this.translation.y = offsetY;
  1679. }
  1680. this.emit('viewChanged');
  1681. };
  1682. /**
  1683. * Get the translation of the network
  1684. * @return {Object} translation An object with parameters x and y, both a number
  1685. * @private
  1686. */
  1687. Network.prototype._getTranslation = function() {
  1688. return {
  1689. x: this.translation.x,
  1690. y: this.translation.y
  1691. };
  1692. };
  1693. /**
  1694. * Scale the network
  1695. * @param {Number} scale Scaling factor 1.0 is unscaled
  1696. * @private
  1697. */
  1698. Network.prototype._setScale = function(scale) {
  1699. this.scale = scale;
  1700. };
  1701. /**
  1702. * Get the current scale of the network
  1703. * @return {Number} scale Scaling factor 1.0 is unscaled
  1704. * @private
  1705. */
  1706. Network.prototype._getScale = function() {
  1707. return this.scale;
  1708. };
  1709. /**
  1710. * Convert the X coordinate in DOM-space (coordinate point in browser relative to the container div) to
  1711. * the X coordinate in canvas-space (the simulation sandbox, which the camera looks upon)
  1712. * @param {number} x
  1713. * @returns {number}
  1714. * @private
  1715. */
  1716. Network.prototype._XconvertDOMtoCanvas = function(x) {
  1717. return (x - this.translation.x) / this.scale;
  1718. };
  1719. /**
  1720. * Convert the X coordinate in canvas-space (the simulation sandbox, which the camera looks upon) to
  1721. * the X coordinate in DOM-space (coordinate point in browser relative to the container div)
  1722. * @param {number} x
  1723. * @returns {number}
  1724. * @private
  1725. */
  1726. Network.prototype._XconvertCanvasToDOM = function(x) {
  1727. return x * this.scale + this.translation.x;
  1728. };
  1729. /**
  1730. * Convert the Y coordinate in DOM-space (coordinate point in browser relative to the container div) to
  1731. * the Y coordinate in canvas-space (the simulation sandbox, which the camera looks upon)
  1732. * @param {number} y
  1733. * @returns {number}
  1734. * @private
  1735. */
  1736. Network.prototype._YconvertDOMtoCanvas = function(y) {
  1737. return (y - this.translation.y) / this.scale;
  1738. };
  1739. /**
  1740. * Convert the Y coordinate in canvas-space (the simulation sandbox, which the camera looks upon) to
  1741. * the Y coordinate in DOM-space (coordinate point in browser relative to the container div)
  1742. * @param {number} y
  1743. * @returns {number}
  1744. * @private
  1745. */
  1746. Network.prototype._YconvertCanvasToDOM = function(y) {
  1747. return y * this.scale + this.translation.y ;
  1748. };
  1749. /**
  1750. *
  1751. * @param {object} pos = {x: number, y: number}
  1752. * @returns {{x: number, y: number}}
  1753. * @constructor
  1754. */
  1755. Network.prototype.canvasToDOM = function (pos) {
  1756. return {x: this._XconvertCanvasToDOM(pos.x), y: this._YconvertCanvasToDOM(pos.y)};
  1757. };
  1758. /**
  1759. *
  1760. * @param {object} pos = {x: number, y: number}
  1761. * @returns {{x: number, y: number}}
  1762. * @constructor
  1763. */
  1764. Network.prototype.DOMtoCanvas = function (pos) {
  1765. return {x: this._XconvertDOMtoCanvas(pos.x), y: this._YconvertDOMtoCanvas(pos.y)};
  1766. };
  1767. /**
  1768. * Redraw all nodes
  1769. * The 2d context of a HTML canvas can be retrieved by canvas.getContext('2d');
  1770. * @param {CanvasRenderingContext2D} ctx
  1771. * @param {Boolean} [alwaysShow]
  1772. * @private
  1773. */
  1774. Network.prototype._drawNodes = function(ctx,alwaysShow) {
  1775. if (alwaysShow === undefined) {
  1776. alwaysShow = false;
  1777. }
  1778. // first draw the unselected nodes
  1779. var nodes = this.nodes;
  1780. var selected = [];
  1781. for (var id in nodes) {
  1782. if (nodes.hasOwnProperty(id)) {
  1783. nodes[id].setScaleAndPos(this.scale,this.canvasTopLeft,this.canvasBottomRight);
  1784. if (nodes[id].isSelected()) {
  1785. selected.push(id);
  1786. }
  1787. else {
  1788. if (nodes[id].inArea() || alwaysShow) {
  1789. nodes[id].draw(ctx);
  1790. }
  1791. }
  1792. }
  1793. }
  1794. // draw the selected nodes on top
  1795. for (var s = 0, sMax = selected.length; s < sMax; s++) {
  1796. if (nodes[selected[s]].inArea() || alwaysShow) {
  1797. nodes[selected[s]].draw(ctx);
  1798. }
  1799. }
  1800. };
  1801. /**
  1802. * Redraw all edges
  1803. * The 2d context of a HTML canvas can be retrieved by canvas.getContext('2d');
  1804. * @param {CanvasRenderingContext2D} ctx
  1805. * @private
  1806. */
  1807. Network.prototype._drawEdges = function(ctx) {
  1808. var edges = this.edges;
  1809. for (var id in edges) {
  1810. if (edges.hasOwnProperty(id)) {
  1811. var edge = edges[id];
  1812. edge.setScale(this.scale);
  1813. if (edge.connected) {
  1814. edges[id].draw(ctx);
  1815. }
  1816. }
  1817. }
  1818. };
  1819. /**
  1820. * Redraw all edges
  1821. * The 2d context of a HTML canvas can be retrieved by canvas.getContext('2d');
  1822. * @param {CanvasRenderingContext2D} ctx
  1823. * @private
  1824. */
  1825. Network.prototype._drawControlNodes = function(ctx) {
  1826. var edges = this.edges;
  1827. for (var id in edges) {
  1828. if (edges.hasOwnProperty(id)) {
  1829. edges[id]._drawControlNodes(ctx);
  1830. }
  1831. }
  1832. };
  1833. /**
  1834. * Find a stable position for all nodes
  1835. * @private
  1836. */
  1837. Network.prototype._stabilize = function() {
  1838. if (this.constants.freezeForStabilization == true) {
  1839. this._freezeDefinedNodes();
  1840. }
  1841. // find stable position
  1842. var count = 0;
  1843. while (this.moving && count < this.constants.stabilizationIterations) {
  1844. this._physicsTick();
  1845. count++;
  1846. }
  1847. if (this.constants.zoomExtentOnStabilize == true) {
  1848. this.zoomExtent(undefined, false, true);
  1849. }
  1850. if (this.constants.freezeForStabilization == true) {
  1851. this._restoreFrozenNodes();
  1852. }
  1853. };
  1854. /**
  1855. * When initializing and stabilizing, we can freeze nodes with a predefined position. This greatly speeds up stabilization
  1856. * because only the supportnodes for the smoothCurves have to settle.
  1857. *
  1858. * @private
  1859. */
  1860. Network.prototype._freezeDefinedNodes = function() {
  1861. var nodes = this.nodes;
  1862. for (var id in nodes) {
  1863. if (nodes.hasOwnProperty(id)) {
  1864. if (nodes[id].x != null && nodes[id].y != null) {
  1865. nodes[id].fixedData.x = nodes[id].xFixed;
  1866. nodes[id].fixedData.y = nodes[id].yFixed;
  1867. nodes[id].xFixed = true;
  1868. nodes[id].yFixed = true;
  1869. }
  1870. }
  1871. }
  1872. };
  1873. /**
  1874. * Unfreezes the nodes that have been frozen by _freezeDefinedNodes.
  1875. *
  1876. * @private
  1877. */
  1878. Network.prototype._restoreFrozenNodes = function() {
  1879. var nodes = this.nodes;
  1880. for (var id in nodes) {
  1881. if (nodes.hasOwnProperty(id)) {
  1882. if (nodes[id].fixedData.x != null) {
  1883. nodes[id].xFixed = nodes[id].fixedData.x;
  1884. nodes[id].yFixed = nodes[id].fixedData.y;
  1885. }
  1886. }
  1887. }
  1888. };
  1889. /**
  1890. * Check if any of the nodes is still moving
  1891. * @param {number} vmin the minimum velocity considered as 'moving'
  1892. * @return {boolean} true if moving, false if non of the nodes is moving
  1893. * @private
  1894. */
  1895. Network.prototype._isMoving = function(vmin) {
  1896. var nodes = this.nodes;
  1897. for (var id in nodes) {
  1898. if (nodes.hasOwnProperty(id) && nodes[id].isMoving(vmin)) {
  1899. return true;
  1900. }
  1901. }
  1902. return false;
  1903. };
  1904. /**
  1905. * /**
  1906. * Perform one discrete step for all nodes
  1907. *
  1908. * @private
  1909. */
  1910. Network.prototype._discreteStepNodes = function() {
  1911. var interval = this.physicsDiscreteStepsize;
  1912. var nodes = this.nodes;
  1913. var nodeId;
  1914. var nodesPresent = false;
  1915. if (this.constants.maxVelocity > 0) {
  1916. for (nodeId in nodes) {
  1917. if (nodes.hasOwnProperty(nodeId)) {
  1918. nodes[nodeId].discreteStepLimited(interval, this.constants.maxVelocity);
  1919. nodesPresent = true;
  1920. }
  1921. }
  1922. }
  1923. else {
  1924. for (nodeId in nodes) {
  1925. if (nodes.hasOwnProperty(nodeId)) {
  1926. nodes[nodeId].discreteStep(interval);
  1927. nodesPresent = true;
  1928. }
  1929. }
  1930. }
  1931. if (nodesPresent == true) {
  1932. var vminCorrected = this.constants.minVelocity / Math.max(this.scale,0.05);
  1933. if (vminCorrected > 0.5*this.constants.maxVelocity) {
  1934. return true;
  1935. }
  1936. else {
  1937. return this._isMoving(vminCorrected);
  1938. }
  1939. }
  1940. return false;
  1941. };
  1942. Network.prototype._revertPhysicsState = function() {
  1943. var nodes = this.nodes;
  1944. for (var nodeId in nodes) {
  1945. if (nodes.hasOwnProperty(nodeId)) {
  1946. nodes[nodeId].revertPosition();
  1947. }
  1948. }
  1949. }
  1950. Network.prototype._revertPhysicsTick = function() {
  1951. this._doInAllActiveSectors("_revertPhysicsState");
  1952. if (this.constants.smoothCurves.enabled == true && this.constants.smoothCurves.dynamic == true) {
  1953. this._doInSupportSector("_revertPhysicsState");
  1954. }
  1955. }
  1956. /**
  1957. * A single simulation step (or "tick") in the physics simulation
  1958. *
  1959. * @private
  1960. */
  1961. Network.prototype._physicsTick = function() {
  1962. if (!this.freezeSimulation) {
  1963. if (this.moving == true) {
  1964. var mainMovingStatus = false;
  1965. var supportMovingStatus = false;
  1966. this._doInAllActiveSectors("_initializeForceCalculation");
  1967. var mainMoving = this._doInAllActiveSectors("_discreteStepNodes");
  1968. if (this.constants.smoothCurves.enabled == true && this.constants.smoothCurves.dynamic == true) {
  1969. supportMovingStatus = this._doInSupportSector("_discreteStepNodes");
  1970. }
  1971. // gather movement data from all sectors, if one moves, we are NOT stabilzied
  1972. for (var i = 0; i < mainMoving.length; i++) {mainMovingStatus = mainMoving[0] || mainMovingStatus;}
  1973. // determine if the network has stabilzied
  1974. this.moving = mainMovingStatus || supportMovingStatus;
  1975. if (this.moving == false) {
  1976. this._revertPhysicsTick();
  1977. }
  1978. else {
  1979. // this is here to ensure that there is no start event when the network is already stable.
  1980. if (this.startedStabilization == false) {
  1981. this.emit("startStabilization");
  1982. this.startedStabilization = true;
  1983. }
  1984. }
  1985. this.stabilizationIterations++;
  1986. }
  1987. }
  1988. };
  1989. /**
  1990. * This function runs one step of the animation. It calls an x amount of physics ticks and one render tick.
  1991. * It reschedules itself at the beginning of the function
  1992. *
  1993. * @private
  1994. */
  1995. Network.prototype._animationStep = function() {
  1996. // reset the timer so a new scheduled animation step can be set
  1997. this.timer = undefined;
  1998. // handle the keyboad movement
  1999. this._handleNavigation();
  2000. // check if the physics have settled
  2001. if (this.moving == true) {
  2002. var startTime = Date.now();
  2003. this._physicsTick();
  2004. var physicsTime = Date.now() - startTime;
  2005. // run double speed if it is a little graph
  2006. if ((this.renderTimestep - this.renderTime > 2 * physicsTime || this.runDoubleSpeed == true) && this.moving == true) {
  2007. this._physicsTick();
  2008. // this makes sure there is no jitter. The decision is taken once to run it at double speed.
  2009. if (this.renderTime != 0) {
  2010. this.runDoubleSpeed = true
  2011. }
  2012. }
  2013. }
  2014. var renderStartTime = Date.now();
  2015. this._redraw();
  2016. this.renderTime = Date.now() - renderStartTime;
  2017. // this schedules a new animation step
  2018. this.start();
  2019. };
  2020. if (typeof window !== 'undefined') {
  2021. window.requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame ||
  2022. window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;
  2023. }
  2024. /**
  2025. * Schedule a animation step with the refreshrate interval.
  2026. */
  2027. Network.prototype.start = function() {
  2028. if (this.moving == true || this.xIncrement != 0 || this.yIncrement != 0 || this.zoomIncrement != 0 || this.animating == true) {
  2029. if (!this.timer) {
  2030. if (this.requiresTimeout == true) {
  2031. this.timer = window.setTimeout(this._animationStep.bind(this), this.renderTimestep); // wait this.renderTimeStep milliseconds and perform the animation step function
  2032. }
  2033. else {
  2034. this.timer = window.requestAnimationFrame(this._animationStep.bind(this)); // wait this.renderTimeStep milliseconds and perform the animation step function
  2035. }
  2036. }
  2037. }
  2038. else {
  2039. this._redraw();
  2040. // this check is to ensure that the network does not emit these events if it was already stabilized and setOptions is called (setting moving to true and calling start())
  2041. if (this.stabilizationIterations > 1) {
  2042. // trigger the "stabilized" event.
  2043. // The event is triggered on the next tick, to prevent the case that
  2044. // it is fired while initializing the Network, in which case you would not
  2045. // be able to catch it
  2046. var me = this;
  2047. var params = {
  2048. iterations: me.stabilizationIterations
  2049. };
  2050. this.stabilizationIterations = 0;
  2051. this.startedStabilization = false;
  2052. setTimeout(function () {
  2053. me.emit("stabilized", params);
  2054. }, 0);
  2055. }
  2056. else {
  2057. this.stabilizationIterations = 0;
  2058. }
  2059. }
  2060. };
  2061. /**
  2062. * Move the network according to the keyboard presses.
  2063. *
  2064. * @private
  2065. */
  2066. Network.prototype._handleNavigation = function() {
  2067. if (this.xIncrement != 0 || this.yIncrement != 0) {
  2068. var translation = this._getTranslation();
  2069. this._setTranslation(translation.x+this.xIncrement, translation.y+this.yIncrement);
  2070. }
  2071. if (this.zoomIncrement != 0) {
  2072. var center = {
  2073. x: this.frame.canvas.clientWidth / 2,
  2074. y: this.frame.canvas.clientHeight / 2
  2075. };
  2076. this._zoom(this.scale*(1 + this.zoomIncrement), center);
  2077. }
  2078. };
  2079. /**
  2080. * Freeze the _animationStep
  2081. */
  2082. Network.prototype.toggleFreeze = function() {
  2083. if (this.freezeSimulation == false) {
  2084. this.freezeSimulation = true;
  2085. }
  2086. else {
  2087. this.freezeSimulation = false;
  2088. this.start();
  2089. }
  2090. };
  2091. /**
  2092. * This function cleans the support nodes if they are not needed and adds them when they are.
  2093. *
  2094. * @param {boolean} [disableStart]
  2095. * @private
  2096. */
  2097. Network.prototype._configureSmoothCurves = function(disableStart) {
  2098. if (disableStart === undefined) {
  2099. disableStart = true;
  2100. }
  2101. if (this.constants.smoothCurves.enabled == true && this.constants.smoothCurves.dynamic == true) {
  2102. this._createBezierNodes();
  2103. // cleanup unused support nodes
  2104. for (var nodeId in this.sectors['support']['nodes']) {
  2105. if (this.sectors['support']['nodes'].hasOwnProperty(nodeId)) {
  2106. if (this.edges[this.sectors['support']['nodes'][nodeId].parentEdgeId] === undefined) {
  2107. delete this.sectors['support']['nodes'][nodeId];
  2108. }
  2109. }
  2110. }
  2111. }
  2112. else {
  2113. // delete the support nodes
  2114. this.sectors['support']['nodes'] = {};
  2115. for (var edgeId in this.edges) {
  2116. if (this.edges.hasOwnProperty(edgeId)) {
  2117. this.edges[edgeId].via = null;
  2118. }
  2119. }
  2120. }
  2121. this._updateCalculationNodes();
  2122. if (!disableStart) {
  2123. this.moving = true;
  2124. this.start();
  2125. }
  2126. };
  2127. /**
  2128. * Bezier curves require an anchor point to calculate the smooth flow. These points are nodes. These nodes are invisible but
  2129. * are used for the force calculation.
  2130. *
  2131. * @private
  2132. */
  2133. Network.prototype._createBezierNodes = function() {
  2134. if (this.constants.smoothCurves.enabled == true && this.constants.smoothCurves.dynamic == true) {
  2135. for (var edgeId in this.edges) {
  2136. if (this.edges.hasOwnProperty(edgeId)) {
  2137. var edge = this.edges[edgeId];
  2138. if (edge.via == null) {
  2139. var nodeId = "edgeId:".concat(edge.id);
  2140. this.sectors['support']['nodes'][nodeId] = new Node(
  2141. {id:nodeId,
  2142. mass:1,
  2143. shape:'circle',
  2144. image:"",
  2145. internalMultiplier:1
  2146. },{},{},this.constants);
  2147. edge.via = this.sectors['support']['nodes'][nodeId];
  2148. edge.via.parentEdgeId = edge.id;
  2149. edge.positionBezierNode();
  2150. }
  2151. }
  2152. }
  2153. }
  2154. };
  2155. /**
  2156. * load the functions that load the mixins into the prototype.
  2157. *
  2158. * @private
  2159. */
  2160. Network.prototype._initializeMixinLoaders = function () {
  2161. for (var mixin in MixinLoader) {
  2162. if (MixinLoader.hasOwnProperty(mixin)) {
  2163. Network.prototype[mixin] = MixinLoader[mixin];
  2164. }
  2165. }
  2166. };
  2167. /**
  2168. * Load the XY positions of the nodes into the dataset.
  2169. */
  2170. Network.prototype.storePosition = function() {
  2171. console.log("storePosition is depricated: use .storePositions() from now on.")
  2172. this.storePositions();
  2173. };
  2174. /**
  2175. * Load the XY positions of the nodes into the dataset.
  2176. */
  2177. Network.prototype.storePositions = function() {
  2178. var dataArray = [];
  2179. for (var nodeId in this.nodes) {
  2180. if (this.nodes.hasOwnProperty(nodeId)) {
  2181. var node = this.nodes[nodeId];
  2182. var allowedToMoveX = !this.nodes.xFixed;
  2183. var allowedToMoveY = !this.nodes.yFixed;
  2184. if (this.nodesData._data[nodeId].x != Math.round(node.x) || this.nodesData._data[nodeId].y != Math.round(node.y)) {
  2185. dataArray.push({id:nodeId,x:Math.round(node.x),y:Math.round(node.y),allowedToMoveX:allowedToMoveX,allowedToMoveY:allowedToMoveY});
  2186. }
  2187. }
  2188. }
  2189. this.nodesData.update(dataArray);
  2190. };
  2191. /**
  2192. * Return the positions of the nodes.
  2193. */
  2194. Network.prototype.getPositions = function(ids) {
  2195. var dataArray = {};
  2196. if (ids !== undefined) {
  2197. if (Array.isArray(ids) == true) {
  2198. for (var i = 0; i < ids.length; i++) {
  2199. if (this.nodes[ids[i]] !== undefined) {
  2200. var node = this.nodes[ids[i]];
  2201. dataArray[ids[i]] = {x: Math.round(node.x), y: Math.round(node.y)};
  2202. }
  2203. }
  2204. }
  2205. else {
  2206. if (this.nodes[ids] !== undefined) {
  2207. var node = this.nodes[ids];
  2208. dataArray[ids] = {x: Math.round(node.x), y: Math.round(node.y)};
  2209. }
  2210. }
  2211. }
  2212. else {
  2213. for (var nodeId in this.nodes) {
  2214. if (this.nodes.hasOwnProperty(nodeId)) {
  2215. var node = this.nodes[nodeId];
  2216. dataArray[nodeId] = {x: Math.round(node.x), y: Math.round(node.y)};
  2217. }
  2218. }
  2219. }
  2220. return dataArray;
  2221. };
  2222. /**
  2223. * Center a node in view.
  2224. *
  2225. * @param {Number} nodeId
  2226. * @param {Number} [options]
  2227. */
  2228. Network.prototype.focusOnNode = function (nodeId, options) {
  2229. if (this.nodes.hasOwnProperty(nodeId)) {
  2230. if (options === undefined) {
  2231. options = {};
  2232. }
  2233. var nodePosition = {x: this.nodes[nodeId].x, y: this.nodes[nodeId].y};
  2234. options.position = nodePosition;
  2235. options.lockedOnNode = nodeId;
  2236. this.moveTo(options)
  2237. }
  2238. else {
  2239. console.log("This nodeId cannot be found.");
  2240. }
  2241. };
  2242. /**
  2243. *
  2244. * @param {Object} options | options.offset = {x:Number, y:Number} // offset from the center in DOM pixels
  2245. * | options.scale = Number // scale to move to
  2246. * | options.position = {x:Number, y:Number} // position to move to
  2247. * | options.animation = {duration:Number, easingFunction:String} || Boolean // position to move to
  2248. */
  2249. Network.prototype.moveTo = function (options) {
  2250. if (options === undefined) {
  2251. options = {};
  2252. return;
  2253. }
  2254. if (options.offset === undefined) {options.offset = {x: 0, y: 0}; }
  2255. if (options.offset.x === undefined) {options.offset.x = 0; }
  2256. if (options.offset.y === undefined) {options.offset.y = 0; }
  2257. if (options.scale === undefined) {options.scale = this._getScale(); }
  2258. if (options.position === undefined) {options.position = this._getTranslation();}
  2259. if (options.animation === undefined) {options.animation = {duration:0}; }
  2260. if (options.animation === false ) {options.animation = {duration:0}; }
  2261. if (options.animation === true ) {options.animation = {}; }
  2262. if (options.animation.duration === undefined) {options.animation.duration = 1000; } // default duration
  2263. if (options.animation.easingFunction === undefined) {options.animation.easingFunction = "easeInOutQuad"; } // default easing function
  2264. this.animateView(options);
  2265. };
  2266. /**
  2267. *
  2268. * @param {Object} options | options.offset = {x:Number, y:Number} // offset from the center in DOM pixels
  2269. * | options.time = Number // animation time in milliseconds
  2270. * | options.scale = Number // scale to animate to
  2271. * | options.position = {x:Number, y:Number} // position to animate to
  2272. * | options.easingFunction = String // linear, easeInQuad, easeOutQuad, easeInOutQuad,
  2273. * // easeInCubic, easeOutCubic, easeInOutCubic,
  2274. * // easeInQuart, easeOutQuart, easeInOutQuart,
  2275. * // easeInQuint, easeOutQuint, easeInOutQuint
  2276. */
  2277. Network.prototype.animateView = function (options) {
  2278. if (options === undefined) {
  2279. options = {};
  2280. return;
  2281. }
  2282. // release if something focussed on the node
  2283. this.releaseNode();
  2284. if (options.locked == true) {
  2285. this.lockedOnNodeId = options.lockedOnNode;
  2286. this.lockedOnNodeOffset = options.offset;
  2287. }
  2288. // forcefully complete the old animation if it was still running
  2289. if (this.easingTime != 0) {
  2290. this._transitionRedraw(1); // by setting easingtime to 1, we finish the animation.
  2291. }
  2292. this.sourceScale = this._getScale();
  2293. this.sourceTranslation = this._getTranslation();
  2294. this.targetScale = options.scale;
  2295. // set the scale so the viewCenter is based on the correct zoom level. This is overridden in the transitionRedraw
  2296. // but at least then we'll have the target transition
  2297. this._setScale(this.targetScale);
  2298. var viewCenter = this.DOMtoCanvas({x: 0.5 * this.frame.canvas.clientWidth, y: 0.5 * this.frame.canvas.clientHeight});
  2299. var distanceFromCenter = { // offset from view, distance view has to change by these x and y to center the node
  2300. x: viewCenter.x - options.position.x,
  2301. y: viewCenter.y - options.position.y
  2302. };
  2303. this.targetTranslation = {
  2304. x: this.sourceTranslation.x + distanceFromCenter.x * this.targetScale + options.offset.x,
  2305. y: this.sourceTranslation.y + distanceFromCenter.y * this.targetScale + options.offset.y
  2306. };
  2307. // if the time is set to 0, don't do an animation
  2308. if (options.animation.duration == 0) {
  2309. if (this.lockedOnNodeId != null) {
  2310. this._classicRedraw = this._redraw;
  2311. this._redraw = this._lockedRedraw;
  2312. }
  2313. else {
  2314. this._setScale(this.targetScale);
  2315. this._setTranslation(this.targetTranslation.x, this.targetTranslation.y);
  2316. this._redraw();
  2317. }
  2318. }
  2319. else {
  2320. this.animating = true;
  2321. this.animationSpeed = 1 / (this.renderRefreshRate * options.animation.duration * 0.001) || 1 / this.renderRefreshRate;
  2322. this.animationEasingFunction = options.animation.easingFunction;
  2323. this._classicRedraw = this._redraw;
  2324. this._redraw = this._transitionRedraw;
  2325. this._redraw();
  2326. this.start();
  2327. }
  2328. };
  2329. /**
  2330. * used to animate smoothly by hijacking the redraw function.
  2331. * @private
  2332. */
  2333. Network.prototype._lockedRedraw = function () {
  2334. var nodePosition = {x: this.nodes[this.lockedOnNodeId].x, y: this.nodes[this.lockedOnNodeId].y};
  2335. var viewCenter = this.DOMtoCanvas({x: 0.5 * this.frame.canvas.clientWidth, y: 0.5 * this.frame.canvas.clientHeight});
  2336. var distanceFromCenter = { // offset from view, distance view has to change by these x and y to center the node
  2337. x: viewCenter.x - nodePosition.x,
  2338. y: viewCenter.y - nodePosition.y
  2339. };
  2340. var sourceTranslation = this._getTranslation();
  2341. var targetTranslation = {
  2342. x: sourceTranslation.x + distanceFromCenter.x * this.scale + this.lockedOnNodeOffset.x,
  2343. y: sourceTranslation.y + distanceFromCenter.y * this.scale + this.lockedOnNodeOffset.y
  2344. };
  2345. this._setTranslation(targetTranslation.x,targetTranslation.y);
  2346. this._classicRedraw();
  2347. }
  2348. Network.prototype.releaseNode = function () {
  2349. if (this.lockedOnNodeId != null) {
  2350. this._redraw = this._classicRedraw;
  2351. this.lockedOnNodeId = null;
  2352. this.lockedOnNodeOffset = null;
  2353. }
  2354. }
  2355. /**
  2356. *
  2357. * @param easingTime
  2358. * @private
  2359. */
  2360. Network.prototype._transitionRedraw = function (easingTime) {
  2361. this.easingTime = easingTime || this.easingTime + this.animationSpeed;
  2362. this.easingTime += this.animationSpeed;
  2363. var progress = util.easingFunctions[this.animationEasingFunction](this.easingTime);
  2364. this._setScale(this.sourceScale + (this.targetScale - this.sourceScale) * progress);
  2365. this._setTranslation(
  2366. this.sourceTranslation.x + (this.targetTranslation.x - this.sourceTranslation.x) * progress,
  2367. this.sourceTranslation.y + (this.targetTranslation.y - this.sourceTranslation.y) * progress
  2368. );
  2369. this._classicRedraw();
  2370. // cleanup
  2371. if (this.easingTime >= 1.0) {
  2372. this.animating = false;
  2373. this.easingTime = 0;
  2374. if (this.lockedOnNodeId != null) {
  2375. this._redraw = this._lockedRedraw;
  2376. }
  2377. else {
  2378. this._redraw = this._classicRedraw;
  2379. }
  2380. this.emit("animationFinished");
  2381. }
  2382. };
  2383. Network.prototype._classicRedraw = function () {
  2384. // placeholder function to be overloaded by animations;
  2385. };
  2386. /**
  2387. * Returns true when the Network is active.
  2388. * @returns {boolean}
  2389. */
  2390. Network.prototype.isActive = function () {
  2391. return !this.activator || this.activator.active;
  2392. };
  2393. /**
  2394. * Sets the scale
  2395. * @returns {Number}
  2396. */
  2397. Network.prototype.setScale = function () {
  2398. return this._setScale();
  2399. };
  2400. /**
  2401. * Returns the scale
  2402. * @returns {Number}
  2403. */
  2404. Network.prototype.getScale = function () {
  2405. return this._getScale();
  2406. };
  2407. /**
  2408. * Returns the scale
  2409. * @returns {Number}
  2410. */
  2411. Network.prototype.getCenterCoordinates = function () {
  2412. return this.DOMtoCanvas({x: 0.5 * this.frame.canvas.clientWidth, y: 0.5 * this.frame.canvas.clientHeight});
  2413. };
  2414. Network.prototype.getBoundingBox = function(nodeId) {
  2415. if (this.nodes[nodeId] !== undefined) {
  2416. return this.nodes[nodeId].boundingBox;
  2417. }
  2418. }
  2419. module.exports = Network;