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.

2375 lines
70 KiB

11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 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. this.moving = true;
  954. this.start();
  955. }
  956. this._redraw();
  957. };
  958. /**
  959. * handle tap/click event: select/unselect a node
  960. * @private
  961. */
  962. Network.prototype._onTap = function (event) {
  963. var pointer = this._getPointer(event.gesture.center);
  964. this.pointerPosition = pointer;
  965. this._handleTap(pointer);
  966. };
  967. /**
  968. * handle doubletap event
  969. * @private
  970. */
  971. Network.prototype._onDoubleTap = function (event) {
  972. var pointer = this._getPointer(event.gesture.center);
  973. this._handleDoubleTap(pointer);
  974. };
  975. /**
  976. * handle long tap event: multi select nodes
  977. * @private
  978. */
  979. Network.prototype._onHold = function (event) {
  980. var pointer = this._getPointer(event.gesture.center);
  981. this.pointerPosition = pointer;
  982. this._handleOnHold(pointer);
  983. };
  984. /**
  985. * handle the release of the screen
  986. *
  987. * @private
  988. */
  989. Network.prototype._onRelease = function (event) {
  990. var pointer = this._getPointer(event.gesture.center);
  991. this._handleOnRelease(pointer);
  992. };
  993. /**
  994. * Handle pinch event
  995. * @param event
  996. * @private
  997. */
  998. Network.prototype._onPinch = function (event) {
  999. var pointer = this._getPointer(event.gesture.center);
  1000. this.drag.pinched = true;
  1001. if (!('scale' in this.pinch)) {
  1002. this.pinch.scale = 1;
  1003. }
  1004. // TODO: enabled moving while pinching?
  1005. var scale = this.pinch.scale * event.gesture.scale;
  1006. this._zoom(scale, pointer)
  1007. };
  1008. /**
  1009. * Zoom the network in or out
  1010. * @param {Number} scale a number around 1, and between 0.01 and 10
  1011. * @param {{x: Number, y: Number}} pointer Position on screen
  1012. * @return {Number} appliedScale scale is limited within the boundaries
  1013. * @private
  1014. */
  1015. Network.prototype._zoom = function(scale, pointer) {
  1016. if (this.constants.zoomable == true) {
  1017. var scaleOld = this._getScale();
  1018. if (scale < 0.00001) {
  1019. scale = 0.00001;
  1020. }
  1021. if (scale > 10) {
  1022. scale = 10;
  1023. }
  1024. var preScaleDragPointer = null;
  1025. if (this.drag !== undefined) {
  1026. if (this.drag.dragging == true) {
  1027. preScaleDragPointer = this.DOMtoCanvas(this.drag.pointer);
  1028. }
  1029. }
  1030. // + this.frame.canvas.clientHeight / 2
  1031. var translation = this._getTranslation();
  1032. var scaleFrac = scale / scaleOld;
  1033. var tx = (1 - scaleFrac) * pointer.x + translation.x * scaleFrac;
  1034. var ty = (1 - scaleFrac) * pointer.y + translation.y * scaleFrac;
  1035. this.areaCenter = {"x" : this._XconvertDOMtoCanvas(pointer.x),
  1036. "y" : this._YconvertDOMtoCanvas(pointer.y)};
  1037. this._setScale(scale);
  1038. this._setTranslation(tx, ty);
  1039. this.updateClustersDefault();
  1040. if (preScaleDragPointer != null) {
  1041. var postScaleDragPointer = this.canvasToDOM(preScaleDragPointer);
  1042. this.drag.pointer.x = postScaleDragPointer.x;
  1043. this.drag.pointer.y = postScaleDragPointer.y;
  1044. }
  1045. this._redraw();
  1046. if (scaleOld < scale) {
  1047. this.emit("zoom", {direction:"+"});
  1048. }
  1049. else {
  1050. this.emit("zoom", {direction:"-"});
  1051. }
  1052. return scale;
  1053. }
  1054. };
  1055. /**
  1056. * Event handler for mouse wheel event, used to zoom the timeline
  1057. * See http://adomas.org/javascript-mouse-wheel/
  1058. * https://github.com/EightMedia/hammer.js/issues/256
  1059. * @param {MouseEvent} event
  1060. * @private
  1061. */
  1062. Network.prototype._onMouseWheel = function(event) {
  1063. // retrieve delta
  1064. var delta = 0;
  1065. if (event.wheelDelta) { /* IE/Opera. */
  1066. delta = event.wheelDelta/120;
  1067. } else if (event.detail) { /* Mozilla case. */
  1068. // In Mozilla, sign of delta is different than in IE.
  1069. // Also, delta is multiple of 3.
  1070. delta = -event.detail/3;
  1071. }
  1072. // If delta is nonzero, handle it.
  1073. // Basically, delta is now positive if wheel was scrolled up,
  1074. // and negative, if wheel was scrolled down.
  1075. if (delta) {
  1076. // calculate the new scale
  1077. var scale = this._getScale();
  1078. var zoom = delta / 10;
  1079. if (delta < 0) {
  1080. zoom = zoom / (1 - zoom);
  1081. }
  1082. scale *= (1 + zoom);
  1083. // calculate the pointer location
  1084. var gesture = util.fakeGesture(this, event);
  1085. var pointer = this._getPointer(gesture.center);
  1086. // apply the new scale
  1087. this._zoom(scale, pointer);
  1088. }
  1089. // Prevent default actions caused by mouse wheel.
  1090. event.preventDefault();
  1091. };
  1092. /**
  1093. * Mouse move handler for checking whether the title moves over a node with a title.
  1094. * @param {Event} event
  1095. * @private
  1096. */
  1097. Network.prototype._onMouseMoveTitle = function (event) {
  1098. var gesture = util.fakeGesture(this, event);
  1099. var pointer = this._getPointer(gesture.center);
  1100. // check if the previously selected node is still selected
  1101. if (this.popupObj) {
  1102. this._checkHidePopup(pointer);
  1103. }
  1104. // start a timeout that will check if the mouse is positioned above
  1105. // an element
  1106. var me = this;
  1107. var checkShow = function() {
  1108. me._checkShowPopup(pointer);
  1109. };
  1110. if (this.popupTimer) {
  1111. clearInterval(this.popupTimer); // stop any running calculationTimer
  1112. }
  1113. if (!this.drag.dragging) {
  1114. this.popupTimer = setTimeout(checkShow, this.constants.tooltip.delay);
  1115. }
  1116. /**
  1117. * Adding hover highlights
  1118. */
  1119. if (this.constants.hover == true) {
  1120. // removing all hover highlights
  1121. for (var edgeId in this.hoverObj.edges) {
  1122. if (this.hoverObj.edges.hasOwnProperty(edgeId)) {
  1123. this.hoverObj.edges[edgeId].hover = false;
  1124. delete this.hoverObj.edges[edgeId];
  1125. }
  1126. }
  1127. // adding hover highlights
  1128. var obj = this._getNodeAt(pointer);
  1129. if (obj == null) {
  1130. obj = this._getEdgeAt(pointer);
  1131. }
  1132. if (obj != null) {
  1133. this._hoverObject(obj);
  1134. }
  1135. // removing all node hover highlights except for the selected one.
  1136. for (var nodeId in this.hoverObj.nodes) {
  1137. if (this.hoverObj.nodes.hasOwnProperty(nodeId)) {
  1138. if (obj instanceof Node && obj.id != nodeId || obj instanceof Edge || obj == null) {
  1139. this._blurObject(this.hoverObj.nodes[nodeId]);
  1140. delete this.hoverObj.nodes[nodeId];
  1141. }
  1142. }
  1143. }
  1144. this.redraw();
  1145. }
  1146. };
  1147. /**
  1148. * Check if there is an element on the given position in the network
  1149. * (a node or edge). If so, and if this element has a title,
  1150. * show a popup window with its title.
  1151. *
  1152. * @param {{x:Number, y:Number}} pointer
  1153. * @private
  1154. */
  1155. Network.prototype._checkShowPopup = function (pointer) {
  1156. var obj = {
  1157. left: this._XconvertDOMtoCanvas(pointer.x),
  1158. top: this._YconvertDOMtoCanvas(pointer.y),
  1159. right: this._XconvertDOMtoCanvas(pointer.x),
  1160. bottom: this._YconvertDOMtoCanvas(pointer.y)
  1161. };
  1162. var id;
  1163. var lastPopupNode = this.popupObj;
  1164. if (this.popupObj == undefined) {
  1165. // search the nodes for overlap, select the top one in case of multiple nodes
  1166. var nodes = this.nodes;
  1167. for (id in nodes) {
  1168. if (nodes.hasOwnProperty(id)) {
  1169. var node = nodes[id];
  1170. if (node.getTitle() !== undefined && node.isOverlappingWith(obj)) {
  1171. this.popupObj = node;
  1172. break;
  1173. }
  1174. }
  1175. }
  1176. }
  1177. if (this.popupObj === undefined) {
  1178. // search the edges for overlap
  1179. var edges = this.edges;
  1180. for (id in edges) {
  1181. if (edges.hasOwnProperty(id)) {
  1182. var edge = edges[id];
  1183. if (edge.connected && (edge.getTitle() !== undefined) &&
  1184. edge.isOverlappingWith(obj)) {
  1185. this.popupObj = edge;
  1186. break;
  1187. }
  1188. }
  1189. }
  1190. }
  1191. if (this.popupObj) {
  1192. // show popup message window
  1193. if (this.popupObj != lastPopupNode) {
  1194. var me = this;
  1195. if (!me.popup) {
  1196. me.popup = new Popup(me.frame, me.constants.tooltip);
  1197. }
  1198. // adjust a small offset such that the mouse cursor is located in the
  1199. // bottom left location of the popup, and you can easily move over the
  1200. // popup area
  1201. me.popup.setPosition(pointer.x - 3, pointer.y - 3);
  1202. me.popup.setText(me.popupObj.getTitle());
  1203. me.popup.show();
  1204. }
  1205. }
  1206. else {
  1207. if (this.popup) {
  1208. this.popup.hide();
  1209. }
  1210. }
  1211. };
  1212. /**
  1213. * Check if the popup must be hided, which is the case when the mouse is no
  1214. * longer hovering on the object
  1215. * @param {{x:Number, y:Number}} pointer
  1216. * @private
  1217. */
  1218. Network.prototype._checkHidePopup = function (pointer) {
  1219. if (!this.popupObj || !this._getNodeAt(pointer) ) {
  1220. this.popupObj = undefined;
  1221. if (this.popup) {
  1222. this.popup.hide();
  1223. }
  1224. }
  1225. };
  1226. /**
  1227. * Set a new size for the network
  1228. * @param {string} width Width in pixels or percentage (for example '800px'
  1229. * or '50%')
  1230. * @param {string} height Height in pixels or percentage (for example '400px'
  1231. * or '30%')
  1232. */
  1233. Network.prototype.setSize = function(width, height) {
  1234. this.frame.style.width = width;
  1235. this.frame.style.height = height;
  1236. this.frame.canvas.style.width = '100%';
  1237. this.frame.canvas.style.height = '100%';
  1238. this.frame.canvas.width = this.frame.canvas.clientWidth;
  1239. this.frame.canvas.height = this.frame.canvas.clientHeight;
  1240. if (this.manipulationDiv !== undefined) {
  1241. this.manipulationDiv.style.width = this.frame.canvas.clientWidth + "px";
  1242. }
  1243. if (this.navigationDivs !== undefined) {
  1244. if (this.navigationDivs['wrapper'] !== undefined) {
  1245. this.navigationDivs['wrapper'].style.width = this.frame.canvas.clientWidth + "px";
  1246. this.navigationDivs['wrapper'].style.height = this.frame.canvas.clientHeight + "px";
  1247. }
  1248. }
  1249. this.emit('resize', {width:this.frame.canvas.width,height:this.frame.canvas.height});
  1250. };
  1251. /**
  1252. * Set a data set with nodes for the network
  1253. * @param {Array | DataSet | DataView} nodes The data containing the nodes.
  1254. * @private
  1255. */
  1256. Network.prototype._setNodes = function(nodes) {
  1257. var oldNodesData = this.nodesData;
  1258. if (nodes instanceof DataSet || nodes instanceof DataView) {
  1259. this.nodesData = nodes;
  1260. }
  1261. else if (nodes instanceof Array) {
  1262. this.nodesData = new DataSet();
  1263. this.nodesData.add(nodes);
  1264. }
  1265. else if (!nodes) {
  1266. this.nodesData = new DataSet();
  1267. }
  1268. else {
  1269. throw new TypeError('Array or DataSet expected');
  1270. }
  1271. if (oldNodesData) {
  1272. // unsubscribe from old dataset
  1273. util.forEach(this.nodesListeners, function (callback, event) {
  1274. oldNodesData.off(event, callback);
  1275. });
  1276. }
  1277. // remove drawn nodes
  1278. this.nodes = {};
  1279. if (this.nodesData) {
  1280. // subscribe to new dataset
  1281. var me = this;
  1282. util.forEach(this.nodesListeners, function (callback, event) {
  1283. me.nodesData.on(event, callback);
  1284. });
  1285. // draw all new nodes
  1286. var ids = this.nodesData.getIds();
  1287. this._addNodes(ids);
  1288. }
  1289. this._updateSelection();
  1290. };
  1291. /**
  1292. * Add nodes
  1293. * @param {Number[] | String[]} ids
  1294. * @private
  1295. */
  1296. Network.prototype._addNodes = function(ids) {
  1297. var id;
  1298. for (var i = 0, len = ids.length; i < len; i++) {
  1299. id = ids[i];
  1300. var data = this.nodesData.get(id);
  1301. var node = new Node(data, this.images, this.groups, this.constants);
  1302. this.nodes[id] = node; // note: this may replace an existing node
  1303. if ((node.xFixed == false || node.yFixed == false) && (node.x === null || node.y === null)) {
  1304. var radius = 10 * 0.1*ids.length;
  1305. var angle = 2 * Math.PI * Math.random();
  1306. if (node.xFixed == false) {node.x = radius * Math.cos(angle);}
  1307. if (node.yFixed == false) {node.y = radius * Math.sin(angle);}
  1308. }
  1309. this.moving = true;
  1310. }
  1311. this._updateNodeIndexList();
  1312. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  1313. this._resetLevels();
  1314. this._setupHierarchicalLayout();
  1315. }
  1316. this._updateCalculationNodes();
  1317. this._reconnectEdges();
  1318. this._updateValueRange(this.nodes);
  1319. this.updateLabels();
  1320. };
  1321. /**
  1322. * Update existing nodes, or create them when not yet existing
  1323. * @param {Number[] | String[]} ids
  1324. * @private
  1325. */
  1326. Network.prototype._updateNodes = function(ids) {
  1327. var nodes = this.nodes,
  1328. nodesData = this.nodesData;
  1329. for (var i = 0, len = ids.length; i < len; i++) {
  1330. var id = ids[i];
  1331. var node = nodes[id];
  1332. var data = nodesData.get(id);
  1333. if (node) {
  1334. // update node
  1335. node.setProperties(data, this.constants);
  1336. }
  1337. else {
  1338. // create node
  1339. node = new Node(properties, this.images, this.groups, this.constants);
  1340. nodes[id] = node;
  1341. }
  1342. }
  1343. this.moving = true;
  1344. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  1345. this._resetLevels();
  1346. this._setupHierarchicalLayout();
  1347. }
  1348. this._updateNodeIndexList();
  1349. this._reconnectEdges();
  1350. this._updateValueRange(nodes);
  1351. };
  1352. /**
  1353. * Remove existing nodes. If nodes do not exist, the method will just ignore it.
  1354. * @param {Number[] | String[]} ids
  1355. * @private
  1356. */
  1357. Network.prototype._removeNodes = function(ids) {
  1358. var nodes = this.nodes;
  1359. for (var i = 0, len = ids.length; i < len; i++) {
  1360. var id = ids[i];
  1361. delete nodes[id];
  1362. }
  1363. this._updateNodeIndexList();
  1364. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  1365. this._resetLevels();
  1366. this._setupHierarchicalLayout();
  1367. }
  1368. this._updateCalculationNodes();
  1369. this._reconnectEdges();
  1370. this._updateSelection();
  1371. this._updateValueRange(nodes);
  1372. };
  1373. /**
  1374. * Load edges by reading the data table
  1375. * @param {Array | DataSet | DataView} edges The data containing the edges.
  1376. * @private
  1377. * @private
  1378. */
  1379. Network.prototype._setEdges = function(edges) {
  1380. var oldEdgesData = this.edgesData;
  1381. if (edges instanceof DataSet || edges instanceof DataView) {
  1382. this.edgesData = edges;
  1383. }
  1384. else if (edges instanceof Array) {
  1385. this.edgesData = new DataSet();
  1386. this.edgesData.add(edges);
  1387. }
  1388. else if (!edges) {
  1389. this.edgesData = new DataSet();
  1390. }
  1391. else {
  1392. throw new TypeError('Array or DataSet expected');
  1393. }
  1394. if (oldEdgesData) {
  1395. // unsubscribe from old dataset
  1396. util.forEach(this.edgesListeners, function (callback, event) {
  1397. oldEdgesData.off(event, callback);
  1398. });
  1399. }
  1400. // remove drawn edges
  1401. this.edges = {};
  1402. if (this.edgesData) {
  1403. // subscribe to new dataset
  1404. var me = this;
  1405. util.forEach(this.edgesListeners, function (callback, event) {
  1406. me.edgesData.on(event, callback);
  1407. });
  1408. // draw all new nodes
  1409. var ids = this.edgesData.getIds();
  1410. this._addEdges(ids);
  1411. }
  1412. this._reconnectEdges();
  1413. };
  1414. /**
  1415. * Add edges
  1416. * @param {Number[] | String[]} ids
  1417. * @private
  1418. */
  1419. Network.prototype._addEdges = function (ids) {
  1420. var edges = this.edges,
  1421. edgesData = this.edgesData;
  1422. for (var i = 0, len = ids.length; i < len; i++) {
  1423. var id = ids[i];
  1424. var oldEdge = edges[id];
  1425. if (oldEdge) {
  1426. oldEdge.disconnect();
  1427. }
  1428. var data = edgesData.get(id, {"showInternalIds" : true});
  1429. edges[id] = new Edge(data, this, this.constants);
  1430. }
  1431. this.moving = true;
  1432. this._updateValueRange(edges);
  1433. this._createBezierNodes();
  1434. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  1435. this._resetLevels();
  1436. this._setupHierarchicalLayout();
  1437. }
  1438. this._updateCalculationNodes();
  1439. };
  1440. /**
  1441. * Update existing edges, or create them when not yet existing
  1442. * @param {Number[] | String[]} ids
  1443. * @private
  1444. */
  1445. Network.prototype._updateEdges = function (ids) {
  1446. var edges = this.edges,
  1447. edgesData = this.edgesData;
  1448. for (var i = 0, len = ids.length; i < len; i++) {
  1449. var id = ids[i];
  1450. var data = edgesData.get(id);
  1451. var edge = edges[id];
  1452. if (edge) {
  1453. // update edge
  1454. edge.disconnect();
  1455. edge.setProperties(data, this.constants);
  1456. edge.connect();
  1457. }
  1458. else {
  1459. // create edge
  1460. edge = new Edge(data, this, this.constants);
  1461. this.edges[id] = edge;
  1462. }
  1463. }
  1464. this._createBezierNodes();
  1465. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  1466. this._resetLevels();
  1467. this._setupHierarchicalLayout();
  1468. }
  1469. this.moving = true;
  1470. this._updateValueRange(edges);
  1471. };
  1472. /**
  1473. * Remove existing edges. Non existing ids will be ignored
  1474. * @param {Number[] | String[]} ids
  1475. * @private
  1476. */
  1477. Network.prototype._removeEdges = function (ids) {
  1478. var edges = this.edges;
  1479. for (var i = 0, len = ids.length; i < len; i++) {
  1480. var id = ids[i];
  1481. var edge = edges[id];
  1482. if (edge) {
  1483. if (edge.via != null) {
  1484. delete this.sectors['support']['nodes'][edge.via.id];
  1485. }
  1486. edge.disconnect();
  1487. delete edges[id];
  1488. }
  1489. }
  1490. this.moving = true;
  1491. this._updateValueRange(edges);
  1492. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  1493. this._resetLevels();
  1494. this._setupHierarchicalLayout();
  1495. }
  1496. this._updateCalculationNodes();
  1497. };
  1498. /**
  1499. * Reconnect all edges
  1500. * @private
  1501. */
  1502. Network.prototype._reconnectEdges = function() {
  1503. var id,
  1504. nodes = this.nodes,
  1505. edges = this.edges;
  1506. for (id in nodes) {
  1507. if (nodes.hasOwnProperty(id)) {
  1508. nodes[id].edges = [];
  1509. }
  1510. }
  1511. for (id in edges) {
  1512. if (edges.hasOwnProperty(id)) {
  1513. var edge = edges[id];
  1514. edge.from = null;
  1515. edge.to = null;
  1516. edge.connect();
  1517. }
  1518. }
  1519. };
  1520. /**
  1521. * Update the values of all object in the given array according to the current
  1522. * value range of the objects in the array.
  1523. * @param {Object} obj An object containing a set of Edges or Nodes
  1524. * The objects must have a method getValue() and
  1525. * setValueRange(min, max).
  1526. * @private
  1527. */
  1528. Network.prototype._updateValueRange = function(obj) {
  1529. var id;
  1530. // determine the range of the objects
  1531. var valueMin = undefined;
  1532. var valueMax = undefined;
  1533. for (id in obj) {
  1534. if (obj.hasOwnProperty(id)) {
  1535. var value = obj[id].getValue();
  1536. if (value !== undefined) {
  1537. valueMin = (valueMin === undefined) ? value : Math.min(value, valueMin);
  1538. valueMax = (valueMax === undefined) ? value : Math.max(value, valueMax);
  1539. }
  1540. }
  1541. }
  1542. // adjust the range of all objects
  1543. if (valueMin !== undefined && valueMax !== undefined) {
  1544. for (id in obj) {
  1545. if (obj.hasOwnProperty(id)) {
  1546. obj[id].setValueRange(valueMin, valueMax);
  1547. }
  1548. }
  1549. }
  1550. };
  1551. /**
  1552. * Redraw the network with the current data
  1553. * chart will be resized too.
  1554. */
  1555. Network.prototype.redraw = function() {
  1556. this.setSize(this.width, this.height);
  1557. this._redraw();
  1558. };
  1559. /**
  1560. * Redraw the network with the current data
  1561. * @private
  1562. */
  1563. Network.prototype._redraw = function() {
  1564. var ctx = this.frame.canvas.getContext('2d');
  1565. // clear the canvas
  1566. var w = this.frame.canvas.width;
  1567. var h = this.frame.canvas.height;
  1568. ctx.clearRect(0, 0, w, h);
  1569. // set scaling and translation
  1570. ctx.save();
  1571. ctx.translate(this.translation.x, this.translation.y);
  1572. ctx.scale(this.scale, this.scale);
  1573. this.canvasTopLeft = {
  1574. "x": this._XconvertDOMtoCanvas(0),
  1575. "y": this._YconvertDOMtoCanvas(0)
  1576. };
  1577. this.canvasBottomRight = {
  1578. "x": this._XconvertDOMtoCanvas(this.frame.canvas.clientWidth),
  1579. "y": this._YconvertDOMtoCanvas(this.frame.canvas.clientHeight)
  1580. };
  1581. this._doInAllSectors("_drawAllSectorNodes",ctx);
  1582. if (this.drag.dragging == false || this.drag.dragging === undefined || this.constants.hideEdgesOnDrag == false) {
  1583. this._doInAllSectors("_drawEdges",ctx);
  1584. }
  1585. if (this.drag.dragging == false || this.drag.dragging === undefined || this.constants.hideNodesOnDrag == false) {
  1586. this._doInAllSectors("_drawNodes",ctx,false);
  1587. }
  1588. if (this.controlNodesActive == true) {
  1589. this._doInAllSectors("_drawControlNodes",ctx);
  1590. }
  1591. // this._doInSupportSector("_drawNodes",ctx,true);
  1592. // this._drawTree(ctx,"#F00F0F");
  1593. // restore original scaling and translation
  1594. ctx.restore();
  1595. };
  1596. /**
  1597. * Set the translation of the network
  1598. * @param {Number} offsetX Horizontal offset
  1599. * @param {Number} offsetY Vertical offset
  1600. * @private
  1601. */
  1602. Network.prototype._setTranslation = function(offsetX, offsetY) {
  1603. if (this.translation === undefined) {
  1604. this.translation = {
  1605. x: 0,
  1606. y: 0
  1607. };
  1608. }
  1609. if (offsetX !== undefined) {
  1610. this.translation.x = offsetX;
  1611. }
  1612. if (offsetY !== undefined) {
  1613. this.translation.y = offsetY;
  1614. }
  1615. this.emit('viewChanged');
  1616. };
  1617. /**
  1618. * Get the translation of the network
  1619. * @return {Object} translation An object with parameters x and y, both a number
  1620. * @private
  1621. */
  1622. Network.prototype._getTranslation = function() {
  1623. return {
  1624. x: this.translation.x,
  1625. y: this.translation.y
  1626. };
  1627. };
  1628. /**
  1629. * Scale the network
  1630. * @param {Number} scale Scaling factor 1.0 is unscaled
  1631. * @private
  1632. */
  1633. Network.prototype._setScale = function(scale) {
  1634. this.scale = scale;
  1635. };
  1636. /**
  1637. * Get the current scale of the network
  1638. * @return {Number} scale Scaling factor 1.0 is unscaled
  1639. * @private
  1640. */
  1641. Network.prototype._getScale = function() {
  1642. return this.scale;
  1643. };
  1644. /**
  1645. * Convert the X coordinate in DOM-space (coordinate point in browser relative to the container div) to
  1646. * the X coordinate in canvas-space (the simulation sandbox, which the camera looks upon)
  1647. * @param {number} x
  1648. * @returns {number}
  1649. * @private
  1650. */
  1651. Network.prototype._XconvertDOMtoCanvas = function(x) {
  1652. return (x - this.translation.x) / this.scale;
  1653. };
  1654. /**
  1655. * Convert the X coordinate in canvas-space (the simulation sandbox, which the camera looks upon) to
  1656. * the X coordinate in DOM-space (coordinate point in browser relative to the container div)
  1657. * @param {number} x
  1658. * @returns {number}
  1659. * @private
  1660. */
  1661. Network.prototype._XconvertCanvasToDOM = function(x) {
  1662. return x * this.scale + this.translation.x;
  1663. };
  1664. /**
  1665. * Convert the Y coordinate in DOM-space (coordinate point in browser relative to the container div) to
  1666. * the Y coordinate in canvas-space (the simulation sandbox, which the camera looks upon)
  1667. * @param {number} y
  1668. * @returns {number}
  1669. * @private
  1670. */
  1671. Network.prototype._YconvertDOMtoCanvas = function(y) {
  1672. return (y - this.translation.y) / this.scale;
  1673. };
  1674. /**
  1675. * Convert the Y coordinate in canvas-space (the simulation sandbox, which the camera looks upon) to
  1676. * the Y coordinate in DOM-space (coordinate point in browser relative to the container div)
  1677. * @param {number} y
  1678. * @returns {number}
  1679. * @private
  1680. */
  1681. Network.prototype._YconvertCanvasToDOM = function(y) {
  1682. return y * this.scale + this.translation.y ;
  1683. };
  1684. /**
  1685. *
  1686. * @param {object} pos = {x: number, y: number}
  1687. * @returns {{x: number, y: number}}
  1688. * @constructor
  1689. */
  1690. Network.prototype.canvasToDOM = function(pos) {
  1691. return {x:this._XconvertCanvasToDOM(pos.x),y:this._YconvertCanvasToDOM(pos.y)};
  1692. }
  1693. /**
  1694. *
  1695. * @param {object} pos = {x: number, y: number}
  1696. * @returns {{x: number, y: number}}
  1697. * @constructor
  1698. */
  1699. Network.prototype.DOMtoCanvas = function(pos) {
  1700. return {x:this._XconvertDOMtoCanvas(pos.x),y:this._YconvertDOMtoCanvas(pos.y)};
  1701. }
  1702. /**
  1703. * Redraw all nodes
  1704. * The 2d context of a HTML canvas can be retrieved by canvas.getContext('2d');
  1705. * @param {CanvasRenderingContext2D} ctx
  1706. * @param {Boolean} [alwaysShow]
  1707. * @private
  1708. */
  1709. Network.prototype._drawNodes = function(ctx,alwaysShow) {
  1710. if (alwaysShow === undefined) {
  1711. alwaysShow = false;
  1712. }
  1713. // first draw the unselected nodes
  1714. var nodes = this.nodes;
  1715. var selected = [];
  1716. for (var id in nodes) {
  1717. if (nodes.hasOwnProperty(id)) {
  1718. nodes[id].setScaleAndPos(this.scale,this.canvasTopLeft,this.canvasBottomRight);
  1719. if (nodes[id].isSelected()) {
  1720. selected.push(id);
  1721. }
  1722. else {
  1723. if (nodes[id].inArea() || alwaysShow) {
  1724. nodes[id].draw(ctx);
  1725. }
  1726. }
  1727. }
  1728. }
  1729. // draw the selected nodes on top
  1730. for (var s = 0, sMax = selected.length; s < sMax; s++) {
  1731. if (nodes[selected[s]].inArea() || alwaysShow) {
  1732. nodes[selected[s]].draw(ctx);
  1733. }
  1734. }
  1735. };
  1736. /**
  1737. * Redraw all edges
  1738. * The 2d context of a HTML canvas can be retrieved by canvas.getContext('2d');
  1739. * @param {CanvasRenderingContext2D} ctx
  1740. * @private
  1741. */
  1742. Network.prototype._drawEdges = function(ctx) {
  1743. var edges = this.edges;
  1744. for (var id in edges) {
  1745. if (edges.hasOwnProperty(id)) {
  1746. var edge = edges[id];
  1747. edge.setScale(this.scale);
  1748. if (edge.connected) {
  1749. edges[id].draw(ctx);
  1750. }
  1751. }
  1752. }
  1753. };
  1754. /**
  1755. * Redraw all edges
  1756. * The 2d context of a HTML canvas can be retrieved by canvas.getContext('2d');
  1757. * @param {CanvasRenderingContext2D} ctx
  1758. * @private
  1759. */
  1760. Network.prototype._drawControlNodes = function(ctx) {
  1761. var edges = this.edges;
  1762. for (var id in edges) {
  1763. if (edges.hasOwnProperty(id)) {
  1764. edges[id]._drawControlNodes(ctx);
  1765. }
  1766. }
  1767. };
  1768. /**
  1769. * Find a stable position for all nodes
  1770. * @private
  1771. */
  1772. Network.prototype._stabilize = function() {
  1773. if (this.constants.freezeForStabilization == true) {
  1774. this._freezeDefinedNodes();
  1775. }
  1776. // find stable position
  1777. var count = 0;
  1778. while (this.moving && count < this.constants.stabilizationIterations) {
  1779. this._physicsTick();
  1780. count++;
  1781. }
  1782. this.zoomExtent(false,true);
  1783. if (this.constants.freezeForStabilization == true) {
  1784. this._restoreFrozenNodes();
  1785. }
  1786. this.emit("stabilized",{iterations:count});
  1787. };
  1788. /**
  1789. * When initializing and stabilizing, we can freeze nodes with a predefined position. This greatly speeds up stabilization
  1790. * because only the supportnodes for the smoothCurves have to settle.
  1791. *
  1792. * @private
  1793. */
  1794. Network.prototype._freezeDefinedNodes = function() {
  1795. var nodes = this.nodes;
  1796. for (var id in nodes) {
  1797. if (nodes.hasOwnProperty(id)) {
  1798. if (nodes[id].x != null && nodes[id].y != null) {
  1799. nodes[id].fixedData.x = nodes[id].xFixed;
  1800. nodes[id].fixedData.y = nodes[id].yFixed;
  1801. nodes[id].xFixed = true;
  1802. nodes[id].yFixed = true;
  1803. }
  1804. }
  1805. }
  1806. };
  1807. /**
  1808. * Unfreezes the nodes that have been frozen by _freezeDefinedNodes.
  1809. *
  1810. * @private
  1811. */
  1812. Network.prototype._restoreFrozenNodes = function() {
  1813. var nodes = this.nodes;
  1814. for (var id in nodes) {
  1815. if (nodes.hasOwnProperty(id)) {
  1816. if (nodes[id].fixedData.x != null) {
  1817. nodes[id].xFixed = nodes[id].fixedData.x;
  1818. nodes[id].yFixed = nodes[id].fixedData.y;
  1819. }
  1820. }
  1821. }
  1822. };
  1823. /**
  1824. * Check if any of the nodes is still moving
  1825. * @param {number} vmin the minimum velocity considered as 'moving'
  1826. * @return {boolean} true if moving, false if non of the nodes is moving
  1827. * @private
  1828. */
  1829. Network.prototype._isMoving = function(vmin) {
  1830. var nodes = this.nodes;
  1831. for (var id in nodes) {
  1832. if (nodes.hasOwnProperty(id) && nodes[id].isMoving(vmin)) {
  1833. return true;
  1834. }
  1835. }
  1836. return false;
  1837. };
  1838. /**
  1839. * /**
  1840. * Perform one discrete step for all nodes
  1841. *
  1842. * @private
  1843. */
  1844. Network.prototype._discreteStepNodes = function() {
  1845. var interval = this.physicsDiscreteStepsize;
  1846. var nodes = this.nodes;
  1847. var nodeId;
  1848. var nodesPresent = false;
  1849. if (this.constants.maxVelocity > 0) {
  1850. for (nodeId in nodes) {
  1851. if (nodes.hasOwnProperty(nodeId)) {
  1852. nodes[nodeId].discreteStepLimited(interval, this.constants.maxVelocity);
  1853. nodesPresent = true;
  1854. }
  1855. }
  1856. }
  1857. else {
  1858. for (nodeId in nodes) {
  1859. if (nodes.hasOwnProperty(nodeId)) {
  1860. nodes[nodeId].discreteStep(interval);
  1861. nodesPresent = true;
  1862. }
  1863. }
  1864. }
  1865. if (nodesPresent == true) {
  1866. var vminCorrected = this.constants.minVelocity / Math.max(this.scale,0.05);
  1867. if (vminCorrected > 0.5*this.constants.maxVelocity) {
  1868. this.moving = true;
  1869. }
  1870. else {
  1871. this.moving = this._isMoving(vminCorrected);
  1872. if (this.moving == false) {
  1873. this.emit("stabilized",{iterations:null});
  1874. }
  1875. this.moving = this.moving || this.configurePhysics;
  1876. }
  1877. }
  1878. };
  1879. /**
  1880. * A single simulation step (or "tick") in the physics simulation
  1881. *
  1882. * @private
  1883. */
  1884. Network.prototype._physicsTick = function() {
  1885. if (!this.freezeSimulation) {
  1886. if (this.moving) {
  1887. this._doInAllActiveSectors("_initializeForceCalculation");
  1888. this._doInAllActiveSectors("_discreteStepNodes");
  1889. if (this.constants.smoothCurves) {
  1890. this._doInSupportSector("_discreteStepNodes");
  1891. }
  1892. this._findCenter(this._getRange())
  1893. }
  1894. }
  1895. };
  1896. /**
  1897. * This function runs one step of the animation. It calls an x amount of physics ticks and one render tick.
  1898. * It reschedules itself at the beginning of the function
  1899. *
  1900. * @private
  1901. */
  1902. Network.prototype._animationStep = function() {
  1903. // reset the timer so a new scheduled animation step can be set
  1904. this.timer = undefined;
  1905. // handle the keyboad movement
  1906. this._handleNavigation();
  1907. // this schedules a new animation step
  1908. this.start();
  1909. // start the physics simulation
  1910. var calculationTime = Date.now();
  1911. var maxSteps = 1;
  1912. this._physicsTick();
  1913. var timeRequired = Date.now() - calculationTime;
  1914. while (timeRequired < 0.9*(this.renderTimestep - this.renderTime) && maxSteps < this.maxPhysicsTicksPerRender) {
  1915. this._physicsTick();
  1916. timeRequired = Date.now() - calculationTime;
  1917. maxSteps++;
  1918. }
  1919. // start the rendering process
  1920. var renderTime = Date.now();
  1921. this._redraw();
  1922. this.renderTime = Date.now() - renderTime;
  1923. };
  1924. if (typeof window !== 'undefined') {
  1925. window.requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame ||
  1926. window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;
  1927. }
  1928. /**
  1929. * Schedule a animation step with the refreshrate interval.
  1930. */
  1931. Network.prototype.start = function() {
  1932. if (this.moving || this.xIncrement != 0 || this.yIncrement != 0 || this.zoomIncrement != 0) {
  1933. if (!this.timer) {
  1934. var ua = navigator.userAgent.toLowerCase();
  1935. var requiresTimeout = false;
  1936. if (ua.indexOf('msie 9.0') != -1) { // IE 9
  1937. requiresTimeout = true;
  1938. }
  1939. else if (ua.indexOf('safari') != -1) { // safari
  1940. if (ua.indexOf('chrome') <= -1) {
  1941. requiresTimeout = true;
  1942. }
  1943. }
  1944. if (requiresTimeout == true) {
  1945. this.timer = window.setTimeout(this._animationStep.bind(this), this.renderTimestep); // wait this.renderTimeStep milliseconds and perform the animation step function
  1946. }
  1947. else{
  1948. this.timer = window.requestAnimationFrame(this._animationStep.bind(this), this.renderTimestep); // wait this.renderTimeStep milliseconds and perform the animation step function
  1949. }
  1950. }
  1951. }
  1952. else {
  1953. this._redraw();
  1954. }
  1955. };
  1956. /**
  1957. * Move the network according to the keyboard presses.
  1958. *
  1959. * @private
  1960. */
  1961. Network.prototype._handleNavigation = function() {
  1962. if (this.xIncrement != 0 || this.yIncrement != 0) {
  1963. var translation = this._getTranslation();
  1964. this._setTranslation(translation.x+this.xIncrement, translation.y+this.yIncrement);
  1965. }
  1966. if (this.zoomIncrement != 0) {
  1967. var center = {
  1968. x: this.frame.canvas.clientWidth / 2,
  1969. y: this.frame.canvas.clientHeight / 2
  1970. };
  1971. this._zoom(this.scale*(1 + this.zoomIncrement), center);
  1972. }
  1973. };
  1974. /**
  1975. * Freeze the _animationStep
  1976. */
  1977. Network.prototype.toggleFreeze = function() {
  1978. if (this.freezeSimulation == false) {
  1979. this.freezeSimulation = true;
  1980. }
  1981. else {
  1982. this.freezeSimulation = false;
  1983. this.start();
  1984. }
  1985. };
  1986. /**
  1987. * This function cleans the support nodes if they are not needed and adds them when they are.
  1988. *
  1989. * @param {boolean} [disableStart]
  1990. * @private
  1991. */
  1992. Network.prototype._configureSmoothCurves = function(disableStart) {
  1993. if (disableStart === undefined) {
  1994. disableStart = true;
  1995. }
  1996. if (this.constants.smoothCurves.enabled == true && this.constants.smoothCurves.dynamic == true) {
  1997. this._createBezierNodes();
  1998. // cleanup unused support nodes
  1999. for (var nodeId in this.sectors['support']['nodes']) {
  2000. if (this.sectors['support']['nodes'].hasOwnProperty(nodeId)) {
  2001. if (this.edges[this.sectors['support']['nodes'][nodeId]] === undefined) {
  2002. delete this.sectors['support']['nodes'][nodeId];
  2003. }
  2004. }
  2005. }
  2006. }
  2007. else {
  2008. // delete the support nodes
  2009. this.sectors['support']['nodes'] = {};
  2010. for (var edgeId in this.edges) {
  2011. if (this.edges.hasOwnProperty(edgeId)) {
  2012. this.edges[edgeId].smooth = false;
  2013. this.edges[edgeId].via = null;
  2014. }
  2015. }
  2016. }
  2017. this._updateCalculationNodes();
  2018. if (!disableStart) {
  2019. this.moving = true;
  2020. this.start();
  2021. }
  2022. };
  2023. /**
  2024. * Bezier curves require an anchor point to calculate the smooth flow. These points are nodes. These nodes are invisible but
  2025. * are used for the force calculation.
  2026. *
  2027. * @private
  2028. */
  2029. Network.prototype._createBezierNodes = function() {
  2030. if (this.constants.smoothCurves.enabled == true && this.constants.smoothCurves.dynamic == true) {
  2031. for (var edgeId in this.edges) {
  2032. if (this.edges.hasOwnProperty(edgeId)) {
  2033. var edge = this.edges[edgeId];
  2034. if (edge.via == null) {
  2035. edge.smooth = true;
  2036. var nodeId = "edgeId:".concat(edge.id);
  2037. this.sectors['support']['nodes'][nodeId] = new Node(
  2038. {id:nodeId,
  2039. mass:1,
  2040. shape:'circle',
  2041. image:"",
  2042. internalMultiplier:1
  2043. },{},{},this.constants);
  2044. edge.via = this.sectors['support']['nodes'][nodeId];
  2045. edge.via.parentEdgeId = edge.id;
  2046. edge.positionBezierNode();
  2047. }
  2048. }
  2049. }
  2050. }
  2051. };
  2052. /**
  2053. * load the functions that load the mixins into the prototype.
  2054. *
  2055. * @private
  2056. */
  2057. Network.prototype._initializeMixinLoaders = function () {
  2058. for (var mixin in MixinLoader) {
  2059. if (MixinLoader.hasOwnProperty(mixin)) {
  2060. Network.prototype[mixin] = MixinLoader[mixin];
  2061. }
  2062. }
  2063. };
  2064. /**
  2065. * Load the XY positions of the nodes into the dataset.
  2066. */
  2067. Network.prototype.storePosition = function() {
  2068. var dataArray = [];
  2069. for (var nodeId in this.nodes) {
  2070. if (this.nodes.hasOwnProperty(nodeId)) {
  2071. var node = this.nodes[nodeId];
  2072. var allowedToMoveX = !this.nodes.xFixed;
  2073. var allowedToMoveY = !this.nodes.yFixed;
  2074. if (this.nodesData._data[nodeId].x != Math.round(node.x) || this.nodesData._data[nodeId].y != Math.round(node.y)) {
  2075. dataArray.push({id:nodeId,x:Math.round(node.x),y:Math.round(node.y),allowedToMoveX:allowedToMoveX,allowedToMoveY:allowedToMoveY});
  2076. }
  2077. }
  2078. }
  2079. this.nodesData.update(dataArray);
  2080. };
  2081. /**
  2082. * Center a node in view.
  2083. *
  2084. * @param {Number} nodeId
  2085. * @param {Number} [zoomLevel]
  2086. */
  2087. Network.prototype.focusOnNode = function (nodeId, zoomLevel) {
  2088. if (this.nodes.hasOwnProperty(nodeId)) {
  2089. if (zoomLevel === undefined) {
  2090. zoomLevel = this._getScale();
  2091. }
  2092. var nodePosition= {x: this.nodes[nodeId].x, y: this.nodes[nodeId].y};
  2093. var requiredScale = zoomLevel;
  2094. this._setScale(requiredScale);
  2095. var canvasCenter = this.DOMtoCanvas({x:0.5 * this.frame.canvas.width,y:0.5 * this.frame.canvas.height});
  2096. var translation = this._getTranslation();
  2097. var distanceFromCenter = {x:canvasCenter.x - nodePosition.x,
  2098. y:canvasCenter.y - nodePosition.y};
  2099. this._setTranslation(translation.x + requiredScale * distanceFromCenter.x,
  2100. translation.y + requiredScale * distanceFromCenter.y);
  2101. this.redraw();
  2102. }
  2103. else {
  2104. console.log("This nodeId cannot be found.")
  2105. }
  2106. };
  2107. module.exports = Network;