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.

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