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.

2857 lines
86 KiB

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