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.

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