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.

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