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.

2296 lines
67 KiB

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