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.

2485 lines
74 KiB

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