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.

2713 lines
82 KiB

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