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.

2376 lines
70 KiB

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