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.

2882 lines
86 KiB

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