vis.js is a dynamic, browser-based visualization library

2271 lines
66 KiB

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