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.

2236 lines
65 KiB

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