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.

2967 lines
87 KiB

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