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.

2744 lines
83 KiB

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