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.

2968 lines
87 KiB

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