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.

2272 lines
66 KiB

10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
  1. var Emitter = require('emitter-component');
  2. var Hammer = require('../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. layout: "hubsize" // hubsize, directed
  173. },
  174. freezeForStabilization: false,
  175. smoothCurves: {
  176. enabled: true,
  177. dynamic: true,
  178. type: "continuous",
  179. roundness: 0.5
  180. },
  181. dynamicSmoothCurves: true,
  182. maxVelocity: 30,
  183. minVelocity: 0.1, // px/s
  184. stabilize: true, // stabilize before displaying the network
  185. stabilizationIterations: 1000, // maximum number of iteration to stabilize
  186. locale: 'en',
  187. locales: locales,
  188. tooltip: {
  189. delay: 300,
  190. fontColor: 'black',
  191. fontSize: 14, // px
  192. fontFace: 'verdana',
  193. color: {
  194. border: '#666',
  195. background: '#FFFFC6'
  196. }
  197. },
  198. dragNetwork: true,
  199. dragNodes: true,
  200. zoomable: true,
  201. hover: false,
  202. hideEdgesOnDrag: false,
  203. hideNodesOnDrag: false,
  204. width : '100%',
  205. height : '100%',
  206. selectable: true
  207. };
  208. this.constants = util.extend({}, this.defaultOptions);
  209. this.hoverObj = {nodes:{},edges:{}};
  210. this.controlNodesActive = false;
  211. // Node variables
  212. var network = this;
  213. this.groups = new Groups(); // object with groups
  214. this.images = new Images(); // object with images
  215. this.images.setOnloadCallback(function () {
  216. network._redraw();
  217. });
  218. // keyboard navigation variables
  219. this.xIncrement = 0;
  220. this.yIncrement = 0;
  221. this.zoomIncrement = 0;
  222. // loading all the mixins:
  223. // load the force calculation functions, grouped under the physics system.
  224. this._loadPhysicsSystem();
  225. // create a frame and canvas
  226. this._create();
  227. // load the sector system. (mandatory, fully integrated with Network)
  228. this._loadSectorSystem();
  229. // load the cluster system. (mandatory, even when not using the cluster system, there are function calls to it)
  230. this._loadClusterSystem();
  231. // load the selection system. (mandatory, required by Network)
  232. this._loadSelectionSystem();
  233. // load the selection system. (mandatory, required by Network)
  234. this._loadHierarchySystem();
  235. // apply options
  236. this._setTranslation(this.frame.clientWidth / 2, this.frame.clientHeight / 2);
  237. this._setScale(1);
  238. this.setOptions(options);
  239. // other vars
  240. this.freezeSimulation = false;// freeze the simulation
  241. this.cachedFunctions = {};
  242. this.stabilized = false;
  243. this.stabilizationIterations = null;
  244. // containers for nodes and edges
  245. this.calculationNodes = {};
  246. this.calculationNodeIndices = [];
  247. this.nodeIndices = []; // array with all the indices of the nodes. Used to speed up forces calculation
  248. this.nodes = {}; // object with Node objects
  249. this.edges = {}; // object with Edge objects
  250. // position and scale variables and objects
  251. this.canvasTopLeft = {"x": 0,"y": 0}; // coordinates of the top left of the canvas. they will be set during _redraw.
  252. this.canvasBottomRight = {"x": 0,"y": 0}; // coordinates of the bottom right of the canvas. they will be set during _redraw
  253. this.pointerPosition = {"x": 0,"y": 0}; // coordinates of the bottom right of the canvas. they will be set during _redraw
  254. this.areaCenter = {}; // object with x and y elements used for determining the center of the zoom action
  255. this.scale = 1; // defining the global scale variable in the constructor
  256. this.previousScale = this.scale; // this is used to check if the zoom operation is zooming in or out
  257. // datasets or dataviews
  258. this.nodesData = null; // A DataSet or DataView
  259. this.edgesData = null; // A DataSet or DataView
  260. // create event listeners used to subscribe on the DataSets of the nodes and edges
  261. this.nodesListeners = {
  262. 'add': function (event, params) {
  263. network._addNodes(params.items);
  264. network.start();
  265. },
  266. 'update': function (event, params) {
  267. network._updateNodes(params.items);
  268. network.start();
  269. },
  270. 'remove': function (event, params) {
  271. network._removeNodes(params.items);
  272. network.start();
  273. }
  274. };
  275. this.edgesListeners = {
  276. 'add': function (event, params) {
  277. network._addEdges(params.items);
  278. network.start();
  279. },
  280. 'update': function (event, params) {
  281. network._updateEdges(params.items);
  282. network.start();
  283. },
  284. 'remove': function (event, params) {
  285. network._removeEdges(params.items);
  286. network.start();
  287. }
  288. };
  289. // properties for the animation
  290. this.moving = true;
  291. this.timer = undefined; // Scheduling function. Is definded in this.start();
  292. // load data (the disable start variable will be the same as the enabled clustering)
  293. this.setData(data,this.constants.clustering.enabled || this.constants.hierarchicalLayout.enabled);
  294. // hierarchical layout
  295. this.initializing = false;
  296. if (this.constants.hierarchicalLayout.enabled == true) {
  297. this._setupHierarchicalLayout();
  298. }
  299. else {
  300. // zoom so all data will fit on the screen, if clustering is enabled, we do not want start to be called here.
  301. if (this.constants.stabilize == false) {
  302. this.zoomExtent(true,this.constants.clustering.enabled);
  303. }
  304. }
  305. // if clustering is disabled, the simulation will have started in the setData function
  306. if (this.constants.clustering.enabled) {
  307. this.startWithClustering();
  308. }
  309. }
  310. // Extend Network with an Emitter mixin
  311. Emitter(Network.prototype);
  312. /**
  313. * Get the script path where the vis.js library is located
  314. *
  315. * @returns {string | null} path Path or null when not found. Path does not
  316. * end with a slash.
  317. * @private
  318. */
  319. Network.prototype._getScriptPath = function() {
  320. var scripts = document.getElementsByTagName( 'script' );
  321. // find script named vis.js or vis.min.js
  322. for (var i = 0; i < scripts.length; i++) {
  323. var src = scripts[i].src;
  324. var match = src && /\/?vis(.min)?\.js$/.exec(src);
  325. if (match) {
  326. // return path without the script name
  327. return src.substring(0, src.length - match[0].length);
  328. }
  329. }
  330. return null;
  331. };
  332. /**
  333. * Find the center position of the network
  334. * @private
  335. */
  336. Network.prototype._getRange = function() {
  337. var minY = 1e9, maxY = -1e9, minX = 1e9, maxX = -1e9, node;
  338. for (var nodeId in this.nodes) {
  339. if (this.nodes.hasOwnProperty(nodeId)) {
  340. node = this.nodes[nodeId];
  341. if (minX > (node.x)) {minX = node.x;}
  342. if (maxX < (node.x)) {maxX = node.x;}
  343. if (minY > (node.y)) {minY = node.y;}
  344. if (maxY < (node.y)) {maxY = node.y;}
  345. }
  346. }
  347. if (minX == 1e9 && maxX == -1e9 && minY == 1e9 && maxY == -1e9) {
  348. minY = 0, maxY = 0, minX = 0, maxX = 0;
  349. }
  350. return {minX: minX, maxX: maxX, minY: minY, maxY: maxY};
  351. };
  352. /**
  353. * @param {object} range = {minX: minX, maxX: maxX, minY: minY, maxY: maxY};
  354. * @returns {{x: number, y: number}}
  355. * @private
  356. */
  357. Network.prototype._findCenter = function(range) {
  358. return {x: (0.5 * (range.maxX + range.minX)),
  359. y: (0.5 * (range.maxY + range.minY))};
  360. };
  361. /**
  362. * center the network
  363. *
  364. * @param {object} range = {minX: minX, maxX: maxX, minY: minY, maxY: maxY};
  365. */
  366. Network.prototype._centerNetwork = function(range) {
  367. var center = this._findCenter(range);
  368. center.x *= this.scale;
  369. center.y *= this.scale;
  370. center.x -= 0.5 * this.frame.canvas.clientWidth;
  371. center.y -= 0.5 * this.frame.canvas.clientHeight;
  372. this._setTranslation(-center.x,-center.y); // set at 0,0
  373. };
  374. /**
  375. * This function zooms out to fit all data on screen based on amount of nodes
  376. *
  377. * @param {Boolean} [initialZoom] | zoom based on fitted formula or range, true = fitted, default = false;
  378. * @param {Boolean} [disableStart] | If true, start is not called.
  379. */
  380. Network.prototype.zoomExtent = function(initialZoom, disableStart) {
  381. if (initialZoom === undefined) {
  382. initialZoom = false;
  383. }
  384. if (disableStart === undefined) {
  385. disableStart = false;
  386. }
  387. var range = this._getRange();
  388. var zoomLevel;
  389. if (initialZoom == true) {
  390. var numberOfNodes = this.nodeIndices.length;
  391. if (this.constants.smoothCurves == true) {
  392. if (this.constants.clustering.enabled == true &&
  393. numberOfNodes >= this.constants.clustering.initialMaxNodes) {
  394. 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.
  395. }
  396. else {
  397. zoomLevel = 12.662 / (numberOfNodes + 7.4147) + 0.0964822; // this is obtained from fitting a dataset from 5 points with scale levels that looked good.
  398. }
  399. }
  400. else {
  401. if (this.constants.clustering.enabled == true &&
  402. numberOfNodes >= this.constants.clustering.initialMaxNodes) {
  403. 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.
  404. }
  405. else {
  406. zoomLevel = 30.5062972 / (numberOfNodes + 19.93597763) + 0.08413486; // this is obtained from fitting a dataset from 5 points with scale levels that looked good.
  407. }
  408. }
  409. // correct for larger canvasses.
  410. var factor = Math.min(this.frame.canvas.clientWidth / 600, this.frame.canvas.clientHeight / 600);
  411. zoomLevel *= factor;
  412. }
  413. else {
  414. var xDistance = (Math.abs(range.minX) + Math.abs(range.maxX)) * 1.1;
  415. var yDistance = (Math.abs(range.minY) + Math.abs(range.maxY)) * 1.1;
  416. var xZoomLevel = this.frame.canvas.clientWidth / xDistance;
  417. var yZoomLevel = this.frame.canvas.clientHeight / yDistance;
  418. zoomLevel = (xZoomLevel <= yZoomLevel) ? xZoomLevel : yZoomLevel;
  419. }
  420. if (zoomLevel > 1.0) {
  421. zoomLevel = 1.0;
  422. }
  423. this._setScale(zoomLevel);
  424. this._centerNetwork(range);
  425. if (disableStart == false) {
  426. this.moving = true;
  427. this.start();
  428. }
  429. };
  430. /**
  431. * Update the this.nodeIndices with the most recent node index list
  432. * @private
  433. */
  434. Network.prototype._updateNodeIndexList = function() {
  435. this._clearNodeIndexList();
  436. for (var idx in this.nodes) {
  437. if (this.nodes.hasOwnProperty(idx)) {
  438. this.nodeIndices.push(idx);
  439. }
  440. }
  441. };
  442. /**
  443. * Set nodes and edges, and optionally options as well.
  444. *
  445. * @param {Object} data Object containing parameters:
  446. * {Array | DataSet | DataView} [nodes] Array with nodes
  447. * {Array | DataSet | DataView} [edges] Array with edges
  448. * {String} [dot] String containing data in DOT format
  449. * {String} [gephi] String containing data in gephi JSON format
  450. * {Options} [options] Object with options
  451. * @param {Boolean} [disableStart] | optional: disable the calling of the start function.
  452. */
  453. Network.prototype.setData = function(data, disableStart) {
  454. if (disableStart === undefined) {
  455. disableStart = false;
  456. }
  457. // we set initializing to true to ensure that the hierarchical layout is not performed until both nodes and edges are added.
  458. this.initializing = true;
  459. if (data && data.dot && (data.nodes || data.edges)) {
  460. throw new SyntaxError('Data must contain either parameter "dot" or ' +
  461. ' parameter pair "nodes" and "edges", but not both.');
  462. }
  463. // set options
  464. this.setOptions(data && data.options);
  465. // set all data
  466. if (data && data.dot) {
  467. // parse DOT file
  468. if(data && data.dot) {
  469. var dotData = dotparser.DOTToGraph(data.dot);
  470. this.setData(dotData);
  471. return;
  472. }
  473. }
  474. else if (data && data.gephi) {
  475. // parse DOT file
  476. if(data && data.gephi) {
  477. var gephiData = gephiParser.parseGephi(data.gephi);
  478. this.setData(gephiData);
  479. return;
  480. }
  481. }
  482. else {
  483. this._setNodes(data && data.nodes);
  484. this._setEdges(data && data.edges);
  485. }
  486. this._putDataInSector();
  487. if (disableStart == false) {
  488. if (this.constants.hierarchicalLayout.enabled == true) {
  489. this._resetLevels();
  490. this._setupHierarchicalLayout();
  491. }
  492. else {
  493. // find a stable position or start animating to a stable position
  494. if (this.constants.stabilize) {
  495. this._stabilize();
  496. }
  497. }
  498. this.start();
  499. }
  500. this.initializing = false;
  501. };
  502. /**
  503. * Set options
  504. * @param {Object} options
  505. */
  506. Network.prototype.setOptions = function (options) {
  507. if (options) {
  508. var prop;
  509. var fields = ['nodes','edges','smoothCurves','hierarchicalLayout','clustering','navigation','keyboard','dataManipulation',
  510. 'onAdd','onEdit','onEditEdge','onConnect','onDelete','clickToUse'
  511. ];
  512. util.selectiveNotDeepExtend(fields,this.constants, options);
  513. util.selectiveNotDeepExtend(['color'],this.constants.nodes, options.nodes);
  514. util.selectiveNotDeepExtend(['color','length'],this.constants.edges, options.edges);
  515. if (options.physics) {
  516. util.mergeOptions(this.constants.physics, options.physics,'barnesHut');
  517. util.mergeOptions(this.constants.physics, options.physics,'repulsion');
  518. if (options.physics.hierarchicalRepulsion) {
  519. this.constants.hierarchicalLayout.enabled = true;
  520. this.constants.physics.hierarchicalRepulsion.enabled = true;
  521. this.constants.physics.barnesHut.enabled = false;
  522. for (prop in options.physics.hierarchicalRepulsion) {
  523. if (options.physics.hierarchicalRepulsion.hasOwnProperty(prop)) {
  524. this.constants.physics.hierarchicalRepulsion[prop] = options.physics.hierarchicalRepulsion[prop];
  525. }
  526. }
  527. }
  528. }
  529. if (options.onAdd) {this.triggerFunctions.add = options.onAdd;}
  530. if (options.onEdit) {this.triggerFunctions.edit = options.onEdit;}
  531. if (options.onEditEdge) {this.triggerFunctions.editEdge = options.onEditEdge;}
  532. if (options.onConnect) {this.triggerFunctions.connect = options.onConnect;}
  533. if (options.onDelete) {this.triggerFunctions.del = options.onDelete;}
  534. util.mergeOptions(this.constants, options,'smoothCurves');
  535. util.mergeOptions(this.constants, options,'hierarchicalLayout');
  536. util.mergeOptions(this.constants, options,'clustering');
  537. util.mergeOptions(this.constants, options,'navigation');
  538. util.mergeOptions(this.constants, options,'keyboard');
  539. util.mergeOptions(this.constants, options,'dataManipulation');
  540. if (options.dataManipulation) {
  541. this.editMode = this.constants.dataManipulation.initiallyVisible;
  542. }
  543. // TODO: work out these options and document them
  544. if (options.edges) {
  545. if (options.edges.color !== undefined) {
  546. if (util.isString(options.edges.color)) {
  547. this.constants.edges.color = {};
  548. this.constants.edges.color.color = options.edges.color;
  549. this.constants.edges.color.highlight = options.edges.color;
  550. this.constants.edges.color.hover = options.edges.color;
  551. }
  552. else {
  553. if (options.edges.color.color !== undefined) {this.constants.edges.color.color = options.edges.color.color;}
  554. if (options.edges.color.highlight !== undefined) {this.constants.edges.color.highlight = options.edges.color.highlight;}
  555. if (options.edges.color.hover !== undefined) {this.constants.edges.color.hover = options.edges.color.hover;}
  556. }
  557. }
  558. if (!options.edges.fontColor) {
  559. if (options.edges.color !== undefined) {
  560. if (util.isString(options.edges.color)) {this.constants.edges.fontColor = options.edges.color;}
  561. else if (options.edges.color.color !== undefined) {this.constants.edges.fontColor = options.edges.color.color;}
  562. }
  563. }
  564. }
  565. if (options.nodes) {
  566. if (options.nodes.color) {
  567. var newColorObj = util.parseColor(options.nodes.color);
  568. this.constants.nodes.color.background = newColorObj.background;
  569. this.constants.nodes.color.border = newColorObj.border;
  570. this.constants.nodes.color.highlight.background = newColorObj.highlight.background;
  571. this.constants.nodes.color.highlight.border = newColorObj.highlight.border;
  572. this.constants.nodes.color.hover.background = newColorObj.hover.background;
  573. this.constants.nodes.color.hover.border = newColorObj.hover.border;
  574. }
  575. }
  576. if (options.groups) {
  577. for (var groupname in options.groups) {
  578. if (options.groups.hasOwnProperty(groupname)) {
  579. var group = options.groups[groupname];
  580. this.groups.add(groupname, group);
  581. }
  582. }
  583. }
  584. if (options.tooltip) {
  585. for (prop in options.tooltip) {
  586. if (options.tooltip.hasOwnProperty(prop)) {
  587. this.constants.tooltip[prop] = options.tooltip[prop];
  588. }
  589. }
  590. if (options.tooltip.color) {
  591. this.constants.tooltip.color = util.parseColor(options.tooltip.color);
  592. }
  593. }
  594. if ('clickToUse' in options) {
  595. if (options.clickToUse) {
  596. this.activator = new Activator(this.frame);
  597. this.activator.on('change', this._createKeyBinds.bind(this));
  598. }
  599. else {
  600. if (this.activator) {
  601. this.activator.destroy();
  602. delete this.activator;
  603. }
  604. }
  605. }
  606. if (options.labels) {
  607. throw new Error('Option "labels" is deprecated. Use options "locale" and "locales" instead.');
  608. }
  609. }
  610. // (Re)loading the mixins that can be enabled or disabled in the options.
  611. // load the force calculation functions, grouped under the physics system.
  612. this._loadPhysicsSystem();
  613. // load the navigation system.
  614. this._loadNavigationControls();
  615. // load the data manipulation system
  616. this._loadManipulationSystem();
  617. // configure the smooth curves
  618. this._configureSmoothCurves();
  619. // bind keys. If disabled, this will not do anything;
  620. this._createKeyBinds();
  621. this.setSize(this.constants.width, this.constants.height);
  622. this.moving = true;
  623. this.start();
  624. };
  625. /**
  626. * Create the main frame for the Network.
  627. * This function is executed once when a Network object is created. The frame
  628. * contains a canvas, and this canvas contains all objects like the axis and
  629. * nodes.
  630. * @private
  631. */
  632. Network.prototype._create = function () {
  633. // remove all elements from the container element.
  634. while (this.containerElement.hasChildNodes()) {
  635. this.containerElement.removeChild(this.containerElement.firstChild);
  636. }
  637. this.frame = document.createElement('div');
  638. this.frame.className = 'vis network-frame';
  639. this.frame.style.position = 'relative';
  640. this.frame.style.overflow = 'hidden';
  641. // create the network canvas (HTML canvas element)
  642. this.frame.canvas = document.createElement( 'canvas' );
  643. this.frame.canvas.style.position = 'relative';
  644. this.frame.appendChild(this.frame.canvas);
  645. if (!this.frame.canvas.getContext) {
  646. var noCanvas = document.createElement( 'DIV' );
  647. noCanvas.style.color = 'red';
  648. noCanvas.style.fontWeight = 'bold' ;
  649. noCanvas.style.padding = '10px';
  650. noCanvas.innerHTML = 'Error: your browser does not support HTML canvas';
  651. this.frame.canvas.appendChild(noCanvas);
  652. }
  653. var me = this;
  654. this.drag = {};
  655. this.pinch = {};
  656. this.hammer = Hammer(this.frame.canvas, {
  657. prevent_default: true
  658. });
  659. this.hammer.on('tap', me._onTap.bind(me) );
  660. this.hammer.on('doubletap', me._onDoubleTap.bind(me) );
  661. this.hammer.on('hold', me._onHold.bind(me) );
  662. this.hammer.on('pinch', me._onPinch.bind(me) );
  663. this.hammer.on('touch', me._onTouch.bind(me) );
  664. this.hammer.on('dragstart', me._onDragStart.bind(me) );
  665. this.hammer.on('drag', me._onDrag.bind(me) );
  666. this.hammer.on('dragend', me._onDragEnd.bind(me) );
  667. this.hammer.on('release', me._onRelease.bind(me) );
  668. this.hammer.on('mousewheel',me._onMouseWheel.bind(me) );
  669. this.hammer.on('DOMMouseScroll',me._onMouseWheel.bind(me) ); // for FF
  670. this.hammer.on('mousemove', me._onMouseMoveTitle.bind(me) );
  671. // add the frame to the container element
  672. this.containerElement.appendChild(this.frame);
  673. };
  674. /**
  675. * Binding the keys for keyboard navigation. These functions are defined in the NavigationMixin
  676. * @private
  677. */
  678. Network.prototype._createKeyBinds = function() {
  679. var me = this;
  680. this.mousetrap = mousetrap;
  681. this.mousetrap.reset();
  682. if (this.constants.keyboard.enabled && this.isActive()) {
  683. this.mousetrap.bind("up", this._moveUp.bind(me) , "keydown");
  684. this.mousetrap.bind("up", this._yStopMoving.bind(me), "keyup");
  685. this.mousetrap.bind("down", this._moveDown.bind(me) , "keydown");
  686. this.mousetrap.bind("down", this._yStopMoving.bind(me), "keyup");
  687. this.mousetrap.bind("left", this._moveLeft.bind(me) , "keydown");
  688. this.mousetrap.bind("left", this._xStopMoving.bind(me), "keyup");
  689. this.mousetrap.bind("right",this._moveRight.bind(me), "keydown");
  690. this.mousetrap.bind("right",this._xStopMoving.bind(me), "keyup");
  691. this.mousetrap.bind("=", this._zoomIn.bind(me), "keydown");
  692. this.mousetrap.bind("=", this._stopZoom.bind(me), "keyup");
  693. this.mousetrap.bind("-", this._zoomOut.bind(me), "keydown");
  694. this.mousetrap.bind("-", this._stopZoom.bind(me), "keyup");
  695. this.mousetrap.bind("[", this._zoomIn.bind(me), "keydown");
  696. this.mousetrap.bind("[", this._stopZoom.bind(me), "keyup");
  697. this.mousetrap.bind("]", this._zoomOut.bind(me), "keydown");
  698. this.mousetrap.bind("]", this._stopZoom.bind(me), "keyup");
  699. this.mousetrap.bind("pageup",this._zoomIn.bind(me), "keydown");
  700. this.mousetrap.bind("pageup",this._stopZoom.bind(me), "keyup");
  701. this.mousetrap.bind("pagedown",this._zoomOut.bind(me),"keydown");
  702. this.mousetrap.bind("pagedown",this._stopZoom.bind(me), "keyup");
  703. }
  704. if (this.constants.dataManipulation.enabled == true) {
  705. this.mousetrap.bind("escape",this._createManipulatorBar.bind(me));
  706. this.mousetrap.bind("del",this._deleteSelected.bind(me));
  707. }
  708. };
  709. /**
  710. * Get the pointer location from a touch location
  711. * @param {{pageX: Number, pageY: Number}} touch
  712. * @return {{x: Number, y: Number}} pointer
  713. * @private
  714. */
  715. Network.prototype._getPointer = function (touch) {
  716. return {
  717. x: touch.pageX - util.getAbsoluteLeft(this.frame.canvas),
  718. y: touch.pageY - util.getAbsoluteTop(this.frame.canvas)
  719. };
  720. };
  721. /**
  722. * On start of a touch gesture, store the pointer
  723. * @param event
  724. * @private
  725. */
  726. Network.prototype._onTouch = function (event) {
  727. this.drag.pointer = this._getPointer(event.gesture.center);
  728. this.drag.pinched = false;
  729. this.pinch.scale = this._getScale();
  730. this._handleTouch(this.drag.pointer);
  731. };
  732. /**
  733. * handle drag start event
  734. * @private
  735. */
  736. Network.prototype._onDragStart = function () {
  737. this._handleDragStart();
  738. };
  739. /**
  740. * This function is called by _onDragStart.
  741. * It is separated out because we can then overload it for the datamanipulation system.
  742. *
  743. * @private
  744. */
  745. Network.prototype._handleDragStart = function() {
  746. var drag = this.drag;
  747. var node = this._getNodeAt(drag.pointer);
  748. // note: drag.pointer is set in _onTouch to get the initial touch location
  749. drag.dragging = true;
  750. drag.selection = [];
  751. drag.translation = this._getTranslation();
  752. drag.nodeId = null;
  753. if (node != null) {
  754. drag.nodeId = node.id;
  755. // select the clicked node if not yet selected
  756. if (!node.isSelected()) {
  757. this._selectObject(node,false);
  758. }
  759. // create an array with the selected nodes and their original location and status
  760. for (var objectId in this.selectionObj.nodes) {
  761. if (this.selectionObj.nodes.hasOwnProperty(objectId)) {
  762. var object = this.selectionObj.nodes[objectId];
  763. var s = {
  764. id: object.id,
  765. node: object,
  766. // store original x, y, xFixed and yFixed, make the node temporarily Fixed
  767. x: object.x,
  768. y: object.y,
  769. xFixed: object.xFixed,
  770. yFixed: object.yFixed
  771. };
  772. object.xFixed = true;
  773. object.yFixed = true;
  774. drag.selection.push(s);
  775. }
  776. }
  777. }
  778. };
  779. /**
  780. * handle drag event
  781. * @private
  782. */
  783. Network.prototype._onDrag = function (event) {
  784. this._handleOnDrag(event)
  785. };
  786. /**
  787. * This function is called by _onDrag.
  788. * It is separated out because we can then overload it for the datamanipulation system.
  789. *
  790. * @private
  791. */
  792. Network.prototype._handleOnDrag = function(event) {
  793. if (this.drag.pinched) {
  794. return;
  795. }
  796. var pointer = this._getPointer(event.gesture.center);
  797. var me = this;
  798. var drag = this.drag;
  799. var selection = drag.selection;
  800. if (selection && selection.length && this.constants.dragNodes == true) {
  801. // calculate delta's and new location
  802. var deltaX = pointer.x - drag.pointer.x;
  803. var deltaY = pointer.y - drag.pointer.y;
  804. // update position of all selected nodes
  805. selection.forEach(function (s) {
  806. var node = s.node;
  807. if (!s.xFixed) {
  808. node.x = me._XconvertDOMtoCanvas(me._XconvertCanvasToDOM(s.x) + deltaX);
  809. }
  810. if (!s.yFixed) {
  811. node.y = me._YconvertDOMtoCanvas(me._YconvertCanvasToDOM(s.y) + deltaY);
  812. }
  813. });
  814. // start _animationStep if not yet running
  815. if (!this.moving) {
  816. this.moving = true;
  817. this.start();
  818. }
  819. }
  820. else {
  821. if (this.constants.dragNetwork == true) {
  822. // move the network
  823. var diffX = pointer.x - this.drag.pointer.x;
  824. var diffY = pointer.y - this.drag.pointer.y;
  825. this._setTranslation(
  826. this.drag.translation.x + diffX,
  827. this.drag.translation.y + diffY
  828. );
  829. this._redraw();
  830. // this.moving = true;
  831. // this.start();
  832. }
  833. }
  834. };
  835. /**
  836. * handle drag start event
  837. * @private
  838. */
  839. Network.prototype._onDragEnd = function () {
  840. this.drag.dragging = false;
  841. var selection = this.drag.selection;
  842. if (selection && selection.length) {
  843. selection.forEach(function (s) {
  844. // restore original xFixed and yFixed
  845. s.node.xFixed = s.xFixed;
  846. s.node.yFixed = s.yFixed;
  847. });
  848. this.moving = true;
  849. this.start();
  850. }
  851. else {
  852. this._redraw();
  853. }
  854. };
  855. /**
  856. * handle tap/click event: select/unselect a node
  857. * @private
  858. */
  859. Network.prototype._onTap = function (event) {
  860. var pointer = this._getPointer(event.gesture.center);
  861. this.pointerPosition = pointer;
  862. this._handleTap(pointer);
  863. };
  864. /**
  865. * handle doubletap event
  866. * @private
  867. */
  868. Network.prototype._onDoubleTap = function (event) {
  869. var pointer = this._getPointer(event.gesture.center);
  870. this._handleDoubleTap(pointer);
  871. };
  872. /**
  873. * handle long tap event: multi select nodes
  874. * @private
  875. */
  876. Network.prototype._onHold = function (event) {
  877. var pointer = this._getPointer(event.gesture.center);
  878. this.pointerPosition = pointer;
  879. this._handleOnHold(pointer);
  880. };
  881. /**
  882. * handle the release of the screen
  883. *
  884. * @private
  885. */
  886. Network.prototype._onRelease = function (event) {
  887. var pointer = this._getPointer(event.gesture.center);
  888. this._handleOnRelease(pointer);
  889. };
  890. /**
  891. * Handle pinch event
  892. * @param event
  893. * @private
  894. */
  895. Network.prototype._onPinch = function (event) {
  896. var pointer = this._getPointer(event.gesture.center);
  897. this.drag.pinched = true;
  898. if (!('scale' in this.pinch)) {
  899. this.pinch.scale = 1;
  900. }
  901. // TODO: enabled moving while pinching?
  902. var scale = this.pinch.scale * event.gesture.scale;
  903. this._zoom(scale, pointer)
  904. };
  905. /**
  906. * Zoom the network in or out
  907. * @param {Number} scale a number around 1, and between 0.01 and 10
  908. * @param {{x: Number, y: Number}} pointer Position on screen
  909. * @return {Number} appliedScale scale is limited within the boundaries
  910. * @private
  911. */
  912. Network.prototype._zoom = function(scale, pointer) {
  913. if (this.constants.zoomable == true) {
  914. var scaleOld = this._getScale();
  915. if (scale < 0.00001) {
  916. scale = 0.00001;
  917. }
  918. if (scale > 10) {
  919. scale = 10;
  920. }
  921. var preScaleDragPointer = null;
  922. if (this.drag !== undefined) {
  923. if (this.drag.dragging == true) {
  924. preScaleDragPointer = this.DOMtoCanvas(this.drag.pointer);
  925. }
  926. }
  927. // + this.frame.canvas.clientHeight / 2
  928. var translation = this._getTranslation();
  929. var scaleFrac = scale / scaleOld;
  930. var tx = (1 - scaleFrac) * pointer.x + translation.x * scaleFrac;
  931. var ty = (1 - scaleFrac) * pointer.y + translation.y * scaleFrac;
  932. this.areaCenter = {"x" : this._XconvertDOMtoCanvas(pointer.x),
  933. "y" : this._YconvertDOMtoCanvas(pointer.y)};
  934. this._setScale(scale);
  935. this._setTranslation(tx, ty);
  936. this.updateClustersDefault();
  937. if (preScaleDragPointer != null) {
  938. var postScaleDragPointer = this.canvasToDOM(preScaleDragPointer);
  939. this.drag.pointer.x = postScaleDragPointer.x;
  940. this.drag.pointer.y = postScaleDragPointer.y;
  941. }
  942. this._redraw();
  943. if (scaleOld < scale) {
  944. this.emit("zoom", {direction:"+"});
  945. }
  946. else {
  947. this.emit("zoom", {direction:"-"});
  948. }
  949. return scale;
  950. }
  951. };
  952. /**
  953. * Event handler for mouse wheel event, used to zoom the timeline
  954. * See http://adomas.org/javascript-mouse-wheel/
  955. * https://github.com/EightMedia/hammer.js/issues/256
  956. * @param {MouseEvent} event
  957. * @private
  958. */
  959. Network.prototype._onMouseWheel = function(event) {
  960. // retrieve delta
  961. var delta = 0;
  962. if (event.wheelDelta) { /* IE/Opera. */
  963. delta = event.wheelDelta/120;
  964. } else if (event.detail) { /* Mozilla case. */
  965. // In Mozilla, sign of delta is different than in IE.
  966. // Also, delta is multiple of 3.
  967. delta = -event.detail/3;
  968. }
  969. // If delta is nonzero, handle it.
  970. // Basically, delta is now positive if wheel was scrolled up,
  971. // and negative, if wheel was scrolled down.
  972. if (delta) {
  973. // calculate the new scale
  974. var scale = this._getScale();
  975. var zoom = delta / 10;
  976. if (delta < 0) {
  977. zoom = zoom / (1 - zoom);
  978. }
  979. scale *= (1 + zoom);
  980. // calculate the pointer location
  981. var gesture = hammerUtil.fakeGesture(this, event);
  982. var pointer = this._getPointer(gesture.center);
  983. // apply the new scale
  984. this._zoom(scale, pointer);
  985. }
  986. // Prevent default actions caused by mouse wheel.
  987. event.preventDefault();
  988. };
  989. /**
  990. * Mouse move handler for checking whether the title moves over a node with a title.
  991. * @param {Event} event
  992. * @private
  993. */
  994. Network.prototype._onMouseMoveTitle = function (event) {
  995. var gesture = hammerUtil.fakeGesture(this, event);
  996. var pointer = this._getPointer(gesture.center);
  997. // check if the previously selected node is still selected
  998. if (this.popupObj) {
  999. this._checkHidePopup(pointer);
  1000. }
  1001. // start a timeout that will check if the mouse is positioned above
  1002. // an element
  1003. var me = this;
  1004. var checkShow = function() {
  1005. me._checkShowPopup(pointer);
  1006. };
  1007. if (this.popupTimer) {
  1008. clearInterval(this.popupTimer); // stop any running calculationTimer
  1009. }
  1010. if (!this.drag.dragging) {
  1011. this.popupTimer = setTimeout(checkShow, this.constants.tooltip.delay);
  1012. }
  1013. /**
  1014. * Adding hover highlights
  1015. */
  1016. if (this.constants.hover == true) {
  1017. // removing all hover highlights
  1018. for (var edgeId in this.hoverObj.edges) {
  1019. if (this.hoverObj.edges.hasOwnProperty(edgeId)) {
  1020. this.hoverObj.edges[edgeId].hover = false;
  1021. delete this.hoverObj.edges[edgeId];
  1022. }
  1023. }
  1024. // adding hover highlights
  1025. var obj = this._getNodeAt(pointer);
  1026. if (obj == null) {
  1027. obj = this._getEdgeAt(pointer);
  1028. }
  1029. if (obj != null) {
  1030. this._hoverObject(obj);
  1031. }
  1032. // removing all node hover highlights except for the selected one.
  1033. for (var nodeId in this.hoverObj.nodes) {
  1034. if (this.hoverObj.nodes.hasOwnProperty(nodeId)) {
  1035. if (obj instanceof Node && obj.id != nodeId || obj instanceof Edge || obj == null) {
  1036. this._blurObject(this.hoverObj.nodes[nodeId]);
  1037. delete this.hoverObj.nodes[nodeId];
  1038. }
  1039. }
  1040. }
  1041. this.redraw();
  1042. }
  1043. };
  1044. /**
  1045. * Check if there is an element on the given position in the network
  1046. * (a node or edge). If so, and if this element has a title,
  1047. * show a popup window with its title.
  1048. *
  1049. * @param {{x:Number, y:Number}} pointer
  1050. * @private
  1051. */
  1052. Network.prototype._checkShowPopup = function (pointer) {
  1053. var obj = {
  1054. left: this._XconvertDOMtoCanvas(pointer.x),
  1055. top: this._YconvertDOMtoCanvas(pointer.y),
  1056. right: this._XconvertDOMtoCanvas(pointer.x),
  1057. bottom: this._YconvertDOMtoCanvas(pointer.y)
  1058. };
  1059. var id;
  1060. var lastPopupNode = this.popupObj;
  1061. if (this.popupObj == undefined) {
  1062. // search the nodes for overlap, select the top one in case of multiple nodes
  1063. var nodes = this.nodes;
  1064. for (id in nodes) {
  1065. if (nodes.hasOwnProperty(id)) {
  1066. var node = nodes[id];
  1067. if (node.getTitle() !== undefined && node.isOverlappingWith(obj)) {
  1068. this.popupObj = node;
  1069. break;
  1070. }
  1071. }
  1072. }
  1073. }
  1074. if (this.popupObj === undefined) {
  1075. // search the edges for overlap
  1076. var edges = this.edges;
  1077. for (id in edges) {
  1078. if (edges.hasOwnProperty(id)) {
  1079. var edge = edges[id];
  1080. if (edge.connected && (edge.getTitle() !== undefined) &&
  1081. edge.isOverlappingWith(obj)) {
  1082. this.popupObj = edge;
  1083. break;
  1084. }
  1085. }
  1086. }
  1087. }
  1088. if (this.popupObj) {
  1089. // show popup message window
  1090. if (this.popupObj != lastPopupNode) {
  1091. var me = this;
  1092. if (!me.popup) {
  1093. me.popup = new Popup(me.frame, me.constants.tooltip);
  1094. }
  1095. // adjust a small offset such that the mouse cursor is located in the
  1096. // bottom left location of the popup, and you can easily move over the
  1097. // popup area
  1098. me.popup.setPosition(pointer.x - 3, pointer.y - 3);
  1099. me.popup.setText(me.popupObj.getTitle());
  1100. me.popup.show();
  1101. }
  1102. }
  1103. else {
  1104. if (this.popup) {
  1105. this.popup.hide();
  1106. }
  1107. }
  1108. };
  1109. /**
  1110. * Check if the popup must be hided, which is the case when the mouse is no
  1111. * longer hovering on the object
  1112. * @param {{x:Number, y:Number}} pointer
  1113. * @private
  1114. */
  1115. Network.prototype._checkHidePopup = function (pointer) {
  1116. if (!this.popupObj || !this._getNodeAt(pointer) ) {
  1117. this.popupObj = undefined;
  1118. if (this.popup) {
  1119. this.popup.hide();
  1120. }
  1121. }
  1122. };
  1123. /**
  1124. * Set a new size for the network
  1125. * @param {string} width Width in pixels or percentage (for example '800px'
  1126. * or '50%')
  1127. * @param {string} height Height in pixels or percentage (for example '400px'
  1128. * or '30%')
  1129. */
  1130. Network.prototype.setSize = function(width, height) {
  1131. this.frame.style.width = width;
  1132. this.frame.style.height = height;
  1133. this.frame.canvas.style.width = '100%';
  1134. this.frame.canvas.style.height = '100%';
  1135. this.frame.canvas.width = this.frame.canvas.clientWidth;
  1136. this.frame.canvas.height = this.frame.canvas.clientHeight;
  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. this._updateCalculationNodes();
  1323. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  1324. this._resetLevels();
  1325. this._setupHierarchicalLayout();
  1326. }
  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. };
  1675. /**
  1676. * When initializing and stabilizing, we can freeze nodes with a predefined position. This greatly speeds up stabilization
  1677. * because only the supportnodes for the smoothCurves have to settle.
  1678. *
  1679. * @private
  1680. */
  1681. Network.prototype._freezeDefinedNodes = function() {
  1682. var nodes = this.nodes;
  1683. for (var id in nodes) {
  1684. if (nodes.hasOwnProperty(id)) {
  1685. if (nodes[id].x != null && nodes[id].y != null) {
  1686. nodes[id].fixedData.x = nodes[id].xFixed;
  1687. nodes[id].fixedData.y = nodes[id].yFixed;
  1688. nodes[id].xFixed = true;
  1689. nodes[id].yFixed = true;
  1690. }
  1691. }
  1692. }
  1693. };
  1694. /**
  1695. * Unfreezes the nodes that have been frozen by _freezeDefinedNodes.
  1696. *
  1697. * @private
  1698. */
  1699. Network.prototype._restoreFrozenNodes = function() {
  1700. var nodes = this.nodes;
  1701. for (var id in nodes) {
  1702. if (nodes.hasOwnProperty(id)) {
  1703. if (nodes[id].fixedData.x != null) {
  1704. nodes[id].xFixed = nodes[id].fixedData.x;
  1705. nodes[id].yFixed = nodes[id].fixedData.y;
  1706. }
  1707. }
  1708. }
  1709. };
  1710. /**
  1711. * Check if any of the nodes is still moving
  1712. * @param {number} vmin the minimum velocity considered as 'moving'
  1713. * @return {boolean} true if moving, false if non of the nodes is moving
  1714. * @private
  1715. */
  1716. Network.prototype._isMoving = function(vmin) {
  1717. var nodes = this.nodes;
  1718. for (var id in nodes) {
  1719. if (nodes.hasOwnProperty(id) && nodes[id].isMoving(vmin)) {
  1720. return true;
  1721. }
  1722. }
  1723. return false;
  1724. };
  1725. /**
  1726. * /**
  1727. * Perform one discrete step for all nodes
  1728. *
  1729. * @private
  1730. */
  1731. Network.prototype._discreteStepNodes = function() {
  1732. var interval = this.physicsDiscreteStepsize;
  1733. var nodes = this.nodes;
  1734. var nodeId;
  1735. var nodesPresent = false;
  1736. if (this.constants.maxVelocity > 0) {
  1737. for (nodeId in nodes) {
  1738. if (nodes.hasOwnProperty(nodeId)) {
  1739. nodes[nodeId].discreteStepLimited(interval, this.constants.maxVelocity);
  1740. nodesPresent = true;
  1741. }
  1742. }
  1743. }
  1744. else {
  1745. for (nodeId in nodes) {
  1746. if (nodes.hasOwnProperty(nodeId)) {
  1747. nodes[nodeId].discreteStep(interval);
  1748. nodesPresent = true;
  1749. }
  1750. }
  1751. }
  1752. if (nodesPresent == true) {
  1753. var vminCorrected = this.constants.minVelocity / Math.max(this.scale,0.05);
  1754. if (vminCorrected > 0.5*this.constants.maxVelocity) {
  1755. return true;
  1756. }
  1757. else {
  1758. return this._isMoving(vminCorrected);
  1759. }
  1760. }
  1761. return false;
  1762. };
  1763. /**
  1764. * A single simulation step (or "tick") in the physics simulation
  1765. *
  1766. * @private
  1767. */
  1768. Network.prototype._physicsTick = function() {
  1769. if (!this.freezeSimulation) {
  1770. if (this.moving == true) {
  1771. var mainMovingStatus = false;
  1772. var supportMovingStatus = false;
  1773. this._doInAllActiveSectors("_initializeForceCalculation");
  1774. var mainMoving = this._doInAllActiveSectors("_discreteStepNodes");
  1775. if (this.constants.smoothCurves.enabled == true && this.constants.smoothCurves.dynamic == true) {
  1776. supportMovingStatus = this._doInSupportSector("_discreteStepNodes");
  1777. }
  1778. // gather movement data from all sectors, if one moves, we are NOT stabilzied
  1779. for (var i = 0; i < mainMoving.length; i++) {mainMovingStatus = mainMoving[0] || mainMovingStatus;}
  1780. // determine if the network has stabilzied
  1781. this.moving = mainMovingStatus || supportMovingStatus;
  1782. this.stabilizationIterations++;
  1783. }
  1784. }
  1785. };
  1786. /**
  1787. * This function runs one step of the animation. It calls an x amount of physics ticks and one render tick.
  1788. * It reschedules itself at the beginning of the function
  1789. *
  1790. * @private
  1791. */
  1792. Network.prototype._animationStep = function() {
  1793. // reset the timer so a new scheduled animation step can be set
  1794. this.timer = undefined;
  1795. // handle the keyboad movement
  1796. this._handleNavigation();
  1797. // this schedules a new animation step
  1798. this.start();
  1799. // start the physics simulation
  1800. var calculationTime = Date.now();
  1801. var maxSteps = 1;
  1802. this._physicsTick();
  1803. var timeRequired = Date.now() - calculationTime;
  1804. while (timeRequired < 0.9*(this.renderTimestep - this.renderTime) && maxSteps < this.maxPhysicsTicksPerRender) {
  1805. this._physicsTick();
  1806. timeRequired = Date.now() - calculationTime;
  1807. maxSteps++;
  1808. }
  1809. // start the rendering process
  1810. var renderTime = Date.now();
  1811. this._redraw();
  1812. this.renderTime = Date.now() - renderTime;
  1813. };
  1814. if (typeof window !== 'undefined') {
  1815. window.requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame ||
  1816. window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;
  1817. }
  1818. /**
  1819. * Schedule a animation step with the refreshrate interval.
  1820. */
  1821. Network.prototype.start = function() {
  1822. if (this.moving == true || this.xIncrement != 0 || this.yIncrement != 0 || this.zoomIncrement != 0) {
  1823. if (!this.timer) {
  1824. var ua = navigator.userAgent.toLowerCase();
  1825. var requiresTimeout = false;
  1826. if (ua.indexOf('msie 9.0') != -1) { // IE 9
  1827. requiresTimeout = true;
  1828. }
  1829. else if (ua.indexOf('safari') != -1) { // safari
  1830. if (ua.indexOf('chrome') <= -1) {
  1831. requiresTimeout = true;
  1832. }
  1833. }
  1834. if (requiresTimeout == true) {
  1835. this.timer = window.setTimeout(this._animationStep.bind(this), this.renderTimestep); // wait this.renderTimeStep milliseconds and perform the animation step function
  1836. }
  1837. else{
  1838. this.timer = window.requestAnimationFrame(this._animationStep.bind(this), this.renderTimestep); // wait this.renderTimeStep milliseconds and perform the animation step function
  1839. }
  1840. }
  1841. }
  1842. else {
  1843. this._redraw();
  1844. if (this.stabilizationIterations > 0) {
  1845. // trigger the "stabilized" event.
  1846. // The event is triggered on the next tick, to prevent the case that
  1847. // it is fired while initializing the Network, in which case you would not
  1848. // be able to catch it
  1849. var me = this;
  1850. var params = {
  1851. iterations: me.stabilizationIterations
  1852. };
  1853. me.stabilizationIterations = 0;
  1854. setTimeout(function () {
  1855. me.emit("stabilized", params);
  1856. }, 0);
  1857. }
  1858. }
  1859. };
  1860. /**
  1861. * Move the network according to the keyboard presses.
  1862. *
  1863. * @private
  1864. */
  1865. Network.prototype._handleNavigation = function() {
  1866. if (this.xIncrement != 0 || this.yIncrement != 0) {
  1867. var translation = this._getTranslation();
  1868. this._setTranslation(translation.x+this.xIncrement, translation.y+this.yIncrement);
  1869. }
  1870. if (this.zoomIncrement != 0) {
  1871. var center = {
  1872. x: this.frame.canvas.clientWidth / 2,
  1873. y: this.frame.canvas.clientHeight / 2
  1874. };
  1875. this._zoom(this.scale*(1 + this.zoomIncrement), center);
  1876. }
  1877. };
  1878. /**
  1879. * Freeze the _animationStep
  1880. */
  1881. Network.prototype.toggleFreeze = function() {
  1882. if (this.freezeSimulation == false) {
  1883. this.freezeSimulation = true;
  1884. }
  1885. else {
  1886. this.freezeSimulation = false;
  1887. this.start();
  1888. }
  1889. };
  1890. /**
  1891. * This function cleans the support nodes if they are not needed and adds them when they are.
  1892. *
  1893. * @param {boolean} [disableStart]
  1894. * @private
  1895. */
  1896. Network.prototype._configureSmoothCurves = function(disableStart) {
  1897. if (disableStart === undefined) {
  1898. disableStart = true;
  1899. }
  1900. if (this.constants.smoothCurves.enabled == true && this.constants.smoothCurves.dynamic == true) {
  1901. this._createBezierNodes();
  1902. // cleanup unused support nodes
  1903. for (var nodeId in this.sectors['support']['nodes']) {
  1904. if (this.sectors['support']['nodes'].hasOwnProperty(nodeId)) {
  1905. if (this.edges[this.sectors['support']['nodes'][nodeId].parentEdgeId] === undefined) {
  1906. delete this.sectors['support']['nodes'][nodeId];
  1907. }
  1908. }
  1909. }
  1910. }
  1911. else {
  1912. // delete the support nodes
  1913. this.sectors['support']['nodes'] = {};
  1914. for (var edgeId in this.edges) {
  1915. if (this.edges.hasOwnProperty(edgeId)) {
  1916. this.edges[edgeId].via = null;
  1917. }
  1918. }
  1919. }
  1920. this._updateCalculationNodes();
  1921. if (!disableStart) {
  1922. this.moving = true;
  1923. this.start();
  1924. }
  1925. };
  1926. /**
  1927. * Bezier curves require an anchor point to calculate the smooth flow. These points are nodes. These nodes are invisible but
  1928. * are used for the force calculation.
  1929. *
  1930. * @private
  1931. */
  1932. Network.prototype._createBezierNodes = function() {
  1933. if (this.constants.smoothCurves.enabled == true && this.constants.smoothCurves.dynamic == true) {
  1934. for (var edgeId in this.edges) {
  1935. if (this.edges.hasOwnProperty(edgeId)) {
  1936. var edge = this.edges[edgeId];
  1937. if (edge.via == null) {
  1938. var nodeId = "edgeId:".concat(edge.id);
  1939. this.sectors['support']['nodes'][nodeId] = new Node(
  1940. {id:nodeId,
  1941. mass:1,
  1942. shape:'circle',
  1943. image:"",
  1944. internalMultiplier:1
  1945. },{},{},this.constants);
  1946. edge.via = this.sectors['support']['nodes'][nodeId];
  1947. edge.via.parentEdgeId = edge.id;
  1948. edge.positionBezierNode();
  1949. }
  1950. }
  1951. }
  1952. }
  1953. };
  1954. /**
  1955. * load the functions that load the mixins into the prototype.
  1956. *
  1957. * @private
  1958. */
  1959. Network.prototype._initializeMixinLoaders = function () {
  1960. for (var mixin in MixinLoader) {
  1961. if (MixinLoader.hasOwnProperty(mixin)) {
  1962. Network.prototype[mixin] = MixinLoader[mixin];
  1963. }
  1964. }
  1965. };
  1966. /**
  1967. * Load the XY positions of the nodes into the dataset.
  1968. */
  1969. Network.prototype.storePosition = function() {
  1970. var dataArray = [];
  1971. for (var nodeId in this.nodes) {
  1972. if (this.nodes.hasOwnProperty(nodeId)) {
  1973. var node = this.nodes[nodeId];
  1974. var allowedToMoveX = !this.nodes.xFixed;
  1975. var allowedToMoveY = !this.nodes.yFixed;
  1976. if (this.nodesData._data[nodeId].x != Math.round(node.x) || this.nodesData._data[nodeId].y != Math.round(node.y)) {
  1977. dataArray.push({id:nodeId,x:Math.round(node.x),y:Math.round(node.y),allowedToMoveX:allowedToMoveX,allowedToMoveY:allowedToMoveY});
  1978. }
  1979. }
  1980. }
  1981. this.nodesData.update(dataArray);
  1982. };
  1983. /**
  1984. * Center a node in view.
  1985. *
  1986. * @param {Number} nodeId
  1987. * @param {Number} [zoomLevel]
  1988. */
  1989. Network.prototype.focusOnNode = function (nodeId, zoomLevel) {
  1990. if (this.nodes.hasOwnProperty(nodeId)) {
  1991. if (zoomLevel === undefined) {
  1992. zoomLevel = this._getScale();
  1993. }
  1994. var nodePosition= {x: this.nodes[nodeId].x, y: this.nodes[nodeId].y};
  1995. var requiredScale = zoomLevel;
  1996. this._setScale(requiredScale);
  1997. var canvasCenter = this.DOMtoCanvas({x:0.5 * this.frame.canvas.width,y:0.5 * this.frame.canvas.height});
  1998. var translation = this._getTranslation();
  1999. var distanceFromCenter = {x:canvasCenter.x - nodePosition.x,
  2000. y:canvasCenter.y - nodePosition.y};
  2001. this._setTranslation(translation.x + requiredScale * distanceFromCenter.x,
  2002. translation.y + requiredScale * distanceFromCenter.y);
  2003. this.redraw();
  2004. }
  2005. else {
  2006. console.log("This nodeId cannot be found.");
  2007. }
  2008. };
  2009. /**
  2010. * Returns true when the Timeline is active.
  2011. * @returns {boolean}
  2012. */
  2013. Network.prototype.isActive = function () {
  2014. return !this.activator || this.activator.active;
  2015. };
  2016. module.exports = Network;