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.

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