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.

2714 lines
81 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 = new Hammer(this.frame.canvas);
  712. this.hammer.get('pinch').set({enable: true});
  713. this.hammer.on('tap', me._onTap.bind(me) );
  714. this.hammer.on('doubletap', me._onDoubleTap.bind(me) );
  715. this.hammer.on('press', me._onHold.bind(me) );
  716. this.hammer.on('pinch', me._onPinch.bind(me) );
  717. hammerUtil.onTouch(this.hammer, me._onTouch.bind(me));
  718. this.hammer.on('panstart', me._onDragStart.bind(me) );
  719. this.hammer.on('panmove', me._onDrag.bind(me) );
  720. this.hammer.on('panend', me._onDragEnd.bind(me) );
  721. this.frame.canvas.addEventListener('mousemove', me._onMouseMoveTitle.bind(me) );
  722. this.frame.canvas.addEventListener('mousewheel', me._onMouseWheel.bind(me));
  723. this.frame.canvas.addEventListener('DOMMouseScroll', me._onMouseWheel.bind(me)); // for FF
  724. // add the frame to the container element
  725. this.containerElement.appendChild(this.frame);
  726. };
  727. /**
  728. * Binding the keys for keyboard navigation. These functions are defined in the NavigationMixin
  729. * @private
  730. */
  731. Network.prototype._createKeyBinds = function() {
  732. var me = this;
  733. if (this.keycharm !== undefined) {
  734. this.keycharm.destroy();
  735. }
  736. this.keycharm = keycharm();
  737. this.keycharm.reset();
  738. if (this.constants.keyboard.enabled && this.isActive()) {
  739. this.keycharm.bind('up', this._moveUp.bind(me) , 'keydown');
  740. this.keycharm.bind('up', this._yStopMoving.bind(me), 'keyup');
  741. this.keycharm.bind('down', this._moveDown.bind(me) , 'keydown');
  742. this.keycharm.bind('down', this._yStopMoving.bind(me), 'keyup');
  743. this.keycharm.bind('left', this._moveLeft.bind(me) , 'keydown');
  744. this.keycharm.bind('left', this._xStopMoving.bind(me), 'keyup');
  745. this.keycharm.bind('right',this._moveRight.bind(me), 'keydown');
  746. this.keycharm.bind('right',this._xStopMoving.bind(me), 'keyup');
  747. this.keycharm.bind('=', this._zoomIn.bind(me), 'keydown');
  748. this.keycharm.bind('=', this._stopZoom.bind(me), 'keyup');
  749. this.keycharm.bind('num+', this._zoomIn.bind(me), 'keydown');
  750. this.keycharm.bind('num+', this._stopZoom.bind(me), 'keyup');
  751. this.keycharm.bind('num-', this._zoomOut.bind(me), 'keydown');
  752. this.keycharm.bind('num-', this._stopZoom.bind(me), 'keyup');
  753. this.keycharm.bind('-', this._zoomOut.bind(me), 'keydown');
  754. this.keycharm.bind('-', this._stopZoom.bind(me), 'keyup');
  755. this.keycharm.bind('[', this._zoomIn.bind(me), 'keydown');
  756. this.keycharm.bind('[', this._stopZoom.bind(me), 'keyup');
  757. this.keycharm.bind(']', this._zoomOut.bind(me), 'keydown');
  758. this.keycharm.bind(']', this._stopZoom.bind(me), 'keyup');
  759. this.keycharm.bind('pageup',this._zoomIn.bind(me), 'keydown');
  760. this.keycharm.bind('pageup',this._stopZoom.bind(me), 'keyup');
  761. this.keycharm.bind('pagedown',this._zoomOut.bind(me),'keydown');
  762. this.keycharm.bind('pagedown',this._stopZoom.bind(me), 'keyup');
  763. }
  764. if (this.constants.dataManipulation.enabled == true) {
  765. this.keycharm.bind('esc',this._createManipulatorBar.bind(me));
  766. this.keycharm.bind('delete',this._deleteSelected.bind(me));
  767. }
  768. };
  769. /**
  770. * Cleans up all bindings of the network, removing it fully from the memory IF the variable is set to null after calling this function.
  771. * var network = new vis.Network(..);
  772. * network.destroy();
  773. * network = null;
  774. */
  775. Network.prototype.destroy = function() {
  776. this.start = function () {};
  777. this.redraw = function () {};
  778. this.timer = false;
  779. // cleanup physicsConfiguration if it exists
  780. this._cleanupPhysicsConfiguration();
  781. // remove keybindings
  782. this.keycharm.reset();
  783. // clear hammer bindings
  784. this.hammer.destroy();
  785. // clear events
  786. this.off();
  787. this._recursiveDOMDelete(this.containerElement);
  788. }
  789. Network.prototype._recursiveDOMDelete = function(DOMobject) {
  790. while (DOMobject.hasChildNodes() == true) {
  791. this._recursiveDOMDelete(DOMobject.firstChild);
  792. DOMobject.removeChild(DOMobject.firstChild);
  793. }
  794. }
  795. /**
  796. * Get the pointer location from a touch location
  797. * @param {{x: Number, y: Number}} center
  798. * @return {{x: Number, y: Number}} pointer
  799. * @private
  800. */
  801. Network.prototype._getPointer = function (center) {
  802. return {
  803. x: center.x - util.getAbsoluteLeft(this.frame.canvas),
  804. y: center.y - util.getAbsoluteTop(this.frame.canvas)
  805. };
  806. };
  807. /**
  808. * On start of a touch gesture, store the pointer
  809. * @param event
  810. * @private
  811. */
  812. Network.prototype._onTouch = function (event) {
  813. if (new Date().valueOf() - this.touchTime > 100) {
  814. this.drag.pointer = this._getPointer(event.center);
  815. this.drag.pinched = false;
  816. this.pinch.scale = this._getScale();
  817. // to avoid double fireing of this event because we have two hammer instances. (on canvas and on frame)
  818. this.touchTime = new Date().valueOf();
  819. this._handleTouch(this.drag.pointer);
  820. }
  821. };
  822. /**
  823. * handle drag start event
  824. * @private
  825. */
  826. Network.prototype._onDragStart = function (event) {
  827. this._handleDragStart(event);
  828. };
  829. /**
  830. * This function is called by _onDragStart.
  831. * It is separated out because we can then overload it for the datamanipulation system.
  832. *
  833. * @private
  834. */
  835. Network.prototype._handleDragStart = function(event) {
  836. // in case the touch event was triggered on an external div, do the initial touch now.
  837. if (this.drag.pointer === undefined) {
  838. this._onTouch(event);
  839. }
  840. var node = this._getNodeAt(this.drag.pointer);
  841. // note: drag.pointer is set in _onTouch to get the initial touch location
  842. this.drag.dragging = true;
  843. this.drag.selection = [];
  844. this.drag.translation = this._getTranslation();
  845. this.drag.nodeId = null;
  846. this.draggingNodes = false;
  847. if (node != null && this.constants.dragNodes == true) {
  848. this.draggingNodes = true;
  849. this.drag.nodeId = node.id;
  850. // select the clicked node if not yet selected
  851. if (!node.isSelected()) {
  852. this._selectObject(node,false);
  853. }
  854. this.emit("dragStart",{nodeIds:this.getSelection().nodes});
  855. // create an array with the selected nodes and their original location and status
  856. for (var objectId in this.selectionObj.nodes) {
  857. if (this.selectionObj.nodes.hasOwnProperty(objectId)) {
  858. var object = this.selectionObj.nodes[objectId];
  859. var s = {
  860. id: object.id,
  861. node: object,
  862. // store original x, y, xFixed and yFixed, make the node temporarily Fixed
  863. x: object.x,
  864. y: object.y,
  865. xFixed: object.xFixed,
  866. yFixed: object.yFixed
  867. };
  868. object.xFixed = true;
  869. object.yFixed = true;
  870. this.drag.selection.push(s);
  871. }
  872. }
  873. }
  874. event.preventDefault();
  875. };
  876. /**
  877. * handle drag event
  878. * @private
  879. */
  880. Network.prototype._onDrag = function (event) {
  881. this._handleOnDrag(event)
  882. };
  883. /**
  884. * This function is called by _onDrag.
  885. * It is separated out because we can then overload it for the datamanipulation system.
  886. *
  887. * @private
  888. */
  889. Network.prototype._handleOnDrag = function(event) {
  890. if (this.drag.pinched) {
  891. return;
  892. }
  893. // remove the focus on node if it is focussed on by the focusOnNode
  894. this.releaseNode();
  895. var pointer = this._getPointer(event.center);
  896. var me = this;
  897. var drag = this.drag;
  898. var selection = drag.selection;
  899. if (selection && selection.length && this.constants.dragNodes == true) {
  900. // calculate delta's and new location
  901. var deltaX = pointer.x - drag.pointer.x;
  902. var deltaY = pointer.y - drag.pointer.y;
  903. // update position of all selected nodes
  904. selection.forEach(function (s) {
  905. var node = s.node;
  906. if (!s.xFixed) {
  907. node.x = me._XconvertDOMtoCanvas(me._XconvertCanvasToDOM(s.x) + deltaX);
  908. }
  909. if (!s.yFixed) {
  910. node.y = me._YconvertDOMtoCanvas(me._YconvertCanvasToDOM(s.y) + deltaY);
  911. }
  912. });
  913. // start _animationStep if not yet running
  914. if (!this.moving) {
  915. this.moving = true;
  916. this.start();
  917. }
  918. }
  919. else {
  920. // move the network
  921. if (this.constants.dragNetwork == true) {
  922. // if the drag was not started properly because the click started outside the network div, start it now.
  923. if (this.drag.pointer === undefined) {
  924. this._handleDragStart(event);
  925. return;
  926. }
  927. var diffX = pointer.x - this.drag.pointer.x;
  928. var diffY = pointer.y - this.drag.pointer.y;
  929. this._setTranslation(
  930. this.drag.translation.x + diffX,
  931. this.drag.translation.y + diffY
  932. );
  933. this._redraw();
  934. }
  935. }
  936. event.preventDefault();
  937. };
  938. /**
  939. * handle drag start event
  940. * @private
  941. */
  942. Network.prototype._onDragEnd = function (event) {
  943. this._handleDragEnd(event);
  944. };
  945. Network.prototype._handleDragEnd = function(event) {
  946. this.drag.dragging = false;
  947. var selection = this.drag.selection;
  948. if (selection && selection.length) {
  949. selection.forEach(function (s) {
  950. // restore original xFixed and yFixed
  951. s.node.xFixed = s.xFixed;
  952. s.node.yFixed = s.yFixed;
  953. });
  954. this.moving = true;
  955. this.start();
  956. }
  957. else {
  958. this._redraw();
  959. }
  960. if (this.draggingNodes == false) {
  961. this.emit("dragEnd",{nodeIds:[]});
  962. }
  963. else {
  964. this.emit("dragEnd",{nodeIds:this.getSelection().nodes});
  965. }
  966. event.preventDefault();
  967. };
  968. /**
  969. * handle tap/click event: select/unselect a node
  970. * @private
  971. */
  972. Network.prototype._onTap = function (event) {
  973. var pointer = this._getPointer(event.center);
  974. this.pointerPosition = pointer;
  975. this._handleTap(pointer);
  976. };
  977. /**
  978. * handle doubletap event
  979. * @private
  980. */
  981. Network.prototype._onDoubleTap = function (event) {
  982. var pointer = this._getPointer(event.center);
  983. this._handleDoubleTap(pointer);
  984. };
  985. /**
  986. * handle long tap event: multi select nodes
  987. * @private
  988. */
  989. Network.prototype._onHold = function (event) {
  990. var pointer = this._getPointer(event.center);
  991. this.pointerPosition = pointer;
  992. this._handleOnHold(pointer);
  993. };
  994. /**
  995. * handle the release of the screen
  996. *
  997. * @private
  998. */
  999. Network.prototype._onRelease = function (event) {
  1000. var pointer = this._getPointer(event.center);
  1001. this._handleOnRelease(pointer);
  1002. };
  1003. /**
  1004. * Handle pinch event
  1005. * @param event
  1006. * @private
  1007. */
  1008. Network.prototype._onPinch = function (event) {
  1009. var pointer = this._getPointer(event.center);
  1010. this.drag.pinched = true;
  1011. if (!('scale' in this.pinch)) {
  1012. this.pinch.scale = 1;
  1013. }
  1014. // TODO: enabled moving while pinching?
  1015. var scale = this.pinch.scale * event.scale;
  1016. this._zoom(scale, pointer)
  1017. };
  1018. /**
  1019. * Zoom the network in or out
  1020. * @param {Number} scale a number around 1, and between 0.01 and 10
  1021. * @param {{x: Number, y: Number}} pointer Position on screen
  1022. * @return {Number} appliedScale scale is limited within the boundaries
  1023. * @private
  1024. */
  1025. Network.prototype._zoom = function(scale, pointer) {
  1026. if (this.constants.zoomable == true) {
  1027. var scaleOld = this._getScale();
  1028. if (scale < 0.00001) {
  1029. scale = 0.00001;
  1030. }
  1031. if (scale > 10) {
  1032. scale = 10;
  1033. }
  1034. var preScaleDragPointer = null;
  1035. if (this.drag !== undefined) {
  1036. if (this.drag.dragging == true) {
  1037. preScaleDragPointer = this.DOMtoCanvas(this.drag.pointer);
  1038. }
  1039. }
  1040. // + this.frame.canvas.clientHeight / 2
  1041. var translation = this._getTranslation();
  1042. var scaleFrac = scale / scaleOld;
  1043. var tx = (1 - scaleFrac) * pointer.x + translation.x * scaleFrac;
  1044. var ty = (1 - scaleFrac) * pointer.y + translation.y * scaleFrac;
  1045. this.areaCenter = {"x" : this._XconvertDOMtoCanvas(pointer.x),
  1046. "y" : this._YconvertDOMtoCanvas(pointer.y)};
  1047. this._setScale(scale);
  1048. this._setTranslation(tx, ty);
  1049. this.updateClustersDefault();
  1050. if (preScaleDragPointer != null) {
  1051. var postScaleDragPointer = this.canvasToDOM(preScaleDragPointer);
  1052. this.drag.pointer.x = postScaleDragPointer.x;
  1053. this.drag.pointer.y = postScaleDragPointer.y;
  1054. }
  1055. this._redraw();
  1056. if (scaleOld < scale) {
  1057. this.emit("zoom", {direction:"+"});
  1058. }
  1059. else {
  1060. this.emit("zoom", {direction:"-"});
  1061. }
  1062. return scale;
  1063. }
  1064. };
  1065. /**
  1066. * Event handler for mouse wheel event, used to zoom the timeline
  1067. * See http://adomas.org/javascript-mouse-wheel/
  1068. * https://github.com/EightMedia/hammer.js/issues/256
  1069. * @param {MouseEvent} event
  1070. * @private
  1071. */
  1072. Network.prototype._onMouseWheel = function(event) {
  1073. // retrieve delta
  1074. var delta = 0;
  1075. if (event.wheelDelta) { /* IE/Opera. */
  1076. delta = event.wheelDelta/120;
  1077. } else if (event.detail) { /* Mozilla case. */
  1078. // In Mozilla, sign of delta is different than in IE.
  1079. // Also, delta is multiple of 3.
  1080. delta = -event.detail/3;
  1081. }
  1082. // If delta is nonzero, handle it.
  1083. // Basically, delta is now positive if wheel was scrolled up,
  1084. // and negative, if wheel was scrolled down.
  1085. if (delta) {
  1086. // calculate the new scale
  1087. var scale = this._getScale();
  1088. var zoom = delta / 10;
  1089. if (delta < 0) {
  1090. zoom = zoom / (1 - zoom);
  1091. }
  1092. scale *= (1 + zoom);
  1093. // calculate the pointer location
  1094. var pointer = this._getPointer({x: event.pageX, y: event.pageY});
  1095. // apply the new scale
  1096. this._zoom(scale, pointer);
  1097. }
  1098. // Prevent default actions caused by mouse wheel.
  1099. event.preventDefault();
  1100. };
  1101. /**
  1102. * Mouse move handler for checking whether the title moves over a node with a title.
  1103. * @param {Event} event
  1104. * @private
  1105. */
  1106. Network.prototype._onMouseMoveTitle = function (event) {
  1107. var pointer = this._getPointer({x: event.pageX, y: event.pageY});
  1108. // check if the previously selected node is still selected
  1109. if (this.popupObj) {
  1110. this._checkHidePopup(pointer);
  1111. }
  1112. // start a timeout that will check if the mouse is positioned above
  1113. // an element
  1114. var me = this;
  1115. var checkShow = function() {
  1116. me._checkShowPopup(pointer);
  1117. };
  1118. if (this.popupTimer) {
  1119. clearInterval(this.popupTimer); // stop any running calculationTimer
  1120. }
  1121. if (!this.drag.dragging) {
  1122. this.popupTimer = setTimeout(checkShow, this.constants.tooltip.delay);
  1123. }
  1124. /**
  1125. * Adding hover highlights
  1126. */
  1127. if (this.constants.hover == true) {
  1128. // removing all hover highlights
  1129. for (var edgeId in this.hoverObj.edges) {
  1130. if (this.hoverObj.edges.hasOwnProperty(edgeId)) {
  1131. this.hoverObj.edges[edgeId].hover = false;
  1132. delete this.hoverObj.edges[edgeId];
  1133. }
  1134. }
  1135. // adding hover highlights
  1136. var obj = this._getNodeAt(pointer);
  1137. if (obj == null) {
  1138. obj = this._getEdgeAt(pointer);
  1139. }
  1140. if (obj != null) {
  1141. this._hoverObject(obj);
  1142. }
  1143. // removing all node hover highlights except for the selected one.
  1144. for (var nodeId in this.hoverObj.nodes) {
  1145. if (this.hoverObj.nodes.hasOwnProperty(nodeId)) {
  1146. if (obj instanceof Node && obj.id != nodeId || obj instanceof Edge || obj == null) {
  1147. this._blurObject(this.hoverObj.nodes[nodeId]);
  1148. delete this.hoverObj.nodes[nodeId];
  1149. }
  1150. }
  1151. }
  1152. this.redraw();
  1153. }
  1154. };
  1155. /**
  1156. * Check if there is an element on the given position in the network
  1157. * (a node or edge). If so, and if this element has a title,
  1158. * show a popup window with its title.
  1159. *
  1160. * @param {{x:Number, y:Number}} pointer
  1161. * @private
  1162. */
  1163. Network.prototype._checkShowPopup = function (pointer) {
  1164. var obj = {
  1165. left: this._XconvertDOMtoCanvas(pointer.x),
  1166. top: this._YconvertDOMtoCanvas(pointer.y),
  1167. right: this._XconvertDOMtoCanvas(pointer.x),
  1168. bottom: this._YconvertDOMtoCanvas(pointer.y)
  1169. };
  1170. var id;
  1171. var lastPopupNode = this.popupObj;
  1172. var nodeUnderCursor = false;
  1173. if (this.popupObj == undefined) {
  1174. // search the nodes for overlap, select the top one in case of multiple nodes
  1175. var nodes = this.nodes;
  1176. var overlappingNodes = [];
  1177. for (id in nodes) {
  1178. if (nodes.hasOwnProperty(id)) {
  1179. var node = nodes[id];
  1180. if (node.isOverlappingWith(obj)) {
  1181. if (node.getTitle() !== undefined) {
  1182. overlappingNodes.push(id);
  1183. }
  1184. }
  1185. }
  1186. }
  1187. if (overlappingNodes.length > 0) {
  1188. // if there are overlapping nodes, select the last one, this is the
  1189. // one which is drawn on top of the others
  1190. this.popupObj = this.nodes[overlappingNodes[overlappingNodes.length - 1]];
  1191. // if you hover over a node, the title of the edge is not supposed to be shown.
  1192. nodeUnderCursor = true;
  1193. }
  1194. }
  1195. if (this.popupObj === undefined && nodeUnderCursor == false) {
  1196. // search the edges for overlap
  1197. var edges = this.edges;
  1198. var overlappingEdges = [];
  1199. for (id in edges) {
  1200. if (edges.hasOwnProperty(id)) {
  1201. var edge = edges[id];
  1202. if (edge.connected && (edge.getTitle() !== undefined) &&
  1203. edge.isOverlappingWith(obj)) {
  1204. overlappingEdges.push(id);
  1205. }
  1206. }
  1207. }
  1208. if (overlappingEdges.length > 0) {
  1209. this.popupObj = this.edges[overlappingEdges[overlappingEdges.length - 1]];
  1210. }
  1211. }
  1212. if (this.popupObj) {
  1213. // show popup message window
  1214. if (this.popupObj != lastPopupNode) {
  1215. var me = this;
  1216. if (!me.popup) {
  1217. me.popup = new Popup(me.frame, me.constants.tooltip);
  1218. }
  1219. // adjust a small offset such that the mouse cursor is located in the
  1220. // bottom left location of the popup, and you can easily move over the
  1221. // popup area
  1222. me.popup.setPosition(pointer.x - 3, pointer.y - 3);
  1223. me.popup.setText(me.popupObj.getTitle());
  1224. me.popup.show();
  1225. }
  1226. }
  1227. else {
  1228. if (this.popup) {
  1229. this.popup.hide();
  1230. }
  1231. }
  1232. };
  1233. /**
  1234. * Check if the popup must be hided, which is the case when the mouse is no
  1235. * longer hovering on the object
  1236. * @param {{x:Number, y:Number}} pointer
  1237. * @private
  1238. */
  1239. Network.prototype._checkHidePopup = function (pointer) {
  1240. if (!this.popupObj || !this._getNodeAt(pointer) ) {
  1241. this.popupObj = undefined;
  1242. if (this.popup) {
  1243. this.popup.hide();
  1244. }
  1245. }
  1246. };
  1247. /**
  1248. * Set a new size for the network
  1249. * @param {string} width Width in pixels or percentage (for example '800px'
  1250. * or '50%')
  1251. * @param {string} height Height in pixels or percentage (for example '400px'
  1252. * or '30%')
  1253. */
  1254. Network.prototype.setSize = function(width, height) {
  1255. var emitEvent = false;
  1256. var oldWidth = this.frame.canvas.width;
  1257. var oldHeight = this.frame.canvas.height;
  1258. if (width != this.constants.width || height != this.constants.height || this.frame.style.width != width || this.frame.style.height != height) {
  1259. this.frame.style.width = width;
  1260. this.frame.style.height = height;
  1261. this.frame.canvas.style.width = '100%';
  1262. this.frame.canvas.style.height = '100%';
  1263. this.frame.canvas.width = this.frame.canvas.clientWidth * this.pixelRatio;
  1264. this.frame.canvas.height = this.frame.canvas.clientHeight * this.pixelRatio;
  1265. this.constants.width = width;
  1266. this.constants.height = height;
  1267. emitEvent = true;
  1268. }
  1269. else {
  1270. // this would adapt the width of the canvas to the width from 100% if and only if
  1271. // there is a change.
  1272. if (this.frame.canvas.width != this.frame.canvas.clientWidth * this.pixelRatio) {
  1273. this.frame.canvas.width = this.frame.canvas.clientWidth * this.pixelRatio;
  1274. emitEvent = true;
  1275. }
  1276. if (this.frame.canvas.height != this.frame.canvas.clientHeight * this.pixelRatio) {
  1277. this.frame.canvas.height = this.frame.canvas.clientHeight * this.pixelRatio;
  1278. emitEvent = true;
  1279. }
  1280. }
  1281. if (emitEvent == true) {
  1282. 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});
  1283. }
  1284. };
  1285. /**
  1286. * Set a data set with nodes for the network
  1287. * @param {Array | DataSet | DataView} nodes The data containing the nodes.
  1288. * @private
  1289. */
  1290. Network.prototype._setNodes = function(nodes) {
  1291. var oldNodesData = this.nodesData;
  1292. if (nodes instanceof DataSet || nodes instanceof DataView) {
  1293. this.nodesData = nodes;
  1294. }
  1295. else if (Array.isArray(nodes)) {
  1296. this.nodesData = new DataSet();
  1297. this.nodesData.add(nodes);
  1298. }
  1299. else if (!nodes) {
  1300. this.nodesData = new DataSet();
  1301. }
  1302. else {
  1303. throw new TypeError('Array or DataSet expected');
  1304. }
  1305. if (oldNodesData) {
  1306. // unsubscribe from old dataset
  1307. util.forEach(this.nodesListeners, function (callback, event) {
  1308. oldNodesData.off(event, callback);
  1309. });
  1310. }
  1311. // remove drawn nodes
  1312. this.nodes = {};
  1313. if (this.nodesData) {
  1314. // subscribe to new dataset
  1315. var me = this;
  1316. util.forEach(this.nodesListeners, function (callback, event) {
  1317. me.nodesData.on(event, callback);
  1318. });
  1319. // draw all new nodes
  1320. var ids = this.nodesData.getIds();
  1321. this._addNodes(ids);
  1322. }
  1323. this._updateSelection();
  1324. };
  1325. /**
  1326. * Add nodes
  1327. * @param {Number[] | String[]} ids
  1328. * @private
  1329. */
  1330. Network.prototype._addNodes = function(ids) {
  1331. var id;
  1332. for (var i = 0, len = ids.length; i < len; i++) {
  1333. id = ids[i];
  1334. var data = this.nodesData.get(id);
  1335. var node = new Node(data, this.images, this.groups, this.constants);
  1336. this.nodes[id] = node; // note: this may replace an existing node
  1337. if ((node.xFixed == false || node.yFixed == false) && (node.x === null || node.y === null)) {
  1338. var radius = 10 * 0.1*ids.length + 10;
  1339. var angle = 2 * Math.PI * Math.random();
  1340. if (node.xFixed == false) {node.x = radius * Math.cos(angle);}
  1341. if (node.yFixed == false) {node.y = radius * Math.sin(angle);}
  1342. }
  1343. this.moving = true;
  1344. }
  1345. this._updateNodeIndexList();
  1346. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  1347. this._resetLevels();
  1348. this._setupHierarchicalLayout();
  1349. }
  1350. this._updateCalculationNodes();
  1351. this._reconnectEdges();
  1352. this._updateValueRange(this.nodes);
  1353. this.updateLabels();
  1354. };
  1355. /**
  1356. * Update existing nodes, or create them when not yet existing
  1357. * @param {Number[] | String[]} ids
  1358. * @private
  1359. */
  1360. Network.prototype._updateNodes = function(ids,changedData) {
  1361. var nodes = this.nodes;
  1362. for (var i = 0, len = ids.length; i < len; i++) {
  1363. var id = ids[i];
  1364. var node = nodes[id];
  1365. var data = changedData[i];
  1366. if (node) {
  1367. // update node
  1368. node.setProperties(data, this.constants);
  1369. }
  1370. else {
  1371. // create node
  1372. node = new Node(properties, this.images, this.groups, this.constants);
  1373. nodes[id] = node;
  1374. }
  1375. }
  1376. this.moving = true;
  1377. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  1378. this._resetLevels();
  1379. this._setupHierarchicalLayout();
  1380. }
  1381. this._updateNodeIndexList();
  1382. this._updateValueRange(nodes);
  1383. };
  1384. /**
  1385. * Remove existing nodes. If nodes do not exist, the method will just ignore it.
  1386. * @param {Number[] | String[]} ids
  1387. * @private
  1388. */
  1389. Network.prototype._removeNodes = function(ids) {
  1390. var nodes = this.nodes;
  1391. for (var i = 0, len = ids.length; i < len; i++) {
  1392. var id = ids[i];
  1393. delete nodes[id];
  1394. }
  1395. this._updateNodeIndexList();
  1396. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  1397. this._resetLevels();
  1398. this._setupHierarchicalLayout();
  1399. }
  1400. this._updateCalculationNodes();
  1401. this._reconnectEdges();
  1402. this._updateSelection();
  1403. this._updateValueRange(nodes);
  1404. };
  1405. /**
  1406. * Load edges by reading the data table
  1407. * @param {Array | DataSet | DataView} edges The data containing the edges.
  1408. * @private
  1409. * @private
  1410. */
  1411. Network.prototype._setEdges = function(edges) {
  1412. var oldEdgesData = this.edgesData;
  1413. if (edges instanceof DataSet || edges instanceof DataView) {
  1414. this.edgesData = edges;
  1415. }
  1416. else if (Array.isArray(edges)) {
  1417. this.edgesData = new DataSet();
  1418. this.edgesData.add(edges);
  1419. }
  1420. else if (!edges) {
  1421. this.edgesData = new DataSet();
  1422. }
  1423. else {
  1424. throw new TypeError('Array or DataSet expected');
  1425. }
  1426. if (oldEdgesData) {
  1427. // unsubscribe from old dataset
  1428. util.forEach(this.edgesListeners, function (callback, event) {
  1429. oldEdgesData.off(event, callback);
  1430. });
  1431. }
  1432. // remove drawn edges
  1433. this.edges = {};
  1434. if (this.edgesData) {
  1435. // subscribe to new dataset
  1436. var me = this;
  1437. util.forEach(this.edgesListeners, function (callback, event) {
  1438. me.edgesData.on(event, callback);
  1439. });
  1440. // draw all new nodes
  1441. var ids = this.edgesData.getIds();
  1442. this._addEdges(ids);
  1443. }
  1444. this._reconnectEdges();
  1445. };
  1446. /**
  1447. * Add edges
  1448. * @param {Number[] | String[]} ids
  1449. * @private
  1450. */
  1451. Network.prototype._addEdges = function (ids) {
  1452. var edges = this.edges,
  1453. edgesData = this.edgesData;
  1454. for (var i = 0, len = ids.length; i < len; i++) {
  1455. var id = ids[i];
  1456. var oldEdge = edges[id];
  1457. if (oldEdge) {
  1458. oldEdge.disconnect();
  1459. }
  1460. var data = edgesData.get(id, {"showInternalIds" : true});
  1461. edges[id] = new Edge(data, this, this.constants);
  1462. }
  1463. this.moving = true;
  1464. this._updateValueRange(edges);
  1465. this._createBezierNodes();
  1466. this._updateCalculationNodes();
  1467. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  1468. this._resetLevels();
  1469. this._setupHierarchicalLayout();
  1470. }
  1471. };
  1472. /**
  1473. * Update existing edges, or create them when not yet existing
  1474. * @param {Number[] | String[]} ids
  1475. * @private
  1476. */
  1477. Network.prototype._updateEdges = function (ids) {
  1478. var edges = this.edges,
  1479. edgesData = this.edgesData;
  1480. for (var i = 0, len = ids.length; i < len; i++) {
  1481. var id = ids[i];
  1482. var data = edgesData.get(id);
  1483. var edge = edges[id];
  1484. if (edge) {
  1485. // update edge
  1486. edge.disconnect();
  1487. edge.setProperties(data, this.constants);
  1488. edge.connect();
  1489. }
  1490. else {
  1491. // create edge
  1492. edge = new Edge(data, this, this.constants);
  1493. this.edges[id] = edge;
  1494. }
  1495. }
  1496. this._createBezierNodes();
  1497. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  1498. this._resetLevels();
  1499. this._setupHierarchicalLayout();
  1500. }
  1501. this.moving = true;
  1502. this._updateValueRange(edges);
  1503. };
  1504. /**
  1505. * Remove existing edges. Non existing ids will be ignored
  1506. * @param {Number[] | String[]} ids
  1507. * @private
  1508. */
  1509. Network.prototype._removeEdges = function (ids) {
  1510. var edges = this.edges;
  1511. for (var i = 0, len = ids.length; i < len; i++) {
  1512. var id = ids[i];
  1513. var edge = edges[id];
  1514. if (edge) {
  1515. if (edge.via != null) {
  1516. delete this.sectors['support']['nodes'][edge.via.id];
  1517. }
  1518. edge.disconnect();
  1519. delete edges[id];
  1520. }
  1521. }
  1522. this.moving = true;
  1523. this._updateValueRange(edges);
  1524. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  1525. this._resetLevels();
  1526. this._setupHierarchicalLayout();
  1527. }
  1528. this._updateCalculationNodes();
  1529. };
  1530. /**
  1531. * Reconnect all edges
  1532. * @private
  1533. */
  1534. Network.prototype._reconnectEdges = function() {
  1535. var id,
  1536. nodes = this.nodes,
  1537. edges = this.edges;
  1538. for (id in nodes) {
  1539. if (nodes.hasOwnProperty(id)) {
  1540. nodes[id].edges = [];
  1541. nodes[id].dynamicEdges = [];
  1542. }
  1543. }
  1544. for (id in edges) {
  1545. if (edges.hasOwnProperty(id)) {
  1546. var edge = edges[id];
  1547. edge.from = null;
  1548. edge.to = null;
  1549. edge.connect();
  1550. }
  1551. }
  1552. };
  1553. /**
  1554. * Update the values of all object in the given array according to the current
  1555. * value range of the objects in the array.
  1556. * @param {Object} obj An object containing a set of Edges or Nodes
  1557. * The objects must have a method getValue() and
  1558. * setValueRange(min, max).
  1559. * @private
  1560. */
  1561. Network.prototype._updateValueRange = function(obj) {
  1562. var id;
  1563. // determine the range of the objects
  1564. var valueMin = undefined;
  1565. var valueMax = undefined;
  1566. for (id in obj) {
  1567. if (obj.hasOwnProperty(id)) {
  1568. var value = obj[id].getValue();
  1569. if (value !== undefined) {
  1570. valueMin = (valueMin === undefined) ? value : Math.min(value, valueMin);
  1571. valueMax = (valueMax === undefined) ? value : Math.max(value, valueMax);
  1572. }
  1573. }
  1574. }
  1575. // adjust the range of all objects
  1576. if (valueMin !== undefined && valueMax !== undefined) {
  1577. for (id in obj) {
  1578. if (obj.hasOwnProperty(id)) {
  1579. obj[id].setValueRange(valueMin, valueMax);
  1580. }
  1581. }
  1582. }
  1583. };
  1584. /**
  1585. * Redraw the network with the current data
  1586. * chart will be resized too.
  1587. */
  1588. Network.prototype.redraw = function() {
  1589. this.setSize(this.constants.width, this.constants.height);
  1590. this._redraw();
  1591. };
  1592. /**
  1593. * Redraw the network with the current data
  1594. * @param hidden | used to get the first estimate of the node sizes. only the nodes are drawn after which they are quickly drawn over.
  1595. * @private
  1596. */
  1597. Network.prototype._redraw = function(hidden) {
  1598. var ctx = this.frame.canvas.getContext('2d');
  1599. ctx.setTransform(this.pixelRatio, 0, 0, this.pixelRatio, 0, 0);
  1600. // clear the canvas
  1601. var w = this.frame.canvas.width * this.pixelRatio;
  1602. var h = this.frame.canvas.height * this.pixelRatio;
  1603. ctx.clearRect(0, 0, w, h);
  1604. // set scaling and translation
  1605. ctx.save();
  1606. ctx.translate(this.translation.x, this.translation.y);
  1607. ctx.scale(this.scale, this.scale);
  1608. this.canvasTopLeft = {
  1609. "x": this._XconvertDOMtoCanvas(0),
  1610. "y": this._YconvertDOMtoCanvas(0)
  1611. };
  1612. this.canvasBottomRight = {
  1613. "x": this._XconvertDOMtoCanvas(this.frame.canvas.clientWidth * this.pixelRatio),
  1614. "y": this._YconvertDOMtoCanvas(this.frame.canvas.clientHeight * this.pixelRatio)
  1615. };
  1616. if (!(hidden == true)) {
  1617. this._doInAllSectors("_drawAllSectorNodes", ctx);
  1618. if (this.drag.dragging == false || this.drag.dragging === undefined || this.constants.hideEdgesOnDrag == false) {
  1619. this._doInAllSectors("_drawEdges", ctx);
  1620. }
  1621. }
  1622. if (this.drag.dragging == false || this.drag.dragging === undefined || this.constants.hideNodesOnDrag == false) {
  1623. this._doInAllSectors("_drawNodes",ctx,false);
  1624. }
  1625. if (!(hidden == true)) {
  1626. if (this.controlNodesActive == true) {
  1627. this._doInAllSectors("_drawControlNodes", ctx);
  1628. }
  1629. }
  1630. // this._doInSupportSector("_drawNodes",ctx,true);
  1631. // this._drawTree(ctx,"#F00F0F");
  1632. // restore original scaling and translation
  1633. ctx.restore();
  1634. if (hidden == true) {
  1635. ctx.clearRect(0, 0, w, h);
  1636. }
  1637. };
  1638. /**
  1639. * Set the translation of the network
  1640. * @param {Number} offsetX Horizontal offset
  1641. * @param {Number} offsetY Vertical offset
  1642. * @private
  1643. */
  1644. Network.prototype._setTranslation = function(offsetX, offsetY) {
  1645. if (this.translation === undefined) {
  1646. this.translation = {
  1647. x: 0,
  1648. y: 0
  1649. };
  1650. }
  1651. if (offsetX !== undefined) {
  1652. this.translation.x = offsetX;
  1653. }
  1654. if (offsetY !== undefined) {
  1655. this.translation.y = offsetY;
  1656. }
  1657. this.emit('viewChanged');
  1658. };
  1659. /**
  1660. * Get the translation of the network
  1661. * @return {Object} translation An object with parameters x and y, both a number
  1662. * @private
  1663. */
  1664. Network.prototype._getTranslation = function() {
  1665. return {
  1666. x: this.translation.x,
  1667. y: this.translation.y
  1668. };
  1669. };
  1670. /**
  1671. * Scale the network
  1672. * @param {Number} scale Scaling factor 1.0 is unscaled
  1673. * @private
  1674. */
  1675. Network.prototype._setScale = function(scale) {
  1676. this.scale = scale;
  1677. };
  1678. /**
  1679. * Get the current scale of the network
  1680. * @return {Number} scale Scaling factor 1.0 is unscaled
  1681. * @private
  1682. */
  1683. Network.prototype._getScale = function() {
  1684. return this.scale;
  1685. };
  1686. /**
  1687. * Convert the X coordinate in DOM-space (coordinate point in browser relative to the container div) to
  1688. * the X coordinate in canvas-space (the simulation sandbox, which the camera looks upon)
  1689. * @param {number} x
  1690. * @returns {number}
  1691. * @private
  1692. */
  1693. Network.prototype._XconvertDOMtoCanvas = function(x) {
  1694. return (x - this.translation.x) / this.scale;
  1695. };
  1696. /**
  1697. * Convert the X coordinate in canvas-space (the simulation sandbox, which the camera looks upon) to
  1698. * the X coordinate in DOM-space (coordinate point in browser relative to the container div)
  1699. * @param {number} x
  1700. * @returns {number}
  1701. * @private
  1702. */
  1703. Network.prototype._XconvertCanvasToDOM = function(x) {
  1704. return x * this.scale + this.translation.x;
  1705. };
  1706. /**
  1707. * Convert the Y coordinate in DOM-space (coordinate point in browser relative to the container div) to
  1708. * the Y coordinate in canvas-space (the simulation sandbox, which the camera looks upon)
  1709. * @param {number} y
  1710. * @returns {number}
  1711. * @private
  1712. */
  1713. Network.prototype._YconvertDOMtoCanvas = function(y) {
  1714. return (y - this.translation.y) / this.scale;
  1715. };
  1716. /**
  1717. * Convert the Y coordinate in canvas-space (the simulation sandbox, which the camera looks upon) to
  1718. * the Y coordinate in DOM-space (coordinate point in browser relative to the container div)
  1719. * @param {number} y
  1720. * @returns {number}
  1721. * @private
  1722. */
  1723. Network.prototype._YconvertCanvasToDOM = function(y) {
  1724. return y * this.scale + this.translation.y ;
  1725. };
  1726. /**
  1727. *
  1728. * @param {object} pos = {x: number, y: number}
  1729. * @returns {{x: number, y: number}}
  1730. * @constructor
  1731. */
  1732. Network.prototype.canvasToDOM = function (pos) {
  1733. return {x: this._XconvertCanvasToDOM(pos.x), y: this._YconvertCanvasToDOM(pos.y)};
  1734. };
  1735. /**
  1736. *
  1737. * @param {object} pos = {x: number, y: number}
  1738. * @returns {{x: number, y: number}}
  1739. * @constructor
  1740. */
  1741. Network.prototype.DOMtoCanvas = function (pos) {
  1742. return {x: this._XconvertDOMtoCanvas(pos.x), y: this._YconvertDOMtoCanvas(pos.y)};
  1743. };
  1744. /**
  1745. * Redraw all nodes
  1746. * The 2d context of a HTML canvas can be retrieved by canvas.getContext('2d');
  1747. * @param {CanvasRenderingContext2D} ctx
  1748. * @param {Boolean} [alwaysShow]
  1749. * @private
  1750. */
  1751. Network.prototype._drawNodes = function(ctx,alwaysShow) {
  1752. if (alwaysShow === undefined) {
  1753. alwaysShow = false;
  1754. }
  1755. // first draw the unselected nodes
  1756. var nodes = this.nodes;
  1757. var selected = [];
  1758. for (var id in nodes) {
  1759. if (nodes.hasOwnProperty(id)) {
  1760. nodes[id].setScaleAndPos(this.scale,this.canvasTopLeft,this.canvasBottomRight);
  1761. if (nodes[id].isSelected()) {
  1762. selected.push(id);
  1763. }
  1764. else {
  1765. if (nodes[id].inArea() || alwaysShow) {
  1766. nodes[id].draw(ctx);
  1767. }
  1768. }
  1769. }
  1770. }
  1771. // draw the selected nodes on top
  1772. for (var s = 0, sMax = selected.length; s < sMax; s++) {
  1773. if (nodes[selected[s]].inArea() || alwaysShow) {
  1774. nodes[selected[s]].draw(ctx);
  1775. }
  1776. }
  1777. };
  1778. /**
  1779. * Redraw all edges
  1780. * The 2d context of a HTML canvas can be retrieved by canvas.getContext('2d');
  1781. * @param {CanvasRenderingContext2D} ctx
  1782. * @private
  1783. */
  1784. Network.prototype._drawEdges = function(ctx) {
  1785. var edges = this.edges;
  1786. for (var id in edges) {
  1787. if (edges.hasOwnProperty(id)) {
  1788. var edge = edges[id];
  1789. edge.setScale(this.scale);
  1790. if (edge.connected) {
  1791. edges[id].draw(ctx);
  1792. }
  1793. }
  1794. }
  1795. };
  1796. /**
  1797. * Redraw all edges
  1798. * The 2d context of a HTML canvas can be retrieved by canvas.getContext('2d');
  1799. * @param {CanvasRenderingContext2D} ctx
  1800. * @private
  1801. */
  1802. Network.prototype._drawControlNodes = function(ctx) {
  1803. var edges = this.edges;
  1804. for (var id in edges) {
  1805. if (edges.hasOwnProperty(id)) {
  1806. edges[id]._drawControlNodes(ctx);
  1807. }
  1808. }
  1809. };
  1810. /**
  1811. * Find a stable position for all nodes
  1812. * @private
  1813. */
  1814. Network.prototype._stabilize = function() {
  1815. if (this.constants.freezeForStabilization == true) {
  1816. this._freezeDefinedNodes();
  1817. }
  1818. // find stable position
  1819. var count = 0;
  1820. while (this.moving && count < this.constants.stabilizationIterations) {
  1821. this._physicsTick();
  1822. count++;
  1823. }
  1824. if (this.constants.zoomExtentOnStabilize == true) {
  1825. this.zoomExtent(undefined, false, true);
  1826. }
  1827. if (this.constants.freezeForStabilization == true) {
  1828. this._restoreFrozenNodes();
  1829. }
  1830. };
  1831. /**
  1832. * When initializing and stabilizing, we can freeze nodes with a predefined position. This greatly speeds up stabilization
  1833. * because only the supportnodes for the smoothCurves have to settle.
  1834. *
  1835. * @private
  1836. */
  1837. Network.prototype._freezeDefinedNodes = function() {
  1838. var nodes = this.nodes;
  1839. for (var id in nodes) {
  1840. if (nodes.hasOwnProperty(id)) {
  1841. if (nodes[id].x != null && nodes[id].y != null) {
  1842. nodes[id].fixedData.x = nodes[id].xFixed;
  1843. nodes[id].fixedData.y = nodes[id].yFixed;
  1844. nodes[id].xFixed = true;
  1845. nodes[id].yFixed = true;
  1846. }
  1847. }
  1848. }
  1849. };
  1850. /**
  1851. * Unfreezes the nodes that have been frozen by _freezeDefinedNodes.
  1852. *
  1853. * @private
  1854. */
  1855. Network.prototype._restoreFrozenNodes = function() {
  1856. var nodes = this.nodes;
  1857. for (var id in nodes) {
  1858. if (nodes.hasOwnProperty(id)) {
  1859. if (nodes[id].fixedData.x != null) {
  1860. nodes[id].xFixed = nodes[id].fixedData.x;
  1861. nodes[id].yFixed = nodes[id].fixedData.y;
  1862. }
  1863. }
  1864. }
  1865. };
  1866. /**
  1867. * Check if any of the nodes is still moving
  1868. * @param {number} vmin the minimum velocity considered as 'moving'
  1869. * @return {boolean} true if moving, false if non of the nodes is moving
  1870. * @private
  1871. */
  1872. Network.prototype._isMoving = function(vmin) {
  1873. var nodes = this.nodes;
  1874. for (var id in nodes) {
  1875. if (nodes.hasOwnProperty(id) && nodes[id].isMoving(vmin)) {
  1876. return true;
  1877. }
  1878. }
  1879. return false;
  1880. };
  1881. /**
  1882. * /**
  1883. * Perform one discrete step for all nodes
  1884. *
  1885. * @private
  1886. */
  1887. Network.prototype._discreteStepNodes = function() {
  1888. var interval = this.physicsDiscreteStepsize;
  1889. var nodes = this.nodes;
  1890. var nodeId;
  1891. var nodesPresent = false;
  1892. if (this.constants.maxVelocity > 0) {
  1893. for (nodeId in nodes) {
  1894. if (nodes.hasOwnProperty(nodeId)) {
  1895. nodes[nodeId].discreteStepLimited(interval, this.constants.maxVelocity);
  1896. nodesPresent = true;
  1897. }
  1898. }
  1899. }
  1900. else {
  1901. for (nodeId in nodes) {
  1902. if (nodes.hasOwnProperty(nodeId)) {
  1903. nodes[nodeId].discreteStep(interval);
  1904. nodesPresent = true;
  1905. }
  1906. }
  1907. }
  1908. if (nodesPresent == true) {
  1909. var vminCorrected = this.constants.minVelocity / Math.max(this.scale,0.05);
  1910. if (vminCorrected > 0.5*this.constants.maxVelocity) {
  1911. return true;
  1912. }
  1913. else {
  1914. return this._isMoving(vminCorrected);
  1915. }
  1916. }
  1917. return false;
  1918. };
  1919. Network.prototype._revertPhysicsState = function() {
  1920. var nodes = this.nodes;
  1921. for (var nodeId in nodes) {
  1922. if (nodes.hasOwnProperty(nodeId)) {
  1923. nodes[nodeId].revertPosition();
  1924. }
  1925. }
  1926. }
  1927. Network.prototype._revertPhysicsTick = function() {
  1928. this._doInAllActiveSectors("_revertPhysicsState");
  1929. if (this.constants.smoothCurves.enabled == true && this.constants.smoothCurves.dynamic == true) {
  1930. this._doInSupportSector("_revertPhysicsState");
  1931. }
  1932. }
  1933. /**
  1934. * A single simulation step (or "tick") in the physics simulation
  1935. *
  1936. * @private
  1937. */
  1938. Network.prototype._physicsTick = function() {
  1939. if (!this.freezeSimulation) {
  1940. if (this.moving == true) {
  1941. var mainMovingStatus = false;
  1942. var supportMovingStatus = false;
  1943. this._doInAllActiveSectors("_initializeForceCalculation");
  1944. var mainMoving = this._doInAllActiveSectors("_discreteStepNodes");
  1945. if (this.constants.smoothCurves.enabled == true && this.constants.smoothCurves.dynamic == true) {
  1946. supportMovingStatus = this._doInSupportSector("_discreteStepNodes");
  1947. }
  1948. // gather movement data from all sectors, if one moves, we are NOT stabilzied
  1949. for (var i = 0; i < mainMoving.length; i++) {mainMovingStatus = mainMoving[0] || mainMovingStatus;}
  1950. // determine if the network has stabilzied
  1951. this.moving = mainMovingStatus || supportMovingStatus;
  1952. if (this.moving == false) {
  1953. this._revertPhysicsTick();
  1954. }
  1955. else {
  1956. // this is here to ensure that there is no start event when the network is already stable.
  1957. if (this.startedStabilization == false) {
  1958. this.emit("startStabilization");
  1959. this.startedStabilization = true;
  1960. }
  1961. }
  1962. this.stabilizationIterations++;
  1963. }
  1964. }
  1965. };
  1966. /**
  1967. * This function runs one step of the animation. It calls an x amount of physics ticks and one render tick.
  1968. * It reschedules itself at the beginning of the function
  1969. *
  1970. * @private
  1971. */
  1972. Network.prototype._animationStep = function() {
  1973. // reset the timer so a new scheduled animation step can be set
  1974. this.timer = undefined;
  1975. // handle the keyboad movement
  1976. this._handleNavigation();
  1977. var startTime = Date.now();
  1978. this._physicsTick();
  1979. var physicsTime = Date.now() - startTime;
  1980. // run double speed if it is a little graph
  1981. if ((this.renderTimestep - this.renderTime > 2 * physicsTime || this.runDoubleSpeed == true) && this.moving == true) {
  1982. this._physicsTick();
  1983. // this makes sure there is no jitter. The decision is taken once to run it at double speed.
  1984. if (this.renderTime != 0) {
  1985. this.runDoubleSpeed = true
  1986. }
  1987. }
  1988. var renderStartTime = Date.now();
  1989. this._redraw();
  1990. this.renderTime = Date.now() - renderStartTime;
  1991. // this schedules a new animation step
  1992. this.start();
  1993. };
  1994. if (typeof window !== 'undefined') {
  1995. window.requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame ||
  1996. window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;
  1997. }
  1998. /**
  1999. * Schedule a animation step with the refreshrate interval.
  2000. */
  2001. Network.prototype.start = function() {
  2002. if (this.moving == true || this.xIncrement != 0 || this.yIncrement != 0 || this.zoomIncrement != 0) {
  2003. if (!this.timer) {
  2004. if (this.requiresTimeout == true) {
  2005. this.timer = window.setTimeout(this._animationStep.bind(this), this.renderTimestep); // wait this.renderTimeStep milliseconds and perform the animation step function
  2006. }
  2007. else {
  2008. this.timer = window.requestAnimationFrame(this._animationStep.bind(this)); // wait this.renderTimeStep milliseconds and perform the animation step function
  2009. }
  2010. }
  2011. }
  2012. else {
  2013. this._redraw();
  2014. // 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())
  2015. if (this.stabilizationIterations > 1) {
  2016. // trigger the "stabilized" event.
  2017. // The event is triggered on the next tick, to prevent the case that
  2018. // it is fired while initializing the Network, in which case you would not
  2019. // be able to catch it
  2020. var me = this;
  2021. var params = {
  2022. iterations: me.stabilizationIterations
  2023. };
  2024. this.stabilizationIterations = 0;
  2025. this.startedStabilization = false;
  2026. setTimeout(function () {
  2027. me.emit("stabilized", params);
  2028. }, 0);
  2029. }
  2030. else {
  2031. this.stabilizationIterations = 0;
  2032. }
  2033. }
  2034. };
  2035. /**
  2036. * Move the network according to the keyboard presses.
  2037. *
  2038. * @private
  2039. */
  2040. Network.prototype._handleNavigation = function() {
  2041. if (this.xIncrement != 0 || this.yIncrement != 0) {
  2042. var translation = this._getTranslation();
  2043. this._setTranslation(translation.x+this.xIncrement, translation.y+this.yIncrement);
  2044. }
  2045. if (this.zoomIncrement != 0) {
  2046. var center = {
  2047. x: this.frame.canvas.clientWidth / 2,
  2048. y: this.frame.canvas.clientHeight / 2
  2049. };
  2050. this._zoom(this.scale*(1 + this.zoomIncrement), center);
  2051. }
  2052. };
  2053. /**
  2054. * Freeze the _animationStep
  2055. */
  2056. Network.prototype.toggleFreeze = function() {
  2057. if (this.freezeSimulation == false) {
  2058. this.freezeSimulation = true;
  2059. }
  2060. else {
  2061. this.freezeSimulation = false;
  2062. this.start();
  2063. }
  2064. };
  2065. /**
  2066. * This function cleans the support nodes if they are not needed and adds them when they are.
  2067. *
  2068. * @param {boolean} [disableStart]
  2069. * @private
  2070. */
  2071. Network.prototype._configureSmoothCurves = function(disableStart) {
  2072. if (disableStart === undefined) {
  2073. disableStart = true;
  2074. }
  2075. if (this.constants.smoothCurves.enabled == true && this.constants.smoothCurves.dynamic == true) {
  2076. this._createBezierNodes();
  2077. // cleanup unused support nodes
  2078. for (var nodeId in this.sectors['support']['nodes']) {
  2079. if (this.sectors['support']['nodes'].hasOwnProperty(nodeId)) {
  2080. if (this.edges[this.sectors['support']['nodes'][nodeId].parentEdgeId] === undefined) {
  2081. delete this.sectors['support']['nodes'][nodeId];
  2082. }
  2083. }
  2084. }
  2085. }
  2086. else {
  2087. // delete the support nodes
  2088. this.sectors['support']['nodes'] = {};
  2089. for (var edgeId in this.edges) {
  2090. if (this.edges.hasOwnProperty(edgeId)) {
  2091. this.edges[edgeId].via = null;
  2092. }
  2093. }
  2094. }
  2095. this._updateCalculationNodes();
  2096. if (!disableStart) {
  2097. this.moving = true;
  2098. this.start();
  2099. }
  2100. };
  2101. /**
  2102. * Bezier curves require an anchor point to calculate the smooth flow. These points are nodes. These nodes are invisible but
  2103. * are used for the force calculation.
  2104. *
  2105. * @private
  2106. */
  2107. Network.prototype._createBezierNodes = function() {
  2108. if (this.constants.smoothCurves.enabled == true && this.constants.smoothCurves.dynamic == true) {
  2109. for (var edgeId in this.edges) {
  2110. if (this.edges.hasOwnProperty(edgeId)) {
  2111. var edge = this.edges[edgeId];
  2112. if (edge.via == null) {
  2113. var nodeId = "edgeId:".concat(edge.id);
  2114. this.sectors['support']['nodes'][nodeId] = new Node(
  2115. {id:nodeId,
  2116. mass:1,
  2117. shape:'circle',
  2118. image:"",
  2119. internalMultiplier:1
  2120. },{},{},this.constants);
  2121. edge.via = this.sectors['support']['nodes'][nodeId];
  2122. edge.via.parentEdgeId = edge.id;
  2123. edge.positionBezierNode();
  2124. }
  2125. }
  2126. }
  2127. }
  2128. };
  2129. /**
  2130. * load the functions that load the mixins into the prototype.
  2131. *
  2132. * @private
  2133. */
  2134. Network.prototype._initializeMixinLoaders = function () {
  2135. for (var mixin in MixinLoader) {
  2136. if (MixinLoader.hasOwnProperty(mixin)) {
  2137. Network.prototype[mixin] = MixinLoader[mixin];
  2138. }
  2139. }
  2140. };
  2141. /**
  2142. * Load the XY positions of the nodes into the dataset.
  2143. */
  2144. Network.prototype.storePosition = function() {
  2145. console.log("storePosition is deprecated: use .storePositions() from now on.")
  2146. this.storePositions();
  2147. };
  2148. /**
  2149. * Load the XY positions of the nodes into the dataset.
  2150. */
  2151. Network.prototype.storePositions = function() {
  2152. var dataArray = [];
  2153. for (var nodeId in this.nodes) {
  2154. if (this.nodes.hasOwnProperty(nodeId)) {
  2155. var node = this.nodes[nodeId];
  2156. var allowedToMoveX = !this.nodes.xFixed;
  2157. var allowedToMoveY = !this.nodes.yFixed;
  2158. if (this.nodesData._data[nodeId].x != Math.round(node.x) || this.nodesData._data[nodeId].y != Math.round(node.y)) {
  2159. dataArray.push({id:nodeId,x:Math.round(node.x),y:Math.round(node.y),allowedToMoveX:allowedToMoveX,allowedToMoveY:allowedToMoveY});
  2160. }
  2161. }
  2162. }
  2163. this.nodesData.update(dataArray);
  2164. };
  2165. /**
  2166. * Return the positions of the nodes.
  2167. */
  2168. Network.prototype.getPositions = function(ids) {
  2169. var dataArray = {};
  2170. if (ids !== undefined) {
  2171. if (Array.isArray(ids) == true) {
  2172. for (var i = 0; i < ids.length; i++) {
  2173. if (this.nodes[ids[i]] !== undefined) {
  2174. var node = this.nodes[ids[i]];
  2175. dataArray[ids[i]] = {x: Math.round(node.x), y: Math.round(node.y)};
  2176. }
  2177. }
  2178. }
  2179. else {
  2180. if (this.nodes[ids] !== undefined) {
  2181. var node = this.nodes[ids];
  2182. dataArray[ids] = {x: Math.round(node.x), y: Math.round(node.y)};
  2183. }
  2184. }
  2185. }
  2186. else {
  2187. for (var nodeId in this.nodes) {
  2188. if (this.nodes.hasOwnProperty(nodeId)) {
  2189. var node = this.nodes[nodeId];
  2190. dataArray[nodeId] = {x: Math.round(node.x), y: Math.round(node.y)};
  2191. }
  2192. }
  2193. }
  2194. return dataArray;
  2195. };
  2196. /**
  2197. * Center a node in view.
  2198. *
  2199. * @param {Number} nodeId
  2200. * @param {Number} [options]
  2201. */
  2202. Network.prototype.focusOnNode = function (nodeId, options) {
  2203. if (this.nodes.hasOwnProperty(nodeId)) {
  2204. if (options === undefined) {
  2205. options = {};
  2206. }
  2207. var nodePosition = {x: this.nodes[nodeId].x, y: this.nodes[nodeId].y};
  2208. options.position = nodePosition;
  2209. options.lockedOnNode = nodeId;
  2210. this.moveTo(options)
  2211. }
  2212. else {
  2213. console.log("This nodeId cannot be found.");
  2214. }
  2215. };
  2216. /**
  2217. *
  2218. * @param {Object} options | options.offset = {x:Number, y:Number} // offset from the center in DOM pixels
  2219. * | options.scale = Number // scale to move to
  2220. * | options.position = {x:Number, y:Number} // position to move to
  2221. * | options.animation = {duration:Number, easingFunction:String} || Boolean // position to move to
  2222. */
  2223. Network.prototype.moveTo = function (options) {
  2224. if (options === undefined) {
  2225. options = {};
  2226. return;
  2227. }
  2228. if (options.offset === undefined) {options.offset = {x: 0, y: 0}; }
  2229. if (options.offset.x === undefined) {options.offset.x = 0; }
  2230. if (options.offset.y === undefined) {options.offset.y = 0; }
  2231. if (options.scale === undefined) {options.scale = this._getScale(); }
  2232. if (options.position === undefined) {options.position = this._getTranslation();}
  2233. if (options.animation === undefined) {options.animation = {duration:0}; }
  2234. if (options.animation === false ) {options.animation = {duration:0}; }
  2235. if (options.animation === true ) {options.animation = {}; }
  2236. if (options.animation.duration === undefined) {options.animation.duration = 1000; } // default duration
  2237. if (options.animation.easingFunction === undefined) {options.animation.easingFunction = "easeInOutQuad"; } // default easing function
  2238. this.animateView(options);
  2239. };
  2240. /**
  2241. *
  2242. * @param {Object} options | options.offset = {x:Number, y:Number} // offset from the center in DOM pixels
  2243. * | options.time = Number // animation time in milliseconds
  2244. * | options.scale = Number // scale to animate to
  2245. * | options.position = {x:Number, y:Number} // position to animate to
  2246. * | options.easingFunction = String // linear, easeInQuad, easeOutQuad, easeInOutQuad,
  2247. * // easeInCubic, easeOutCubic, easeInOutCubic,
  2248. * // easeInQuart, easeOutQuart, easeInOutQuart,
  2249. * // easeInQuint, easeOutQuint, easeInOutQuint
  2250. */
  2251. Network.prototype.animateView = function (options) {
  2252. if (options === undefined) {
  2253. options = {};
  2254. return;
  2255. }
  2256. // release if something focussed on the node
  2257. this.releaseNode();
  2258. if (options.locked == true) {
  2259. this.lockedOnNodeId = options.lockedOnNode;
  2260. this.lockedOnNodeOffset = options.offset;
  2261. }
  2262. // forcefully complete the old animation if it was still running
  2263. if (this.easingTime != 0) {
  2264. this._transitionRedraw(1); // by setting easingtime to 1, we finish the animation.
  2265. }
  2266. this.sourceScale = this._getScale();
  2267. this.sourceTranslation = this._getTranslation();
  2268. this.targetScale = options.scale;
  2269. // set the scale so the viewCenter is based on the correct zoom level. This is overridden in the transitionRedraw
  2270. // but at least then we'll have the target transition
  2271. this._setScale(this.targetScale);
  2272. var viewCenter = this.DOMtoCanvas({x: 0.5 * this.frame.canvas.clientWidth, y: 0.5 * this.frame.canvas.clientHeight});
  2273. var distanceFromCenter = { // offset from view, distance view has to change by these x and y to center the node
  2274. x: viewCenter.x - options.position.x,
  2275. y: viewCenter.y - options.position.y
  2276. };
  2277. this.targetTranslation = {
  2278. x: this.sourceTranslation.x + distanceFromCenter.x * this.targetScale + options.offset.x,
  2279. y: this.sourceTranslation.y + distanceFromCenter.y * this.targetScale + options.offset.y
  2280. };
  2281. // if the time is set to 0, don't do an animation
  2282. if (options.animation.duration == 0) {
  2283. if (this.lockedOnNodeId != null) {
  2284. this._classicRedraw = this._redraw;
  2285. this._redraw = this._lockedRedraw;
  2286. }
  2287. else {
  2288. this._setScale(this.targetScale);
  2289. this._setTranslation(this.targetTranslation.x, this.targetTranslation.y);
  2290. this._redraw();
  2291. }
  2292. }
  2293. else {
  2294. this.animationSpeed = 1 / (this.renderRefreshRate * options.animation.duration * 0.001) || 1 / this.renderRefreshRate;
  2295. this.animationEasingFunction = options.animation.easingFunction;
  2296. this._classicRedraw = this._redraw;
  2297. this._redraw = this._transitionRedraw;
  2298. this._redraw();
  2299. this.moving = true;
  2300. this.start();
  2301. }
  2302. };
  2303. /**
  2304. * used to animate smoothly by hijacking the redraw function.
  2305. * @private
  2306. */
  2307. Network.prototype._lockedRedraw = function () {
  2308. var nodePosition = {x: this.nodes[this.lockedOnNodeId].x, y: this.nodes[this.lockedOnNodeId].y};
  2309. var viewCenter = this.DOMtoCanvas({x: 0.5 * this.frame.canvas.clientWidth, y: 0.5 * this.frame.canvas.clientHeight});
  2310. var distanceFromCenter = { // offset from view, distance view has to change by these x and y to center the node
  2311. x: viewCenter.x - nodePosition.x,
  2312. y: viewCenter.y - nodePosition.y
  2313. };
  2314. var sourceTranslation = this._getTranslation();
  2315. var targetTranslation = {
  2316. x: sourceTranslation.x + distanceFromCenter.x * this.scale + this.lockedOnNodeOffset.x,
  2317. y: sourceTranslation.y + distanceFromCenter.y * this.scale + this.lockedOnNodeOffset.y
  2318. };
  2319. this._setTranslation(targetTranslation.x,targetTranslation.y);
  2320. this._classicRedraw();
  2321. }
  2322. Network.prototype.releaseNode = function () {
  2323. if (this.lockedOnNodeId != null) {
  2324. this._redraw = this._classicRedraw;
  2325. this.lockedOnNodeId = null;
  2326. this.lockedOnNodeOffset = null;
  2327. }
  2328. }
  2329. /**
  2330. *
  2331. * @param easingTime
  2332. * @private
  2333. */
  2334. Network.prototype._transitionRedraw = function (easingTime) {
  2335. this.easingTime = easingTime || this.easingTime + this.animationSpeed;
  2336. this.easingTime += this.animationSpeed;
  2337. var progress = util.easingFunctions[this.animationEasingFunction](this.easingTime);
  2338. this._setScale(this.sourceScale + (this.targetScale - this.sourceScale) * progress);
  2339. this._setTranslation(
  2340. this.sourceTranslation.x + (this.targetTranslation.x - this.sourceTranslation.x) * progress,
  2341. this.sourceTranslation.y + (this.targetTranslation.y - this.sourceTranslation.y) * progress
  2342. );
  2343. this._classicRedraw();
  2344. this.moving = true;
  2345. // cleanup
  2346. if (this.easingTime >= 1.0) {
  2347. this.easingTime = 0;
  2348. if (this.lockedOnNodeId != null) {
  2349. this._redraw = this._lockedRedraw;
  2350. }
  2351. else {
  2352. this._redraw = this._classicRedraw;
  2353. }
  2354. this.emit("animationFinished");
  2355. }
  2356. };
  2357. Network.prototype._classicRedraw = function () {
  2358. // placeholder function to be overloaded by animations;
  2359. };
  2360. /**
  2361. * Returns true when the Network is active.
  2362. * @returns {boolean}
  2363. */
  2364. Network.prototype.isActive = function () {
  2365. return !this.activator || this.activator.active;
  2366. };
  2367. /**
  2368. * Sets the scale
  2369. * @returns {Number}
  2370. */
  2371. Network.prototype.setScale = function () {
  2372. return this._setScale();
  2373. };
  2374. /**
  2375. * Returns the scale
  2376. * @returns {Number}
  2377. */
  2378. Network.prototype.getScale = function () {
  2379. return this._getScale();
  2380. };
  2381. /**
  2382. * Returns the scale
  2383. * @returns {Number}
  2384. */
  2385. Network.prototype.getCenterCoordinates = function () {
  2386. return this.DOMtoCanvas({x: 0.5 * this.frame.canvas.clientWidth, y: 0.5 * this.frame.canvas.clientHeight});
  2387. };
  2388. Network.prototype.getBoundingBox = function(nodeId) {
  2389. if (this.nodes[nodeId] !== undefined) {
  2390. return this.nodes[nodeId].boundingBox;
  2391. }
  2392. }
  2393. module.exports = Network;