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.

2904 lines
85 KiB

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