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.

2299 lines
67 KiB

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