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.

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