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.

2358 lines
69 KiB

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