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.

2309 lines
68 KiB

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