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.

2917 lines
88 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 // release in 4.0
  126. },
  127. configurePhysics:false,
  128. physics: {
  129. barnesHut: {
  130. enabled: true,
  131. thetaInverted: 1 / 0.5, // inverted to save time during calculation
  132. gravitationalConstant: -2000,
  133. centralGravity: 0.3,
  134. springLength: 95,
  135. springConstant: 0.04,
  136. damping: 0.09
  137. },
  138. repulsion: {
  139. centralGravity: 0.0,
  140. springLength: 200,
  141. springConstant: 0.05,
  142. nodeDistance: 100,
  143. damping: 0.09
  144. },
  145. hierarchicalRepulsion: {
  146. enabled: false,
  147. centralGravity: 0.0,
  148. springLength: 100,
  149. springConstant: 0.01,
  150. nodeDistance: 150,
  151. damping: 0.09
  152. },
  153. damping: null,
  154. centralGravity: null,
  155. springLength: null,
  156. springConstant: null
  157. },
  158. clustering: { // Per Node in Cluster = PNiC
  159. enabled: false, // (Boolean) | global on/off switch for clustering.
  160. initialMaxNodes: 100, // (# nodes) | if the initial amount of nodes is larger than this, we cluster until the total number is less than this threshold.
  161. clusterThreshold:500, // (# nodes) | during calculate forces, we check if the total number of nodes is larger than this. If it is, cluster until reduced to reduceToNodes
  162. reduceToNodes:300, // (# nodes) | during calculate forces, we check if the total number of nodes is larger than clusterThreshold. If it is, cluster until reduced to this
  163. chainThreshold: 0.4, // (% of all drawn nodes)| maximum percentage of allowed chainnodes (long strings of connected nodes) within all nodes. (lower means less chains).
  164. clusterEdgeThreshold: 20, // (px) | edge length threshold. if smaller, this node is clustered.
  165. sectorThreshold: 100, // (# nodes in cluster) | cluster size threshold. If larger, expanding in own sector.
  166. screenSizeThreshold: 0.2, // (% of canvas) | relative size threshold. If the width or height of a clusternode takes up this much of the screen, decluster node.
  167. fontSizeMultiplier: 4.0, // (px PNiC) | how much the cluster font size grows per node in cluster (in px).
  168. maxFontSize: 1000,
  169. forceAmplification: 0.1, // (multiplier PNiC) | factor of increase fo the repulsion force of a cluster (per node in cluster).
  170. distanceAmplification: 0.1, // (multiplier PNiC) | factor how much the repulsion distance of a cluster increases (per node in cluster).
  171. edgeGrowth: 20, // (px PNiC) | amount of clusterSize connected to the edge is multiplied with this and added to edgeLength.
  172. nodeScaling: {width: 1, // (px PNiC) | growth of the width per node in cluster.
  173. height: 1, // (px PNiC) | growth of the height per node in cluster.
  174. radius: 1}, // (px PNiC) | growth of the radius per node in cluster.
  175. maxNodeSizeIncrements: 600, // (# increments) | max growth of the width per node in cluster.
  176. activeAreaBoxSize: 80, // (px) | box area around the curser where clusters are popped open.
  177. clusterLevelDifference: 2, // used for normalization of the cluster levels
  178. clusterByZoom: true // enable clustering through zooming in and out
  179. },
  180. navigation: {
  181. enabled: false
  182. },
  183. keyboard: {
  184. enabled: false,
  185. speed: {x: 10, y: 10, zoom: 0.02},
  186. bindToWindow: true
  187. },
  188. dataManipulation: {
  189. enabled: false,
  190. initiallyVisible: false
  191. },
  192. hierarchicalLayout: {
  193. enabled:false,
  194. levelSeparation: 150,
  195. nodeSpacing: 100,
  196. direction: "UD", // UD, DU, LR, RL
  197. layout: "hubsize" // hubsize, directed
  198. },
  199. freezeForStabilization: false,
  200. smoothCurves: {
  201. enabled: true,
  202. dynamic: true,
  203. type: "continuous",
  204. roundness: 0.5
  205. },
  206. maxVelocity: 50,
  207. minVelocity: 0.1, // px/s
  208. stabilize: true, // stabilize before displaying the network
  209. stabilizationIterations: 1000, // maximum number of iteration to stabilize
  210. zoomExtentOnStabilize: true,
  211. locale: 'en',
  212. locales: locales,
  213. tooltip: {
  214. delay: 300,
  215. fontColor: 'black',
  216. fontSize: 14, // px
  217. fontFace: 'verdana',
  218. color: {
  219. border: '#666',
  220. background: '#FFFFC6'
  221. }
  222. },
  223. dragNetwork: true,
  224. dragNodes: true,
  225. zoomable: true,
  226. hover: false,
  227. hideEdgesOnDrag: false,
  228. hideNodesOnDrag: false,
  229. width : '100%',
  230. height : '100%',
  231. selectable: true
  232. };
  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. var popupVisible = false;
  1197. // check if the previously selected node is still selected
  1198. if (this.popup !== undefined) {
  1199. if (this.popup.hidden === false) {
  1200. this._checkHidePopup(pointer);
  1201. }
  1202. // if the popup was not hidden above
  1203. if (this.popup.hidden === false) {
  1204. popupVisible = true;
  1205. this.popup.setPosition(pointer.x + 3,pointer.y - 5)
  1206. this.popup.show();
  1207. }
  1208. }
  1209. // if we bind the keyboard to the div, we have to highlight it to use it. This highlights it on mouse over
  1210. if (this.constants.keyboard.bindToWindow == false && this.constants.keyboard.enabled == true) {
  1211. this.frame.focus();
  1212. }
  1213. // start a timeout that will check if the mouse is positioned above an element
  1214. if (popupVisible === false) {
  1215. var me = this;
  1216. var checkShow = function () {
  1217. me._checkShowPopup(pointer);
  1218. };
  1219. if (this.popupTimer) {
  1220. clearInterval(this.popupTimer); // stop any running calculationTimer
  1221. }
  1222. if (!this.drag.dragging) {
  1223. this.popupTimer = setTimeout(checkShow, this.constants.tooltip.delay);
  1224. }
  1225. }
  1226. /**
  1227. * Adding hover highlights
  1228. */
  1229. if (this.constants.hover == true) {
  1230. // removing all hover highlights
  1231. for (var edgeId in this.hoverObj.edges) {
  1232. if (this.hoverObj.edges.hasOwnProperty(edgeId)) {
  1233. this.hoverObj.edges[edgeId].hover = false;
  1234. delete this.hoverObj.edges[edgeId];
  1235. }
  1236. }
  1237. // adding hover highlights
  1238. var obj = this._getNodeAt(pointer);
  1239. if (obj == null) {
  1240. obj = this._getEdgeAt(pointer);
  1241. }
  1242. if (obj != null) {
  1243. this._hoverObject(obj);
  1244. }
  1245. // removing all node hover highlights except for the selected one.
  1246. for (var nodeId in this.hoverObj.nodes) {
  1247. if (this.hoverObj.nodes.hasOwnProperty(nodeId)) {
  1248. if (obj instanceof Node && obj.id != nodeId || obj instanceof Edge || obj == null) {
  1249. this._blurObject(this.hoverObj.nodes[nodeId]);
  1250. delete this.hoverObj.nodes[nodeId];
  1251. }
  1252. }
  1253. }
  1254. this.redraw();
  1255. }
  1256. };
  1257. /**
  1258. * Check if there is an element on the given position in the network
  1259. * (a node or edge). If so, and if this element has a title,
  1260. * show a popup window with its title.
  1261. *
  1262. * @param {{x:Number, y:Number}} pointer
  1263. * @private
  1264. */
  1265. Network.prototype._checkShowPopup = function (pointer) {
  1266. var obj = {
  1267. left: this._XconvertDOMtoCanvas(pointer.x),
  1268. top: this._YconvertDOMtoCanvas(pointer.y),
  1269. right: this._XconvertDOMtoCanvas(pointer.x),
  1270. bottom: this._YconvertDOMtoCanvas(pointer.y)
  1271. };
  1272. var id;
  1273. var previousPopupObjId = this.popupObj === undefined ? "" : this.popupObj.id;
  1274. var nodeUnderCursor = false;
  1275. var popupType = "node";
  1276. if (this.popupObj == undefined) {
  1277. // search the nodes for overlap, select the top one in case of multiple nodes
  1278. var nodes = this.nodes;
  1279. var overlappingNodes = [];
  1280. for (id in nodes) {
  1281. if (nodes.hasOwnProperty(id)) {
  1282. var node = nodes[id];
  1283. if (node.isOverlappingWith(obj)) {
  1284. if (node.getTitle() !== undefined) {
  1285. overlappingNodes.push(id);
  1286. }
  1287. }
  1288. }
  1289. }
  1290. if (overlappingNodes.length > 0) {
  1291. // if there are overlapping nodes, select the last one, this is the
  1292. // one which is drawn on top of the others
  1293. this.popupObj = this.nodes[overlappingNodes[overlappingNodes.length - 1]];
  1294. // if you hover over a node, the title of the edge is not supposed to be shown.
  1295. nodeUnderCursor = true;
  1296. }
  1297. }
  1298. if (this.popupObj === undefined && nodeUnderCursor == false) {
  1299. // search the edges for overlap
  1300. var edges = this.edges;
  1301. var overlappingEdges = [];
  1302. for (id in edges) {
  1303. if (edges.hasOwnProperty(id)) {
  1304. var edge = edges[id];
  1305. if (edge.connected && (edge.getTitle() !== undefined) &&
  1306. edge.isOverlappingWith(obj)) {
  1307. overlappingEdges.push(id);
  1308. }
  1309. }
  1310. }
  1311. if (overlappingEdges.length > 0) {
  1312. this.popupObj = this.edges[overlappingEdges[overlappingEdges.length - 1]];
  1313. popupType = "edge";
  1314. }
  1315. }
  1316. if (this.popupObj) {
  1317. // show popup message window
  1318. if (this.popupObj.id != previousPopupObjId) {
  1319. if (this.popup === undefined) {
  1320. this.popup = new Popup(this.frame, this.constants.tooltip);
  1321. }
  1322. this.popup.popupTargetType = popupType;
  1323. this.popup.popupTargetId = this.popupObj.id;
  1324. // adjust a small offset such that the mouse cursor is located in the
  1325. // bottom left location of the popup, and you can easily move over the
  1326. // popup area
  1327. this.popup.setPosition(pointer.x + 3, pointer.y - 5);
  1328. this.popup.setText(this.popupObj.getTitle());
  1329. this.popup.show();
  1330. }
  1331. }
  1332. else {
  1333. if (this.popup) {
  1334. this.popup.hide();
  1335. }
  1336. }
  1337. };
  1338. /**
  1339. * Check if the popup must be hidden, which is the case when the mouse is no
  1340. * longer hovering on the object
  1341. * @param {{x:Number, y:Number}} pointer
  1342. * @private
  1343. */
  1344. Network.prototype._checkHidePopup = function (pointer) {
  1345. var pointerObj = {
  1346. left: this._XconvertDOMtoCanvas(pointer.x),
  1347. top: this._YconvertDOMtoCanvas(pointer.y),
  1348. right: this._XconvertDOMtoCanvas(pointer.x),
  1349. bottom: this._YconvertDOMtoCanvas(pointer.y)
  1350. };
  1351. var stillOnObj = false;
  1352. if (this.popup.popupTargetType == 'node') {
  1353. stillOnObj = this.nodes[this.popup.popupTargetId].isOverlappingWith(pointerObj);
  1354. if (stillOnObj === true) {
  1355. var overNode = this._getNodeAt(pointer);
  1356. stillOnObj = overNode.id == this.popup.popupTargetId;
  1357. }
  1358. }
  1359. else {
  1360. if (this._getNodeAt(pointer) === null) {
  1361. stillOnObj = this.edges[this.popup.popupTargetId].isOverlappingWith(pointerObj);
  1362. }
  1363. }
  1364. if (stillOnObj === false) {
  1365. this.popupObj = undefined;
  1366. this.popup.hide();
  1367. }
  1368. };
  1369. /**
  1370. * Set a new size for the network
  1371. * @param {string} width Width in pixels or percentage (for example '800px'
  1372. * or '50%')
  1373. * @param {string} height Height in pixels or percentage (for example '400px'
  1374. * or '30%')
  1375. */
  1376. Network.prototype.setSize = function(width, height) {
  1377. var emitEvent = false;
  1378. var oldWidth = this.frame.canvas.width;
  1379. var oldHeight = this.frame.canvas.height;
  1380. if (width != this.constants.width || height != this.constants.height || this.frame.style.width != width || this.frame.style.height != height) {
  1381. this.frame.style.width = width;
  1382. this.frame.style.height = height;
  1383. this.frame.canvas.style.width = '100%';
  1384. this.frame.canvas.style.height = '100%';
  1385. this.frame.canvas.width = this.frame.canvas.clientWidth * this.pixelRatio;
  1386. this.frame.canvas.height = this.frame.canvas.clientHeight * this.pixelRatio;
  1387. this.constants.width = width;
  1388. this.constants.height = height;
  1389. emitEvent = true;
  1390. }
  1391. else {
  1392. // this would adapt the width of the canvas to the width from 100% if and only if
  1393. // there is a change.
  1394. if (this.frame.canvas.width != this.frame.canvas.clientWidth * this.pixelRatio) {
  1395. this.frame.canvas.width = this.frame.canvas.clientWidth * this.pixelRatio;
  1396. emitEvent = true;
  1397. }
  1398. if (this.frame.canvas.height != this.frame.canvas.clientHeight * this.pixelRatio) {
  1399. this.frame.canvas.height = this.frame.canvas.clientHeight * this.pixelRatio;
  1400. emitEvent = true;
  1401. }
  1402. }
  1403. if (emitEvent == true) {
  1404. 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});
  1405. }
  1406. };
  1407. /**
  1408. * Set a data set with nodes for the network
  1409. * @param {Array | DataSet | DataView} nodes The data containing the nodes.
  1410. * @private
  1411. */
  1412. Network.prototype._setNodes = function(nodes) {
  1413. var oldNodesData = this.nodesData;
  1414. if (nodes instanceof DataSet || nodes instanceof DataView) {
  1415. this.nodesData = nodes;
  1416. }
  1417. else if (Array.isArray(nodes)) {
  1418. this.nodesData = new DataSet();
  1419. this.nodesData.add(nodes);
  1420. }
  1421. else if (!nodes) {
  1422. this.nodesData = new DataSet();
  1423. }
  1424. else {
  1425. throw new TypeError('Array or DataSet expected');
  1426. }
  1427. if (oldNodesData) {
  1428. // unsubscribe from old dataset
  1429. util.forEach(this.nodesListeners, function (callback, event) {
  1430. oldNodesData.off(event, callback);
  1431. });
  1432. }
  1433. // remove drawn nodes
  1434. this.nodes = {};
  1435. if (this.nodesData) {
  1436. // subscribe to new dataset
  1437. var me = this;
  1438. util.forEach(this.nodesListeners, function (callback, event) {
  1439. me.nodesData.on(event, callback);
  1440. });
  1441. // draw all new nodes
  1442. var ids = this.nodesData.getIds();
  1443. this._addNodes(ids);
  1444. }
  1445. this._updateSelection();
  1446. };
  1447. /**
  1448. * Add nodes
  1449. * @param {Number[] | String[]} ids
  1450. * @private
  1451. */
  1452. Network.prototype._addNodes = function(ids) {
  1453. var id;
  1454. for (var i = 0, len = ids.length; i < len; i++) {
  1455. id = ids[i];
  1456. var data = this.nodesData.get(id);
  1457. var node = new Node(data, this.images, this.groups, this.constants);
  1458. this.nodes[id] = node; // note: this may replace an existing node
  1459. if ((node.xFixed == false || node.yFixed == false) && (node.x === null || node.y === null)) {
  1460. var radius = 10 * 0.1*ids.length + 10;
  1461. var angle = 2 * Math.PI * Math.random();
  1462. if (node.xFixed == false) {node.x = radius * Math.cos(angle);}
  1463. if (node.yFixed == false) {node.y = radius * Math.sin(angle);}
  1464. }
  1465. this.moving = true;
  1466. }
  1467. this._updateNodeIndexList();
  1468. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  1469. this._resetLevels();
  1470. this._setupHierarchicalLayout();
  1471. }
  1472. this._updateCalculationNodes();
  1473. this._reconnectEdges();
  1474. this._updateValueRange(this.nodes);
  1475. this.updateLabels();
  1476. };
  1477. /**
  1478. * Update existing nodes, or create them when not yet existing
  1479. * @param {Number[] | String[]} ids
  1480. * @private
  1481. */
  1482. Network.prototype._updateNodes = function(ids,changedData) {
  1483. var nodes = this.nodes;
  1484. for (var i = 0, len = ids.length; i < len; i++) {
  1485. var id = ids[i];
  1486. var node = nodes[id];
  1487. var data = changedData[i];
  1488. if (node) {
  1489. // update node
  1490. node.setProperties(data, this.constants);
  1491. }
  1492. else {
  1493. // create node
  1494. node = new Node(properties, this.images, this.groups, this.constants);
  1495. nodes[id] = node;
  1496. }
  1497. }
  1498. this.moving = true;
  1499. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  1500. this._resetLevels();
  1501. this._setupHierarchicalLayout();
  1502. }
  1503. this._updateNodeIndexList();
  1504. this._updateValueRange(nodes);
  1505. this._markAllEdgesAsDirty();
  1506. };
  1507. Network.prototype._markAllEdgesAsDirty = function() {
  1508. for (var edgeId in this.edges) {
  1509. this.edges[edgeId].colorDirty = true;
  1510. }
  1511. }
  1512. /**
  1513. * Remove existing nodes. If nodes do not exist, the method will just ignore it.
  1514. * @param {Number[] | String[]} ids
  1515. * @private
  1516. */
  1517. Network.prototype._removeNodes = function(ids) {
  1518. var nodes = this.nodes;
  1519. // remove from selection
  1520. for (var i = 0, len = ids.length; i < len; i++) {
  1521. if (this.selectionObj.nodes[ids[i]] !== undefined) {
  1522. this.nodes[ids[i]].unselect();
  1523. this._removeFromSelection(this.nodes[ids[i]]);
  1524. }
  1525. }
  1526. for (var i = 0, len = ids.length; i < len; i++) {
  1527. var id = ids[i];
  1528. delete nodes[id];
  1529. }
  1530. this._updateNodeIndexList();
  1531. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  1532. this._resetLevels();
  1533. this._setupHierarchicalLayout();
  1534. }
  1535. this._updateCalculationNodes();
  1536. this._reconnectEdges();
  1537. this._updateSelection();
  1538. this._updateValueRange(nodes);
  1539. };
  1540. /**
  1541. * Load edges by reading the data table
  1542. * @param {Array | DataSet | DataView} edges The data containing the edges.
  1543. * @private
  1544. * @private
  1545. */
  1546. Network.prototype._setEdges = function(edges) {
  1547. var oldEdgesData = this.edgesData;
  1548. if (edges instanceof DataSet || edges instanceof DataView) {
  1549. this.edgesData = edges;
  1550. }
  1551. else if (Array.isArray(edges)) {
  1552. this.edgesData = new DataSet();
  1553. this.edgesData.add(edges);
  1554. }
  1555. else if (!edges) {
  1556. this.edgesData = new DataSet();
  1557. }
  1558. else {
  1559. throw new TypeError('Array or DataSet expected');
  1560. }
  1561. if (oldEdgesData) {
  1562. // unsubscribe from old dataset
  1563. util.forEach(this.edgesListeners, function (callback, event) {
  1564. oldEdgesData.off(event, callback);
  1565. });
  1566. }
  1567. // remove drawn edges
  1568. this.edges = {};
  1569. if (this.edgesData) {
  1570. // subscribe to new dataset
  1571. var me = this;
  1572. util.forEach(this.edgesListeners, function (callback, event) {
  1573. me.edgesData.on(event, callback);
  1574. });
  1575. // draw all new nodes
  1576. var ids = this.edgesData.getIds();
  1577. this._addEdges(ids);
  1578. }
  1579. this._reconnectEdges();
  1580. };
  1581. /**
  1582. * Add edges
  1583. * @param {Number[] | String[]} ids
  1584. * @private
  1585. */
  1586. Network.prototype._addEdges = function (ids) {
  1587. var edges = this.edges,
  1588. edgesData = this.edgesData;
  1589. for (var i = 0, len = ids.length; i < len; i++) {
  1590. var id = ids[i];
  1591. var oldEdge = edges[id];
  1592. if (oldEdge) {
  1593. oldEdge.disconnect();
  1594. }
  1595. var data = edgesData.get(id, {"showInternalIds" : true});
  1596. edges[id] = new Edge(data, this, this.constants);
  1597. }
  1598. this.moving = true;
  1599. this._updateValueRange(edges);
  1600. this._createBezierNodes();
  1601. this._updateCalculationNodes();
  1602. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  1603. this._resetLevels();
  1604. this._setupHierarchicalLayout();
  1605. }
  1606. };
  1607. /**
  1608. * Update existing edges, or create them when not yet existing
  1609. * @param {Number[] | String[]} ids
  1610. * @private
  1611. */
  1612. Network.prototype._updateEdges = function (ids) {
  1613. var edges = this.edges,
  1614. edgesData = this.edgesData;
  1615. for (var i = 0, len = ids.length; i < len; i++) {
  1616. var id = ids[i];
  1617. var data = edgesData.get(id);
  1618. var edge = edges[id];
  1619. if (edge) {
  1620. // update edge
  1621. edge.disconnect();
  1622. edge.setProperties(data, this.constants);
  1623. edge.connect();
  1624. }
  1625. else {
  1626. // create edge
  1627. edge = new Edge(data, this, this.constants);
  1628. this.edges[id] = edge;
  1629. }
  1630. }
  1631. this._createBezierNodes();
  1632. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  1633. this._resetLevels();
  1634. this._setupHierarchicalLayout();
  1635. }
  1636. this.moving = true;
  1637. this._updateValueRange(edges);
  1638. };
  1639. /**
  1640. * Remove existing edges. Non existing ids will be ignored
  1641. * @param {Number[] | String[]} ids
  1642. * @private
  1643. */
  1644. Network.prototype._removeEdges = function (ids) {
  1645. var edges = this.edges;
  1646. // remove from selection
  1647. for (var i = 0, len = ids.length; i < len; i++) {
  1648. if (this.selectionObj.edges[ids[i]] !== undefined) {
  1649. edges[ids[i]].unselect();
  1650. this._removeFromSelection(edges[ids[i]]);
  1651. }
  1652. }
  1653. for (var i = 0, len = ids.length; i < len; i++) {
  1654. var id = ids[i];
  1655. var edge = edges[id];
  1656. if (edge) {
  1657. if (edge.via != null) {
  1658. delete this.sectors['support']['nodes'][edge.via.id];
  1659. }
  1660. edge.disconnect();
  1661. delete edges[id];
  1662. }
  1663. }
  1664. this.moving = true;
  1665. this._updateValueRange(edges);
  1666. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  1667. this._resetLevels();
  1668. this._setupHierarchicalLayout();
  1669. }
  1670. this._updateCalculationNodes();
  1671. };
  1672. /**
  1673. * Reconnect all edges
  1674. * @private
  1675. */
  1676. Network.prototype._reconnectEdges = function() {
  1677. var id,
  1678. nodes = this.nodes,
  1679. edges = this.edges;
  1680. for (id in nodes) {
  1681. if (nodes.hasOwnProperty(id)) {
  1682. nodes[id].edges = [];
  1683. nodes[id].dynamicEdges = [];
  1684. }
  1685. }
  1686. for (id in edges) {
  1687. if (edges.hasOwnProperty(id)) {
  1688. var edge = edges[id];
  1689. edge.from = null;
  1690. edge.to = null;
  1691. edge.connect();
  1692. }
  1693. }
  1694. };
  1695. /**
  1696. * Update the values of all object in the given array according to the current
  1697. * value range of the objects in the array.
  1698. * @param {Object} obj An object containing a set of Edges or Nodes
  1699. * The objects must have a method getValue() and
  1700. * setValueRange(min, max).
  1701. * @private
  1702. */
  1703. Network.prototype._updateValueRange = function(obj) {
  1704. var id;
  1705. // determine the range of the objects
  1706. var valueMin = undefined;
  1707. var valueMax = undefined;
  1708. var valueTotal = 0;
  1709. for (id in obj) {
  1710. if (obj.hasOwnProperty(id)) {
  1711. var value = obj[id].getValue();
  1712. if (value !== undefined) {
  1713. valueMin = (valueMin === undefined) ? value : Math.min(value, valueMin);
  1714. valueMax = (valueMax === undefined) ? value : Math.max(value, valueMax);
  1715. valueTotal += value;
  1716. }
  1717. }
  1718. }
  1719. // adjust the range of all objects
  1720. if (valueMin !== undefined && valueMax !== undefined) {
  1721. for (id in obj) {
  1722. if (obj.hasOwnProperty(id)) {
  1723. obj[id].setValueRange(valueMin, valueMax, valueTotal);
  1724. }
  1725. }
  1726. }
  1727. };
  1728. /**
  1729. * Redraw the network with the current data
  1730. * chart will be resized too.
  1731. */
  1732. Network.prototype.redraw = function() {
  1733. this.setSize(this.constants.width, this.constants.height);
  1734. this._redraw();
  1735. };
  1736. /**
  1737. * Redraw the network with the current data
  1738. * @param hidden | used to get the first estimate of the node sizes. only the nodes are drawn after which they are quickly drawn over.
  1739. * @private
  1740. */
  1741. Network.prototype._redraw = function(hidden) {
  1742. var ctx = this.frame.canvas.getContext('2d');
  1743. ctx.setTransform(this.pixelRatio, 0, 0, this.pixelRatio, 0, 0);
  1744. // clear the canvas
  1745. var w = this.frame.canvas.clientWidth;
  1746. var h = this.frame.canvas.clientHeight;
  1747. ctx.clearRect(0, 0, w, h);
  1748. // set scaling and translation
  1749. ctx.save();
  1750. ctx.translate(this.translation.x, this.translation.y);
  1751. ctx.scale(this.scale, this.scale);
  1752. this.canvasTopLeft = {
  1753. "x": this._XconvertDOMtoCanvas(0),
  1754. "y": this._YconvertDOMtoCanvas(0)
  1755. };
  1756. this.canvasBottomRight = {
  1757. "x": this._XconvertDOMtoCanvas(this.frame.canvas.clientWidth),
  1758. "y": this._YconvertDOMtoCanvas(this.frame.canvas.clientHeight)
  1759. };
  1760. if (!(hidden == true)) {
  1761. this._doInAllSectors("_drawAllSectorNodes", ctx);
  1762. if (this.drag.dragging == false || this.drag.dragging === undefined || this.constants.hideEdgesOnDrag == false) {
  1763. this._doInAllSectors("_drawEdges", ctx);
  1764. }
  1765. }
  1766. if (this.drag.dragging == false || this.drag.dragging === undefined || this.constants.hideNodesOnDrag == false) {
  1767. this._doInAllSectors("_drawNodes",ctx,false);
  1768. }
  1769. if (!(hidden == true)) {
  1770. if (this.controlNodesActive == true) {
  1771. this._doInAllSectors("_drawControlNodes", ctx);
  1772. }
  1773. }
  1774. // this._doInSupportSector("_drawNodes",ctx,true);
  1775. // this._drawTree(ctx,"#F00F0F");
  1776. // restore original scaling and translation
  1777. ctx.restore();
  1778. if (hidden == true) {
  1779. ctx.clearRect(0, 0, w, h);
  1780. }
  1781. };
  1782. /**
  1783. * Set the translation of the network
  1784. * @param {Number} offsetX Horizontal offset
  1785. * @param {Number} offsetY Vertical offset
  1786. * @private
  1787. */
  1788. Network.prototype._setTranslation = function(offsetX, offsetY) {
  1789. if (this.translation === undefined) {
  1790. this.translation = {
  1791. x: 0,
  1792. y: 0
  1793. };
  1794. }
  1795. if (offsetX !== undefined) {
  1796. this.translation.x = offsetX;
  1797. }
  1798. if (offsetY !== undefined) {
  1799. this.translation.y = offsetY;
  1800. }
  1801. this.emit('viewChanged');
  1802. };
  1803. /**
  1804. * Get the translation of the network
  1805. * @return {Object} translation An object with parameters x and y, both a number
  1806. * @private
  1807. */
  1808. Network.prototype._getTranslation = function() {
  1809. return {
  1810. x: this.translation.x,
  1811. y: this.translation.y
  1812. };
  1813. };
  1814. /**
  1815. * Scale the network
  1816. * @param {Number} scale Scaling factor 1.0 is unscaled
  1817. * @private
  1818. */
  1819. Network.prototype._setScale = function(scale) {
  1820. this.scale = scale;
  1821. };
  1822. /**
  1823. * Get the current scale of the network
  1824. * @return {Number} scale Scaling factor 1.0 is unscaled
  1825. * @private
  1826. */
  1827. Network.prototype._getScale = function() {
  1828. return this.scale;
  1829. };
  1830. /**
  1831. * Convert the X coordinate in DOM-space (coordinate point in browser relative to the container div) to
  1832. * the X coordinate in canvas-space (the simulation sandbox, which the camera looks upon)
  1833. * @param {number} x
  1834. * @returns {number}
  1835. * @private
  1836. */
  1837. Network.prototype._XconvertDOMtoCanvas = function(x) {
  1838. return (x - this.translation.x) / this.scale;
  1839. };
  1840. /**
  1841. * Convert the X coordinate in canvas-space (the simulation sandbox, which the camera looks upon) to
  1842. * the X coordinate in DOM-space (coordinate point in browser relative to the container div)
  1843. * @param {number} x
  1844. * @returns {number}
  1845. * @private
  1846. */
  1847. Network.prototype._XconvertCanvasToDOM = function(x) {
  1848. return x * this.scale + this.translation.x;
  1849. };
  1850. /**
  1851. * Convert the Y coordinate in DOM-space (coordinate point in browser relative to the container div) to
  1852. * the Y coordinate in canvas-space (the simulation sandbox, which the camera looks upon)
  1853. * @param {number} y
  1854. * @returns {number}
  1855. * @private
  1856. */
  1857. Network.prototype._YconvertDOMtoCanvas = function(y) {
  1858. return (y - this.translation.y) / this.scale;
  1859. };
  1860. /**
  1861. * Convert the Y coordinate in canvas-space (the simulation sandbox, which the camera looks upon) to
  1862. * the Y coordinate in DOM-space (coordinate point in browser relative to the container div)
  1863. * @param {number} y
  1864. * @returns {number}
  1865. * @private
  1866. */
  1867. Network.prototype._YconvertCanvasToDOM = function(y) {
  1868. return y * this.scale + this.translation.y ;
  1869. };
  1870. /**
  1871. *
  1872. * @param {object} pos = {x: number, y: number}
  1873. * @returns {{x: number, y: number}}
  1874. * @constructor
  1875. */
  1876. Network.prototype.canvasToDOM = function (pos) {
  1877. return {x: this._XconvertCanvasToDOM(pos.x), y: this._YconvertCanvasToDOM(pos.y)};
  1878. };
  1879. /**
  1880. *
  1881. * @param {object} pos = {x: number, y: number}
  1882. * @returns {{x: number, y: number}}
  1883. * @constructor
  1884. */
  1885. Network.prototype.DOMtoCanvas = function (pos) {
  1886. return {x: this._XconvertDOMtoCanvas(pos.x), y: this._YconvertDOMtoCanvas(pos.y)};
  1887. };
  1888. /**
  1889. * Redraw all nodes
  1890. * The 2d context of a HTML canvas can be retrieved by canvas.getContext('2d');
  1891. * @param {CanvasRenderingContext2D} ctx
  1892. * @param {Boolean} [alwaysShow]
  1893. * @private
  1894. */
  1895. Network.prototype._drawNodes = function(ctx,alwaysShow) {
  1896. if (alwaysShow === undefined) {
  1897. alwaysShow = false;
  1898. }
  1899. // first draw the unselected nodes
  1900. var nodes = this.nodes;
  1901. var selected = [];
  1902. for (var id in nodes) {
  1903. if (nodes.hasOwnProperty(id)) {
  1904. nodes[id].setScaleAndPos(this.scale,this.canvasTopLeft,this.canvasBottomRight);
  1905. if (nodes[id].isSelected()) {
  1906. selected.push(id);
  1907. }
  1908. else {
  1909. if (nodes[id].inArea() || alwaysShow) {
  1910. nodes[id].draw(ctx);
  1911. }
  1912. }
  1913. }
  1914. }
  1915. // draw the selected nodes on top
  1916. for (var s = 0, sMax = selected.length; s < sMax; s++) {
  1917. if (nodes[selected[s]].inArea() || alwaysShow) {
  1918. nodes[selected[s]].draw(ctx);
  1919. }
  1920. }
  1921. };
  1922. /**
  1923. * Redraw all edges
  1924. * The 2d context of a HTML canvas can be retrieved by canvas.getContext('2d');
  1925. * @param {CanvasRenderingContext2D} ctx
  1926. * @private
  1927. */
  1928. Network.prototype._drawEdges = function(ctx) {
  1929. var edges = this.edges;
  1930. for (var id in edges) {
  1931. if (edges.hasOwnProperty(id)) {
  1932. var edge = edges[id];
  1933. edge.setScale(this.scale);
  1934. if (edge.connected) {
  1935. edges[id].draw(ctx);
  1936. }
  1937. }
  1938. }
  1939. };
  1940. /**
  1941. * Redraw all edges
  1942. * The 2d context of a HTML canvas can be retrieved by canvas.getContext('2d');
  1943. * @param {CanvasRenderingContext2D} ctx
  1944. * @private
  1945. */
  1946. Network.prototype._drawControlNodes = function(ctx) {
  1947. var edges = this.edges;
  1948. for (var id in edges) {
  1949. if (edges.hasOwnProperty(id)) {
  1950. edges[id]._drawControlNodes(ctx);
  1951. }
  1952. }
  1953. };
  1954. /**
  1955. * Find a stable position for all nodes
  1956. * @private
  1957. */
  1958. Network.prototype._stabilize = function() {
  1959. if (this.constants.freezeForStabilization == true) {
  1960. this._freezeDefinedNodes();
  1961. }
  1962. // find stable position
  1963. var count = 0;
  1964. while (this.moving && count < this.constants.stabilizationIterations) {
  1965. this._physicsTick();
  1966. // TODO: cleanup
  1967. //if (count % 100 == 0) {
  1968. // console.log("stabilizationIterations",count);
  1969. //}
  1970. count++;
  1971. }
  1972. if (this.constants.zoomExtentOnStabilize == true) {
  1973. this.zoomExtent({duration:0}, false, true);
  1974. }
  1975. if (this.constants.freezeForStabilization == true) {
  1976. this._restoreFrozenNodes();
  1977. }
  1978. this.emit("stabilizationIterationsDone");
  1979. };
  1980. /**
  1981. * When initializing and stabilizing, we can freeze nodes with a predefined position. This greatly speeds up stabilization
  1982. * because only the supportnodes for the smoothCurves have to settle.
  1983. *
  1984. * @private
  1985. */
  1986. Network.prototype._freezeDefinedNodes = function() {
  1987. var nodes = this.nodes;
  1988. for (var id in nodes) {
  1989. if (nodes.hasOwnProperty(id)) {
  1990. if (nodes[id].x != null && nodes[id].y != null) {
  1991. nodes[id].fixedData.x = nodes[id].xFixed;
  1992. nodes[id].fixedData.y = nodes[id].yFixed;
  1993. nodes[id].xFixed = true;
  1994. nodes[id].yFixed = true;
  1995. }
  1996. }
  1997. }
  1998. };
  1999. /**
  2000. * Unfreezes the nodes that have been frozen by _freezeDefinedNodes.
  2001. *
  2002. * @private
  2003. */
  2004. Network.prototype._restoreFrozenNodes = function() {
  2005. var nodes = this.nodes;
  2006. for (var id in nodes) {
  2007. if (nodes.hasOwnProperty(id)) {
  2008. if (nodes[id].fixedData.x != null) {
  2009. nodes[id].xFixed = nodes[id].fixedData.x;
  2010. nodes[id].yFixed = nodes[id].fixedData.y;
  2011. }
  2012. }
  2013. }
  2014. };
  2015. /**
  2016. * Check if any of the nodes is still moving
  2017. * @param {number} vmin the minimum velocity considered as 'moving'
  2018. * @return {boolean} true if moving, false if non of the nodes is moving
  2019. * @private
  2020. */
  2021. Network.prototype._isMoving = function(vmin) {
  2022. var nodes = this.nodes;
  2023. for (var id in nodes) {
  2024. if (nodes[id] !== undefined) {
  2025. if (nodes[id].isMoving(vmin) == true) {
  2026. return true;
  2027. }
  2028. }
  2029. }
  2030. return false;
  2031. };
  2032. /**
  2033. * /**
  2034. * Perform one discrete step for all nodes
  2035. *
  2036. * @private
  2037. */
  2038. Network.prototype._discreteStepNodes = function() {
  2039. var interval = this.physicsDiscreteStepsize;
  2040. var nodes = this.nodes;
  2041. var nodeId;
  2042. var nodesPresent = false;
  2043. if (this.constants.maxVelocity > 0) {
  2044. for (nodeId in nodes) {
  2045. if (nodes.hasOwnProperty(nodeId)) {
  2046. nodes[nodeId].discreteStepLimited(interval, this.constants.maxVelocity);
  2047. nodesPresent = true;
  2048. }
  2049. }
  2050. }
  2051. else {
  2052. for (nodeId in nodes) {
  2053. if (nodes.hasOwnProperty(nodeId)) {
  2054. nodes[nodeId].discreteStep(interval);
  2055. nodesPresent = true;
  2056. }
  2057. }
  2058. }
  2059. if (nodesPresent == true) {
  2060. var vminCorrected = this.constants.minVelocity / Math.max(this.scale,0.05);
  2061. if (vminCorrected > 0.5*this.constants.maxVelocity) {
  2062. return true;
  2063. }
  2064. else {
  2065. return this._isMoving(vminCorrected);
  2066. }
  2067. }
  2068. return false;
  2069. };
  2070. Network.prototype._revertPhysicsState = function() {
  2071. var nodes = this.nodes;
  2072. for (var nodeId in nodes) {
  2073. if (nodes.hasOwnProperty(nodeId)) {
  2074. nodes[nodeId].revertPosition();
  2075. }
  2076. }
  2077. }
  2078. Network.prototype._revertPhysicsTick = function() {
  2079. this._doInAllActiveSectors("_revertPhysicsState");
  2080. if (this.constants.smoothCurves.enabled == true && this.constants.smoothCurves.dynamic == true) {
  2081. this._doInSupportSector("_revertPhysicsState");
  2082. }
  2083. }
  2084. /**
  2085. * A single simulation step (or "tick") in the physics simulation
  2086. *
  2087. * @private
  2088. */
  2089. Network.prototype._physicsTick = function() {
  2090. if (!this.freezeSimulationEnabled) {
  2091. if (this.moving == true) {
  2092. var mainMovingStatus = false;
  2093. var supportMovingStatus = false;
  2094. this._doInAllActiveSectors("_initializeForceCalculation");
  2095. var mainMoving = this._doInAllActiveSectors("_discreteStepNodes");
  2096. if (this.constants.smoothCurves.enabled == true && this.constants.smoothCurves.dynamic == true) {
  2097. supportMovingStatus = this._doInSupportSector("_discreteStepNodes");
  2098. }
  2099. // gather movement data from all sectors, if one moves, we are NOT stabilzied
  2100. for (var i = 0; i < mainMoving.length; i++) {
  2101. mainMovingStatus = mainMoving[i] || mainMovingStatus;
  2102. }
  2103. // determine if the network has stabilzied
  2104. this.moving = mainMovingStatus || supportMovingStatus;
  2105. if (this.moving == false) {
  2106. this._revertPhysicsTick();
  2107. }
  2108. else {
  2109. // this is here to ensure that there is no start event when the network is already stable.
  2110. if (this.startedStabilization == false) {
  2111. this.emit("startStabilization");
  2112. this.startedStabilization = true;
  2113. }
  2114. }
  2115. this.stabilizationIterations++;
  2116. }
  2117. }
  2118. };
  2119. /**
  2120. * This function runs one step of the animation. It calls an x amount of physics ticks and one render tick.
  2121. * It reschedules itself at the beginning of the function
  2122. *
  2123. * @private
  2124. */
  2125. Network.prototype._animationStep = function() {
  2126. // reset the timer so a new scheduled animation step can be set
  2127. this.timer = undefined;
  2128. // handle the keyboad movement
  2129. this._handleNavigation();
  2130. // check if the physics have settled
  2131. if (this.moving == true) {
  2132. var startTime = Date.now();
  2133. this._physicsTick();
  2134. var physicsTime = Date.now() - startTime;
  2135. // run double speed if it is a little graph
  2136. if ((this.renderTimestep - this.renderTime > 2 * physicsTime || this.runDoubleSpeed == true) && this.moving == true) {
  2137. this._physicsTick();
  2138. // this makes sure there is no jitter. The decision is taken once to run it at double speed.
  2139. if (this.renderTime != 0) {
  2140. this.runDoubleSpeed = true
  2141. }
  2142. }
  2143. }
  2144. var renderStartTime = Date.now();
  2145. this._redraw();
  2146. this.renderTime = Date.now() - renderStartTime;
  2147. // this schedules a new animation step
  2148. this.start();
  2149. };
  2150. if (typeof window !== 'undefined') {
  2151. window.requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame ||
  2152. window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;
  2153. }
  2154. /**
  2155. * Schedule a animation step with the refreshrate interval.
  2156. */
  2157. Network.prototype.start = function() {
  2158. if (this.freezeSimulationEnabled == true) {
  2159. this.moving = false;
  2160. }
  2161. if (this.moving == true || this.xIncrement != 0 || this.yIncrement != 0 || this.zoomIncrement != 0 || this.animating == true) {
  2162. if (!this.timer) {
  2163. if (this.requiresTimeout == true) {
  2164. this.timer = window.setTimeout(this._animationStep.bind(this), this.renderTimestep); // wait this.renderTimeStep milliseconds and perform the animation step function
  2165. }
  2166. else {
  2167. this.timer = window.requestAnimationFrame(this._animationStep.bind(this)); // wait this.renderTimeStep milliseconds and perform the animation step function
  2168. }
  2169. }
  2170. }
  2171. else {
  2172. this._redraw();
  2173. // 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())
  2174. if (this.stabilizationIterations > 1) {
  2175. // trigger the "stabilized" event.
  2176. // The event is triggered on the next tick, to prevent the case that
  2177. // it is fired while initializing the Network, in which case you would not
  2178. // be able to catch it
  2179. var me = this;
  2180. var params = {
  2181. iterations: me.stabilizationIterations
  2182. };
  2183. this.stabilizationIterations = 0;
  2184. this.startedStabilization = false;
  2185. setTimeout(function () {
  2186. me.emit("stabilized", params);
  2187. }, 0);
  2188. }
  2189. else {
  2190. this.stabilizationIterations = 0;
  2191. }
  2192. }
  2193. };
  2194. /**
  2195. * Move the network according to the keyboard presses.
  2196. *
  2197. * @private
  2198. */
  2199. Network.prototype._handleNavigation = function() {
  2200. if (this.xIncrement != 0 || this.yIncrement != 0) {
  2201. var translation = this._getTranslation();
  2202. this._setTranslation(translation.x+this.xIncrement, translation.y+this.yIncrement);
  2203. }
  2204. if (this.zoomIncrement != 0) {
  2205. var center = {
  2206. x: this.frame.canvas.clientWidth / 2,
  2207. y: this.frame.canvas.clientHeight / 2
  2208. };
  2209. this._zoom(this.scale*(1 + this.zoomIncrement), center);
  2210. }
  2211. };
  2212. /**
  2213. * Freeze the _animationStep
  2214. */
  2215. Network.prototype.freezeSimulation = function(freeze) {
  2216. if (freeze == true) {
  2217. this.freezeSimulationEnabled = true;
  2218. this.moving = false;
  2219. }
  2220. else {
  2221. this.freezeSimulationEnabled = false;
  2222. this.moving = true;
  2223. this.start();
  2224. }
  2225. };
  2226. /**
  2227. * This function cleans the support nodes if they are not needed and adds them when they are.
  2228. *
  2229. * @param {boolean} [disableStart]
  2230. * @private
  2231. */
  2232. Network.prototype._configureSmoothCurves = function(disableStart) {
  2233. if (disableStart === undefined) {
  2234. disableStart = true;
  2235. }
  2236. if (this.constants.smoothCurves.enabled == true && this.constants.smoothCurves.dynamic == true) {
  2237. this._createBezierNodes();
  2238. // cleanup unused support nodes
  2239. for (var nodeId in this.sectors['support']['nodes']) {
  2240. if (this.sectors['support']['nodes'].hasOwnProperty(nodeId)) {
  2241. if (this.edges[this.sectors['support']['nodes'][nodeId].parentEdgeId] === undefined) {
  2242. delete this.sectors['support']['nodes'][nodeId];
  2243. }
  2244. }
  2245. }
  2246. }
  2247. else {
  2248. // delete the support nodes
  2249. this.sectors['support']['nodes'] = {};
  2250. for (var edgeId in this.edges) {
  2251. if (this.edges.hasOwnProperty(edgeId)) {
  2252. this.edges[edgeId].via = null;
  2253. }
  2254. }
  2255. }
  2256. this._updateCalculationNodes();
  2257. if (!disableStart) {
  2258. this.moving = true;
  2259. this.start();
  2260. }
  2261. };
  2262. /**
  2263. * Bezier curves require an anchor point to calculate the smooth flow. These points are nodes. These nodes are invisible but
  2264. * are used for the force calculation.
  2265. *
  2266. * @private
  2267. */
  2268. Network.prototype._createBezierNodes = function() {
  2269. if (this.constants.smoothCurves.enabled == true && this.constants.smoothCurves.dynamic == true) {
  2270. for (var edgeId in this.edges) {
  2271. if (this.edges.hasOwnProperty(edgeId)) {
  2272. var edge = this.edges[edgeId];
  2273. if (edge.via == null) {
  2274. var nodeId = "edgeId:".concat(edge.id);
  2275. this.sectors['support']['nodes'][nodeId] = new Node(
  2276. {id:nodeId,
  2277. mass:1,
  2278. shape:'circle',
  2279. image:"",
  2280. internalMultiplier:1
  2281. },{},{},this.constants);
  2282. edge.via = this.sectors['support']['nodes'][nodeId];
  2283. edge.via.parentEdgeId = edge.id;
  2284. edge.positionBezierNode();
  2285. }
  2286. }
  2287. }
  2288. }
  2289. };
  2290. /**
  2291. * load the functions that load the mixins into the prototype.
  2292. *
  2293. * @private
  2294. */
  2295. Network.prototype._initializeMixinLoaders = function () {
  2296. for (var mixin in MixinLoader) {
  2297. if (MixinLoader.hasOwnProperty(mixin)) {
  2298. Network.prototype[mixin] = MixinLoader[mixin];
  2299. }
  2300. }
  2301. };
  2302. /**
  2303. * Load the XY positions of the nodes into the dataset.
  2304. */
  2305. Network.prototype.storePosition = function() {
  2306. console.log("storePosition is depricated: use .storePositions() from now on.")
  2307. this.storePositions();
  2308. };
  2309. /**
  2310. * Load the XY positions of the nodes into the dataset.
  2311. */
  2312. Network.prototype.storePositions = function() {
  2313. var dataArray = [];
  2314. for (var nodeId in this.nodes) {
  2315. if (this.nodes.hasOwnProperty(nodeId)) {
  2316. var node = this.nodes[nodeId];
  2317. var allowedToMoveX = !this.nodes.xFixed;
  2318. var allowedToMoveY = !this.nodes.yFixed;
  2319. if (this.nodesData._data[nodeId].x != Math.round(node.x) || this.nodesData._data[nodeId].y != Math.round(node.y)) {
  2320. dataArray.push({id:nodeId,x:Math.round(node.x),y:Math.round(node.y),allowedToMoveX:allowedToMoveX,allowedToMoveY:allowedToMoveY});
  2321. }
  2322. }
  2323. }
  2324. this.nodesData.update(dataArray);
  2325. };
  2326. /**
  2327. * Return the positions of the nodes.
  2328. */
  2329. Network.prototype.getPositions = function(ids) {
  2330. var dataArray = {};
  2331. if (ids !== undefined) {
  2332. if (Array.isArray(ids) == true) {
  2333. for (var i = 0; i < ids.length; i++) {
  2334. if (this.nodes[ids[i]] !== undefined) {
  2335. var node = this.nodes[ids[i]];
  2336. dataArray[ids[i]] = {x: Math.round(node.x), y: Math.round(node.y)};
  2337. }
  2338. }
  2339. }
  2340. else {
  2341. if (this.nodes[ids] !== undefined) {
  2342. var node = this.nodes[ids];
  2343. dataArray[ids] = {x: Math.round(node.x), y: Math.round(node.y)};
  2344. }
  2345. }
  2346. }
  2347. else {
  2348. for (var nodeId in this.nodes) {
  2349. if (this.nodes.hasOwnProperty(nodeId)) {
  2350. var node = this.nodes[nodeId];
  2351. dataArray[nodeId] = {x: Math.round(node.x), y: Math.round(node.y)};
  2352. }
  2353. }
  2354. }
  2355. return dataArray;
  2356. };
  2357. /**
  2358. * Center a node in view.
  2359. *
  2360. * @param {Number} nodeId
  2361. * @param {Number} [options]
  2362. */
  2363. Network.prototype.focusOnNode = function (nodeId, options) {
  2364. if (this.nodes.hasOwnProperty(nodeId)) {
  2365. if (options === undefined) {
  2366. options = {};
  2367. }
  2368. var nodePosition = {x: this.nodes[nodeId].x, y: this.nodes[nodeId].y};
  2369. options.position = nodePosition;
  2370. options.lockedOnNode = nodeId;
  2371. this.moveTo(options)
  2372. }
  2373. else {
  2374. console.log("This nodeId cannot be found.");
  2375. }
  2376. };
  2377. /**
  2378. *
  2379. * @param {Object} options | options.offset = {x:Number, y:Number} // offset from the center in DOM pixels
  2380. * | options.scale = Number // scale to move to
  2381. * | options.position = {x:Number, y:Number} // position to move to
  2382. * | options.animation = {duration:Number, easingFunction:String} || Boolean // position to move to
  2383. */
  2384. Network.prototype.moveTo = function (options) {
  2385. if (options === undefined) {
  2386. options = {};
  2387. return;
  2388. }
  2389. if (options.offset === undefined) {options.offset = {x: 0, y: 0}; }
  2390. if (options.offset.x === undefined) {options.offset.x = 0; }
  2391. if (options.offset.y === undefined) {options.offset.y = 0; }
  2392. if (options.scale === undefined) {options.scale = this._getScale(); }
  2393. if (options.position === undefined) {options.position = this._getTranslation();}
  2394. if (options.animation === undefined) {options.animation = {duration:0}; }
  2395. if (options.animation === false ) {options.animation = {duration:0}; }
  2396. if (options.animation === true ) {options.animation = {}; }
  2397. if (options.animation.duration === undefined) {options.animation.duration = 1000; } // default duration
  2398. if (options.animation.easingFunction === undefined) {options.animation.easingFunction = "easeInOutQuad"; } // default easing function
  2399. this.animateView(options);
  2400. };
  2401. /**
  2402. *
  2403. * @param {Object} options | options.offset = {x:Number, y:Number} // offset from the center in DOM pixels
  2404. * | options.time = Number // animation time in milliseconds
  2405. * | options.scale = Number // scale to animate to
  2406. * | options.position = {x:Number, y:Number} // position to animate to
  2407. * | options.easingFunction = String // linear, easeInQuad, easeOutQuad, easeInOutQuad,
  2408. * // easeInCubic, easeOutCubic, easeInOutCubic,
  2409. * // easeInQuart, easeOutQuart, easeInOutQuart,
  2410. * // easeInQuint, easeOutQuint, easeInOutQuint
  2411. */
  2412. Network.prototype.animateView = function (options) {
  2413. if (options === undefined) {
  2414. options = {};
  2415. return;
  2416. }
  2417. // release if something focussed on the node
  2418. this.releaseNode();
  2419. if (options.locked == true) {
  2420. this.lockedOnNodeId = options.lockedOnNode;
  2421. this.lockedOnNodeOffset = options.offset;
  2422. }
  2423. // forcefully complete the old animation if it was still running
  2424. if (this.easingTime != 0) {
  2425. this._transitionRedraw(1); // by setting easingtime to 1, we finish the animation.
  2426. }
  2427. this.sourceScale = this._getScale();
  2428. this.sourceTranslation = this._getTranslation();
  2429. this.targetScale = options.scale;
  2430. // set the scale so the viewCenter is based on the correct zoom level. This is overridden in the transitionRedraw
  2431. // but at least then we'll have the target transition
  2432. this._setScale(this.targetScale);
  2433. var viewCenter = this.DOMtoCanvas({x: 0.5 * this.frame.canvas.clientWidth, y: 0.5 * this.frame.canvas.clientHeight});
  2434. var distanceFromCenter = { // offset from view, distance view has to change by these x and y to center the node
  2435. x: viewCenter.x - options.position.x,
  2436. y: viewCenter.y - options.position.y
  2437. };
  2438. this.targetTranslation = {
  2439. x: this.sourceTranslation.x + distanceFromCenter.x * this.targetScale + options.offset.x,
  2440. y: this.sourceTranslation.y + distanceFromCenter.y * this.targetScale + options.offset.y
  2441. };
  2442. // if the time is set to 0, don't do an animation
  2443. if (options.animation.duration == 0) {
  2444. if (this.lockedOnNodeId != null) {
  2445. this._classicRedraw = this._redraw;
  2446. this._redraw = this._lockedRedraw;
  2447. }
  2448. else {
  2449. this._setScale(this.targetScale);
  2450. this._setTranslation(this.targetTranslation.x, this.targetTranslation.y);
  2451. this._redraw();
  2452. }
  2453. }
  2454. else {
  2455. this.animating = true;
  2456. this.animationSpeed = 1 / (this.renderRefreshRate * options.animation.duration * 0.001) || 1 / this.renderRefreshRate;
  2457. this.animationEasingFunction = options.animation.easingFunction;
  2458. this._classicRedraw = this._redraw;
  2459. this._redraw = this._transitionRedraw;
  2460. this._redraw();
  2461. this.start();
  2462. }
  2463. };
  2464. /**
  2465. * used to animate smoothly by hijacking the redraw function.
  2466. * @private
  2467. */
  2468. Network.prototype._lockedRedraw = function () {
  2469. var nodePosition = {x: this.nodes[this.lockedOnNodeId].x, y: this.nodes[this.lockedOnNodeId].y};
  2470. var viewCenter = this.DOMtoCanvas({x: 0.5 * this.frame.canvas.clientWidth, y: 0.5 * this.frame.canvas.clientHeight});
  2471. var distanceFromCenter = { // offset from view, distance view has to change by these x and y to center the node
  2472. x: viewCenter.x - nodePosition.x,
  2473. y: viewCenter.y - nodePosition.y
  2474. };
  2475. var sourceTranslation = this._getTranslation();
  2476. var targetTranslation = {
  2477. x: sourceTranslation.x + distanceFromCenter.x * this.scale + this.lockedOnNodeOffset.x,
  2478. y: sourceTranslation.y + distanceFromCenter.y * this.scale + this.lockedOnNodeOffset.y
  2479. };
  2480. this._setTranslation(targetTranslation.x,targetTranslation.y);
  2481. this._classicRedraw();
  2482. }
  2483. Network.prototype.releaseNode = function () {
  2484. if (this.lockedOnNodeId != null) {
  2485. this._redraw = this._classicRedraw;
  2486. this.lockedOnNodeId = null;
  2487. this.lockedOnNodeOffset = null;
  2488. }
  2489. }
  2490. /**
  2491. *
  2492. * @param easingTime
  2493. * @private
  2494. */
  2495. Network.prototype._transitionRedraw = function (easingTime) {
  2496. this.easingTime = easingTime || this.easingTime + this.animationSpeed;
  2497. this.easingTime += this.animationSpeed;
  2498. var progress = util.easingFunctions[this.animationEasingFunction](this.easingTime);
  2499. this._setScale(this.sourceScale + (this.targetScale - this.sourceScale) * progress);
  2500. this._setTranslation(
  2501. this.sourceTranslation.x + (this.targetTranslation.x - this.sourceTranslation.x) * progress,
  2502. this.sourceTranslation.y + (this.targetTranslation.y - this.sourceTranslation.y) * progress
  2503. );
  2504. this._classicRedraw();
  2505. // cleanup
  2506. if (this.easingTime >= 1.0) {
  2507. this.animating = false;
  2508. this.easingTime = 0;
  2509. if (this.lockedOnNodeId != null) {
  2510. this._redraw = this._lockedRedraw;
  2511. }
  2512. else {
  2513. this._redraw = this._classicRedraw;
  2514. }
  2515. this.emit("animationFinished");
  2516. }
  2517. };
  2518. Network.prototype._classicRedraw = function () {
  2519. // placeholder function to be overloaded by animations;
  2520. };
  2521. /**
  2522. * Returns true when the Network is active.
  2523. * @returns {boolean}
  2524. */
  2525. Network.prototype.isActive = function () {
  2526. return !this.activator || this.activator.active;
  2527. };
  2528. /**
  2529. * Sets the scale
  2530. * @returns {Number}
  2531. */
  2532. Network.prototype.setScale = function () {
  2533. return this._setScale();
  2534. };
  2535. /**
  2536. * Returns the scale
  2537. * @returns {Number}
  2538. */
  2539. Network.prototype.getScale = function () {
  2540. return this._getScale();
  2541. };
  2542. /**
  2543. * Returns the scale
  2544. * @returns {Number}
  2545. */
  2546. Network.prototype.getCenterCoordinates = function () {
  2547. return this.DOMtoCanvas({x: 0.5 * this.frame.canvas.clientWidth, y: 0.5 * this.frame.canvas.clientHeight});
  2548. };
  2549. Network.prototype.getBoundingBox = function(nodeId) {
  2550. if (this.nodes[nodeId] !== undefined) {
  2551. return this.nodes[nodeId].boundingBox;
  2552. }
  2553. }
  2554. Network.prototype.getConnectedNodes = function(nodeId) {
  2555. var nodeList = [];
  2556. if (this.nodes[nodeId] !== undefined) {
  2557. var node = this.nodes[nodeId];
  2558. var nodeObj = {nodeId : true}; // used to quickly check if node already exists
  2559. for (var i = 0; i < node.edges.length; i++) {
  2560. var edge = node.edges[i];
  2561. if (edge.toId == nodeId) {
  2562. if (nodeObj[edge.fromId] === undefined) {
  2563. nodeList.push(edge.fromId);
  2564. nodeObj[edge.fromId] = true;
  2565. }
  2566. }
  2567. else if (edge.fromId == nodeId) {
  2568. if (nodeObj[edge.toId] === undefined) {
  2569. nodeList.push(edge.toId)
  2570. nodeObj[edge.toId] = true;
  2571. }
  2572. }
  2573. }
  2574. }
  2575. return nodeList;
  2576. }
  2577. module.exports = Network;