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.

2727 lines
82 KiB

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