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.

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