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.

2883 lines
86 KiB

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