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.

2516 lines
75 KiB

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