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.

2248 lines
66 KiB

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