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.

2480 lines
74 KiB

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