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.

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