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.

2960 lines
89 KiB

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