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.

2963 lines
89 KiB

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