vis.js is a dynamic, browser-based visualization library
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2967 lines
87 KiB

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