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.

2972 lines
89 KiB

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