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.

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