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.

2842 lines
86 KiB

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