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.

2961 lines
89 KiB

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