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.

2966 lines
89 KiB

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