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.

2535 lines
76 KiB

10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
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 && this.constants.dragNodes == true) {
  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. var oldWidth = this.frame.canvas.width;
  1152. var oldHeight = this.frame.canvas.height;
  1153. if (width != this.constants.width || height != this.constants.height || this.frame.style.width != width || this.frame.style.height != height) {
  1154. this.frame.style.width = width;
  1155. this.frame.style.height = height;
  1156. this.frame.canvas.style.width = '100%';
  1157. this.frame.canvas.style.height = '100%';
  1158. this.frame.canvas.width = this.frame.canvas.clientWidth;
  1159. this.frame.canvas.height = this.frame.canvas.clientHeight;
  1160. this.constants.width = width;
  1161. this.constants.height = height;
  1162. emitEvent = true;
  1163. }
  1164. else {
  1165. // this would adapt the width of the canvas to the width from 100% if and only if
  1166. // there is a change.
  1167. if (this.frame.canvas.width != this.frame.canvas.clientWidth) {
  1168. this.frame.canvas.width = this.frame.canvas.clientWidth;
  1169. emitEvent = true;
  1170. }
  1171. if (this.frame.canvas.height != this.frame.canvas.clientHeight) {
  1172. this.frame.canvas.height = this.frame.canvas.clientHeight;
  1173. emitEvent = true;
  1174. }
  1175. }
  1176. if (emitEvent == true) {
  1177. this.emit('resize', {width:this.frame.canvas.width,height:this.frame.canvas.height, oldWidth: oldWidth, oldHeight: oldHeight});
  1178. }
  1179. };
  1180. /**
  1181. * Set a data set with nodes for the network
  1182. * @param {Array | DataSet | DataView} nodes The data containing the nodes.
  1183. * @private
  1184. */
  1185. Network.prototype._setNodes = function(nodes) {
  1186. var oldNodesData = this.nodesData;
  1187. if (nodes instanceof DataSet || nodes instanceof DataView) {
  1188. this.nodesData = nodes;
  1189. }
  1190. else if (Array.isArray(nodes)) {
  1191. this.nodesData = new DataSet();
  1192. this.nodesData.add(nodes);
  1193. }
  1194. else if (!nodes) {
  1195. this.nodesData = new DataSet();
  1196. }
  1197. else {
  1198. throw new TypeError('Array or DataSet expected');
  1199. }
  1200. if (oldNodesData) {
  1201. // unsubscribe from old dataset
  1202. util.forEach(this.nodesListeners, function (callback, event) {
  1203. oldNodesData.off(event, callback);
  1204. });
  1205. }
  1206. // remove drawn nodes
  1207. this.nodes = {};
  1208. if (this.nodesData) {
  1209. // subscribe to new dataset
  1210. var me = this;
  1211. util.forEach(this.nodesListeners, function (callback, event) {
  1212. me.nodesData.on(event, callback);
  1213. });
  1214. // draw all new nodes
  1215. var ids = this.nodesData.getIds();
  1216. this._addNodes(ids);
  1217. }
  1218. this._updateSelection();
  1219. };
  1220. /**
  1221. * Add nodes
  1222. * @param {Number[] | String[]} ids
  1223. * @private
  1224. */
  1225. Network.prototype._addNodes = function(ids) {
  1226. var id;
  1227. for (var i = 0, len = ids.length; i < len; i++) {
  1228. id = ids[i];
  1229. var data = this.nodesData.get(id);
  1230. var node = new Node(data, this.images, this.groups, this.constants);
  1231. this.nodes[id] = node; // note: this may replace an existing node
  1232. if ((node.xFixed == false || node.yFixed == false) && (node.x === null || node.y === null)) {
  1233. var radius = 10 * 0.1*ids.length + 10;
  1234. var angle = 2 * Math.PI * Math.random();
  1235. if (node.xFixed == false) {node.x = radius * Math.cos(angle);}
  1236. if (node.yFixed == false) {node.y = radius * Math.sin(angle);}
  1237. }
  1238. this.moving = true;
  1239. }
  1240. this._updateNodeIndexList();
  1241. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  1242. this._resetLevels();
  1243. this._setupHierarchicalLayout();
  1244. }
  1245. this._updateCalculationNodes();
  1246. this._reconnectEdges();
  1247. this._updateValueRange(this.nodes);
  1248. this.updateLabels();
  1249. };
  1250. /**
  1251. * Update existing nodes, or create them when not yet existing
  1252. * @param {Number[] | String[]} ids
  1253. * @private
  1254. */
  1255. Network.prototype._updateNodes = function(ids,changedData) {
  1256. var nodes = this.nodes;
  1257. for (var i = 0, len = ids.length; i < len; i++) {
  1258. var id = ids[i];
  1259. var node = nodes[id];
  1260. var data = changedData[i];
  1261. if (node) {
  1262. // update node
  1263. node.setProperties(data, this.constants);
  1264. }
  1265. else {
  1266. // create node
  1267. node = new Node(properties, this.images, this.groups, this.constants);
  1268. nodes[id] = node;
  1269. }
  1270. }
  1271. this.moving = true;
  1272. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  1273. this._resetLevels();
  1274. this._setupHierarchicalLayout();
  1275. }
  1276. this._updateNodeIndexList();
  1277. this._updateValueRange(nodes);
  1278. };
  1279. /**
  1280. * Remove existing nodes. If nodes do not exist, the method will just ignore it.
  1281. * @param {Number[] | String[]} ids
  1282. * @private
  1283. */
  1284. Network.prototype._removeNodes = function(ids) {
  1285. var nodes = this.nodes;
  1286. for (var i = 0, len = ids.length; i < len; i++) {
  1287. var id = ids[i];
  1288. delete nodes[id];
  1289. }
  1290. this._updateNodeIndexList();
  1291. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  1292. this._resetLevels();
  1293. this._setupHierarchicalLayout();
  1294. }
  1295. this._updateCalculationNodes();
  1296. this._reconnectEdges();
  1297. this._updateSelection();
  1298. this._updateValueRange(nodes);
  1299. };
  1300. /**
  1301. * Load edges by reading the data table
  1302. * @param {Array | DataSet | DataView} edges The data containing the edges.
  1303. * @private
  1304. * @private
  1305. */
  1306. Network.prototype._setEdges = function(edges) {
  1307. var oldEdgesData = this.edgesData;
  1308. if (edges instanceof DataSet || edges instanceof DataView) {
  1309. this.edgesData = edges;
  1310. }
  1311. else if (Array.isArray(edges)) {
  1312. this.edgesData = new DataSet();
  1313. this.edgesData.add(edges);
  1314. }
  1315. else if (!edges) {
  1316. this.edgesData = new DataSet();
  1317. }
  1318. else {
  1319. throw new TypeError('Array or DataSet expected');
  1320. }
  1321. if (oldEdgesData) {
  1322. // unsubscribe from old dataset
  1323. util.forEach(this.edgesListeners, function (callback, event) {
  1324. oldEdgesData.off(event, callback);
  1325. });
  1326. }
  1327. // remove drawn edges
  1328. this.edges = {};
  1329. if (this.edgesData) {
  1330. // subscribe to new dataset
  1331. var me = this;
  1332. util.forEach(this.edgesListeners, function (callback, event) {
  1333. me.edgesData.on(event, callback);
  1334. });
  1335. // draw all new nodes
  1336. var ids = this.edgesData.getIds();
  1337. this._addEdges(ids);
  1338. }
  1339. this._reconnectEdges();
  1340. };
  1341. /**
  1342. * Add edges
  1343. * @param {Number[] | String[]} ids
  1344. * @private
  1345. */
  1346. Network.prototype._addEdges = function (ids) {
  1347. var edges = this.edges,
  1348. edgesData = this.edgesData;
  1349. for (var i = 0, len = ids.length; i < len; i++) {
  1350. var id = ids[i];
  1351. var oldEdge = edges[id];
  1352. if (oldEdge) {
  1353. oldEdge.disconnect();
  1354. }
  1355. var data = edgesData.get(id, {"showInternalIds" : true});
  1356. edges[id] = new Edge(data, this, this.constants);
  1357. }
  1358. this.moving = true;
  1359. this._updateValueRange(edges);
  1360. this._createBezierNodes();
  1361. this._updateCalculationNodes();
  1362. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  1363. this._resetLevels();
  1364. this._setupHierarchicalLayout();
  1365. }
  1366. };
  1367. /**
  1368. * Update existing edges, or create them when not yet existing
  1369. * @param {Number[] | String[]} ids
  1370. * @private
  1371. */
  1372. Network.prototype._updateEdges = function (ids) {
  1373. var edges = this.edges,
  1374. edgesData = this.edgesData;
  1375. for (var i = 0, len = ids.length; i < len; i++) {
  1376. var id = ids[i];
  1377. var data = edgesData.get(id);
  1378. var edge = edges[id];
  1379. if (edge) {
  1380. // update edge
  1381. edge.disconnect();
  1382. edge.setProperties(data, this.constants);
  1383. edge.connect();
  1384. }
  1385. else {
  1386. // create edge
  1387. edge = new Edge(data, this, this.constants);
  1388. this.edges[id] = edge;
  1389. }
  1390. }
  1391. this._createBezierNodes();
  1392. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  1393. this._resetLevels();
  1394. this._setupHierarchicalLayout();
  1395. }
  1396. this.moving = true;
  1397. this._updateValueRange(edges);
  1398. };
  1399. /**
  1400. * Remove existing edges. Non existing ids will be ignored
  1401. * @param {Number[] | String[]} ids
  1402. * @private
  1403. */
  1404. Network.prototype._removeEdges = function (ids) {
  1405. var edges = this.edges;
  1406. for (var i = 0, len = ids.length; i < len; i++) {
  1407. var id = ids[i];
  1408. var edge = edges[id];
  1409. if (edge) {
  1410. if (edge.via != null) {
  1411. delete this.sectors['support']['nodes'][edge.via.id];
  1412. }
  1413. edge.disconnect();
  1414. delete edges[id];
  1415. }
  1416. }
  1417. this.moving = true;
  1418. this._updateValueRange(edges);
  1419. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  1420. this._resetLevels();
  1421. this._setupHierarchicalLayout();
  1422. }
  1423. this._updateCalculationNodes();
  1424. };
  1425. /**
  1426. * Reconnect all edges
  1427. * @private
  1428. */
  1429. Network.prototype._reconnectEdges = function() {
  1430. var id,
  1431. nodes = this.nodes,
  1432. edges = this.edges;
  1433. for (id in nodes) {
  1434. if (nodes.hasOwnProperty(id)) {
  1435. nodes[id].edges = [];
  1436. nodes[id].dynamicEdges = [];
  1437. }
  1438. }
  1439. for (id in edges) {
  1440. if (edges.hasOwnProperty(id)) {
  1441. var edge = edges[id];
  1442. edge.from = null;
  1443. edge.to = null;
  1444. edge.connect();
  1445. }
  1446. }
  1447. };
  1448. /**
  1449. * Update the values of all object in the given array according to the current
  1450. * value range of the objects in the array.
  1451. * @param {Object} obj An object containing a set of Edges or Nodes
  1452. * The objects must have a method getValue() and
  1453. * setValueRange(min, max).
  1454. * @private
  1455. */
  1456. Network.prototype._updateValueRange = function(obj) {
  1457. var id;
  1458. // determine the range of the objects
  1459. var valueMin = undefined;
  1460. var valueMax = undefined;
  1461. for (id in obj) {
  1462. if (obj.hasOwnProperty(id)) {
  1463. var value = obj[id].getValue();
  1464. if (value !== undefined) {
  1465. valueMin = (valueMin === undefined) ? value : Math.min(value, valueMin);
  1466. valueMax = (valueMax === undefined) ? value : Math.max(value, valueMax);
  1467. }
  1468. }
  1469. }
  1470. // adjust the range of all objects
  1471. if (valueMin !== undefined && valueMax !== undefined) {
  1472. for (id in obj) {
  1473. if (obj.hasOwnProperty(id)) {
  1474. obj[id].setValueRange(valueMin, valueMax);
  1475. }
  1476. }
  1477. }
  1478. };
  1479. /**
  1480. * Redraw the network with the current data
  1481. * chart will be resized too.
  1482. */
  1483. Network.prototype.redraw = function() {
  1484. this.setSize(this.constants.width, this.constants.height);
  1485. this._redraw();
  1486. };
  1487. /**
  1488. * Redraw the network with the current data
  1489. * @private
  1490. */
  1491. Network.prototype._redraw = function() {
  1492. var ctx = this.frame.canvas.getContext('2d');
  1493. // clear the canvas
  1494. var w = this.frame.canvas.width;
  1495. var h = this.frame.canvas.height;
  1496. ctx.clearRect(0, 0, w, h);
  1497. // set scaling and translation
  1498. ctx.save();
  1499. ctx.translate(this.translation.x, this.translation.y);
  1500. ctx.scale(this.scale, this.scale);
  1501. this.canvasTopLeft = {
  1502. "x": this._XconvertDOMtoCanvas(0),
  1503. "y": this._YconvertDOMtoCanvas(0)
  1504. };
  1505. this.canvasBottomRight = {
  1506. "x": this._XconvertDOMtoCanvas(this.frame.canvas.clientWidth),
  1507. "y": this._YconvertDOMtoCanvas(this.frame.canvas.clientHeight)
  1508. };
  1509. this._doInAllSectors("_drawAllSectorNodes",ctx);
  1510. if (this.drag.dragging == false || this.drag.dragging === undefined || this.constants.hideEdgesOnDrag == false) {
  1511. this._doInAllSectors("_drawEdges",ctx);
  1512. }
  1513. if (this.drag.dragging == false || this.drag.dragging === undefined || this.constants.hideNodesOnDrag == false) {
  1514. this._doInAllSectors("_drawNodes",ctx,false);
  1515. }
  1516. if (this.controlNodesActive == true) {
  1517. this._doInAllSectors("_drawControlNodes",ctx);
  1518. }
  1519. // this._doInSupportSector("_drawNodes",ctx,true);
  1520. // this._drawTree(ctx,"#F00F0F");
  1521. // restore original scaling and translation
  1522. ctx.restore();
  1523. };
  1524. /**
  1525. * Set the translation of the network
  1526. * @param {Number} offsetX Horizontal offset
  1527. * @param {Number} offsetY Vertical offset
  1528. * @private
  1529. */
  1530. Network.prototype._setTranslation = function(offsetX, offsetY) {
  1531. if (this.translation === undefined) {
  1532. this.translation = {
  1533. x: 0,
  1534. y: 0
  1535. };
  1536. }
  1537. if (offsetX !== undefined) {
  1538. this.translation.x = offsetX;
  1539. }
  1540. if (offsetY !== undefined) {
  1541. this.translation.y = offsetY;
  1542. }
  1543. this.emit('viewChanged');
  1544. };
  1545. /**
  1546. * Get the translation of the network
  1547. * @return {Object} translation An object with parameters x and y, both a number
  1548. * @private
  1549. */
  1550. Network.prototype._getTranslation = function() {
  1551. return {
  1552. x: this.translation.x,
  1553. y: this.translation.y
  1554. };
  1555. };
  1556. /**
  1557. * Scale the network
  1558. * @param {Number} scale Scaling factor 1.0 is unscaled
  1559. * @private
  1560. */
  1561. Network.prototype._setScale = function(scale) {
  1562. this.scale = scale;
  1563. };
  1564. /**
  1565. * Get the current scale of the network
  1566. * @return {Number} scale Scaling factor 1.0 is unscaled
  1567. * @private
  1568. */
  1569. Network.prototype._getScale = function() {
  1570. return this.scale;
  1571. };
  1572. /**
  1573. * Convert the X coordinate in DOM-space (coordinate point in browser relative to the container div) to
  1574. * the X coordinate in canvas-space (the simulation sandbox, which the camera looks upon)
  1575. * @param {number} x
  1576. * @returns {number}
  1577. * @private
  1578. */
  1579. Network.prototype._XconvertDOMtoCanvas = function(x) {
  1580. return (x - this.translation.x) / this.scale;
  1581. };
  1582. /**
  1583. * Convert the X coordinate in canvas-space (the simulation sandbox, which the camera looks upon) to
  1584. * the X coordinate in DOM-space (coordinate point in browser relative to the container div)
  1585. * @param {number} x
  1586. * @returns {number}
  1587. * @private
  1588. */
  1589. Network.prototype._XconvertCanvasToDOM = function(x) {
  1590. return x * this.scale + this.translation.x;
  1591. };
  1592. /**
  1593. * Convert the Y coordinate in DOM-space (coordinate point in browser relative to the container div) to
  1594. * the Y coordinate in canvas-space (the simulation sandbox, which the camera looks upon)
  1595. * @param {number} y
  1596. * @returns {number}
  1597. * @private
  1598. */
  1599. Network.prototype._YconvertDOMtoCanvas = function(y) {
  1600. return (y - this.translation.y) / this.scale;
  1601. };
  1602. /**
  1603. * Convert the Y coordinate in canvas-space (the simulation sandbox, which the camera looks upon) to
  1604. * the Y coordinate in DOM-space (coordinate point in browser relative to the container div)
  1605. * @param {number} y
  1606. * @returns {number}
  1607. * @private
  1608. */
  1609. Network.prototype._YconvertCanvasToDOM = function(y) {
  1610. return y * this.scale + this.translation.y ;
  1611. };
  1612. /**
  1613. *
  1614. * @param {object} pos = {x: number, y: number}
  1615. * @returns {{x: number, y: number}}
  1616. * @constructor
  1617. */
  1618. Network.prototype.canvasToDOM = function (pos) {
  1619. return {x: this._XconvertCanvasToDOM(pos.x), y: this._YconvertCanvasToDOM(pos.y)};
  1620. };
  1621. /**
  1622. *
  1623. * @param {object} pos = {x: number, y: number}
  1624. * @returns {{x: number, y: number}}
  1625. * @constructor
  1626. */
  1627. Network.prototype.DOMtoCanvas = function (pos) {
  1628. return {x: this._XconvertDOMtoCanvas(pos.x), y: this._YconvertDOMtoCanvas(pos.y)};
  1629. };
  1630. /**
  1631. * Redraw all nodes
  1632. * The 2d context of a HTML canvas can be retrieved by canvas.getContext('2d');
  1633. * @param {CanvasRenderingContext2D} ctx
  1634. * @param {Boolean} [alwaysShow]
  1635. * @private
  1636. */
  1637. Network.prototype._drawNodes = function(ctx,alwaysShow) {
  1638. if (alwaysShow === undefined) {
  1639. alwaysShow = false;
  1640. }
  1641. // first draw the unselected nodes
  1642. var nodes = this.nodes;
  1643. var selected = [];
  1644. for (var id in nodes) {
  1645. if (nodes.hasOwnProperty(id)) {
  1646. nodes[id].setScaleAndPos(this.scale,this.canvasTopLeft,this.canvasBottomRight);
  1647. if (nodes[id].isSelected()) {
  1648. selected.push(id);
  1649. }
  1650. else {
  1651. if (nodes[id].inArea() || alwaysShow) {
  1652. nodes[id].draw(ctx);
  1653. }
  1654. }
  1655. }
  1656. }
  1657. // draw the selected nodes on top
  1658. for (var s = 0, sMax = selected.length; s < sMax; s++) {
  1659. if (nodes[selected[s]].inArea() || alwaysShow) {
  1660. nodes[selected[s]].draw(ctx);
  1661. }
  1662. }
  1663. };
  1664. /**
  1665. * Redraw all edges
  1666. * The 2d context of a HTML canvas can be retrieved by canvas.getContext('2d');
  1667. * @param {CanvasRenderingContext2D} ctx
  1668. * @private
  1669. */
  1670. Network.prototype._drawEdges = function(ctx) {
  1671. var edges = this.edges;
  1672. for (var id in edges) {
  1673. if (edges.hasOwnProperty(id)) {
  1674. var edge = edges[id];
  1675. edge.setScale(this.scale);
  1676. if (edge.connected) {
  1677. edges[id].draw(ctx);
  1678. }
  1679. }
  1680. }
  1681. };
  1682. /**
  1683. * Redraw all edges
  1684. * The 2d context of a HTML canvas can be retrieved by canvas.getContext('2d');
  1685. * @param {CanvasRenderingContext2D} ctx
  1686. * @private
  1687. */
  1688. Network.prototype._drawControlNodes = function(ctx) {
  1689. var edges = this.edges;
  1690. for (var id in edges) {
  1691. if (edges.hasOwnProperty(id)) {
  1692. edges[id]._drawControlNodes(ctx);
  1693. }
  1694. }
  1695. };
  1696. /**
  1697. * Find a stable position for all nodes
  1698. * @private
  1699. */
  1700. Network.prototype._stabilize = function() {
  1701. if (this.constants.freezeForStabilization == true) {
  1702. this._freezeDefinedNodes();
  1703. }
  1704. // find stable position
  1705. var count = 0;
  1706. while (this.moving && count < this.constants.stabilizationIterations) {
  1707. this._physicsTick();
  1708. count++;
  1709. }
  1710. this.zoomExtent(undefined,false,true);
  1711. if (this.constants.freezeForStabilization == true) {
  1712. this._restoreFrozenNodes();
  1713. }
  1714. };
  1715. /**
  1716. * When initializing and stabilizing, we can freeze nodes with a predefined position. This greatly speeds up stabilization
  1717. * because only the supportnodes for the smoothCurves have to settle.
  1718. *
  1719. * @private
  1720. */
  1721. Network.prototype._freezeDefinedNodes = function() {
  1722. var nodes = this.nodes;
  1723. for (var id in nodes) {
  1724. if (nodes.hasOwnProperty(id)) {
  1725. if (nodes[id].x != null && nodes[id].y != null) {
  1726. nodes[id].fixedData.x = nodes[id].xFixed;
  1727. nodes[id].fixedData.y = nodes[id].yFixed;
  1728. nodes[id].xFixed = true;
  1729. nodes[id].yFixed = true;
  1730. }
  1731. }
  1732. }
  1733. };
  1734. /**
  1735. * Unfreezes the nodes that have been frozen by _freezeDefinedNodes.
  1736. *
  1737. * @private
  1738. */
  1739. Network.prototype._restoreFrozenNodes = function() {
  1740. var nodes = this.nodes;
  1741. for (var id in nodes) {
  1742. if (nodes.hasOwnProperty(id)) {
  1743. if (nodes[id].fixedData.x != null) {
  1744. nodes[id].xFixed = nodes[id].fixedData.x;
  1745. nodes[id].yFixed = nodes[id].fixedData.y;
  1746. }
  1747. }
  1748. }
  1749. };
  1750. /**
  1751. * Check if any of the nodes is still moving
  1752. * @param {number} vmin the minimum velocity considered as 'moving'
  1753. * @return {boolean} true if moving, false if non of the nodes is moving
  1754. * @private
  1755. */
  1756. Network.prototype._isMoving = function(vmin) {
  1757. var nodes = this.nodes;
  1758. for (var id in nodes) {
  1759. if (nodes.hasOwnProperty(id) && nodes[id].isMoving(vmin)) {
  1760. return true;
  1761. }
  1762. }
  1763. return false;
  1764. };
  1765. /**
  1766. * /**
  1767. * Perform one discrete step for all nodes
  1768. *
  1769. * @private
  1770. */
  1771. Network.prototype._discreteStepNodes = function() {
  1772. var interval = this.physicsDiscreteStepsize;
  1773. var nodes = this.nodes;
  1774. var nodeId;
  1775. var nodesPresent = false;
  1776. if (this.constants.maxVelocity > 0) {
  1777. for (nodeId in nodes) {
  1778. if (nodes.hasOwnProperty(nodeId)) {
  1779. nodes[nodeId].discreteStepLimited(interval, this.constants.maxVelocity);
  1780. nodesPresent = true;
  1781. }
  1782. }
  1783. }
  1784. else {
  1785. for (nodeId in nodes) {
  1786. if (nodes.hasOwnProperty(nodeId)) {
  1787. nodes[nodeId].discreteStep(interval);
  1788. nodesPresent = true;
  1789. }
  1790. }
  1791. }
  1792. if (nodesPresent == true) {
  1793. var vminCorrected = this.constants.minVelocity / Math.max(this.scale,0.05);
  1794. if (vminCorrected > 0.5*this.constants.maxVelocity) {
  1795. return true;
  1796. }
  1797. else {
  1798. return this._isMoving(vminCorrected);
  1799. }
  1800. }
  1801. return false;
  1802. };
  1803. /**
  1804. * A single simulation step (or "tick") in the physics simulation
  1805. *
  1806. * @private
  1807. */
  1808. Network.prototype._physicsTick = function() {
  1809. if (!this.freezeSimulation) {
  1810. if (this.moving == true) {
  1811. var mainMovingStatus = false;
  1812. var supportMovingStatus = false;
  1813. this._doInAllActiveSectors("_initializeForceCalculation");
  1814. var mainMoving = this._doInAllActiveSectors("_discreteStepNodes");
  1815. if (this.constants.smoothCurves.enabled == true && this.constants.smoothCurves.dynamic == true) {
  1816. supportMovingStatus = this._doInSupportSector("_discreteStepNodes");
  1817. }
  1818. // gather movement data from all sectors, if one moves, we are NOT stabilzied
  1819. for (var i = 0; i < mainMoving.length; i++) {mainMovingStatus = mainMoving[0] || mainMovingStatus;}
  1820. // determine if the network has stabilzied
  1821. this.moving = mainMovingStatus || supportMovingStatus;
  1822. this.stabilizationIterations++;
  1823. }
  1824. }
  1825. };
  1826. /**
  1827. * This function runs one step of the animation. It calls an x amount of physics ticks and one render tick.
  1828. * It reschedules itself at the beginning of the function
  1829. *
  1830. * @private
  1831. */
  1832. Network.prototype._animationStep = function() {
  1833. // reset the timer so a new scheduled animation step can be set
  1834. this.timer = undefined;
  1835. // handle the keyboad movement
  1836. this._handleNavigation();
  1837. // this schedules a new animation step
  1838. this.start();
  1839. // start the physics simulation
  1840. var calculationTime = Date.now();
  1841. var maxSteps = 1;
  1842. this._physicsTick();
  1843. var timeRequired = Date.now() - calculationTime;
  1844. while (timeRequired < 0.9*(this.renderTimestep - this.renderTime) && maxSteps < this.maxPhysicsTicksPerRender) {
  1845. this._physicsTick();
  1846. timeRequired = Date.now() - calculationTime;
  1847. maxSteps++;
  1848. }
  1849. // start the rendering process
  1850. var renderTime = Date.now();
  1851. this._redraw();
  1852. this.renderTime = Date.now() - renderTime;
  1853. };
  1854. if (typeof window !== 'undefined') {
  1855. window.requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame ||
  1856. window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;
  1857. }
  1858. /**
  1859. * Schedule a animation step with the refreshrate interval.
  1860. */
  1861. Network.prototype.start = function() {
  1862. if (this.moving == true || this.xIncrement != 0 || this.yIncrement != 0 || this.zoomIncrement != 0) {
  1863. if (this.startedStabilization == false) {
  1864. this.emit("startStabilization");
  1865. this.startedStabilization = true;
  1866. }
  1867. if (!this.timer) {
  1868. var ua = navigator.userAgent.toLowerCase();
  1869. var requiresTimeout = false;
  1870. if (ua.indexOf('msie 9.0') != -1) { // IE 9
  1871. requiresTimeout = true;
  1872. }
  1873. else if (ua.indexOf('safari') != -1) { // safari
  1874. if (ua.indexOf('chrome') <= -1) {
  1875. requiresTimeout = true;
  1876. }
  1877. }
  1878. if (requiresTimeout == true) {
  1879. this.timer = window.setTimeout(this._animationStep.bind(this), this.renderTimestep); // wait this.renderTimeStep milliseconds and perform the animation step function
  1880. }
  1881. else{
  1882. this.timer = window.requestAnimationFrame(this._animationStep.bind(this), this.renderTimestep); // wait this.renderTimeStep milliseconds and perform the animation step function
  1883. }
  1884. }
  1885. }
  1886. else {
  1887. this._redraw();
  1888. if (this.stabilizationIterations > 0) {
  1889. // trigger the "stabilized" event.
  1890. // The event is triggered on the next tick, to prevent the case that
  1891. // it is fired while initializing the Network, in which case you would not
  1892. // be able to catch it
  1893. var me = this;
  1894. var params = {
  1895. iterations: me.stabilizationIterations
  1896. };
  1897. me.stabilizationIterations = 0;
  1898. me.startedStabilization = false;
  1899. setTimeout(function () {
  1900. me.emit("stabilized", params);
  1901. }, 0);
  1902. }
  1903. }
  1904. };
  1905. /**
  1906. * Move the network according to the keyboard presses.
  1907. *
  1908. * @private
  1909. */
  1910. Network.prototype._handleNavigation = function() {
  1911. if (this.xIncrement != 0 || this.yIncrement != 0) {
  1912. var translation = this._getTranslation();
  1913. this._setTranslation(translation.x+this.xIncrement, translation.y+this.yIncrement);
  1914. }
  1915. if (this.zoomIncrement != 0) {
  1916. var center = {
  1917. x: this.frame.canvas.clientWidth / 2,
  1918. y: this.frame.canvas.clientHeight / 2
  1919. };
  1920. this._zoom(this.scale*(1 + this.zoomIncrement), center);
  1921. }
  1922. };
  1923. /**
  1924. * Freeze the _animationStep
  1925. */
  1926. Network.prototype.toggleFreeze = function() {
  1927. if (this.freezeSimulation == false) {
  1928. this.freezeSimulation = true;
  1929. }
  1930. else {
  1931. this.freezeSimulation = false;
  1932. this.start();
  1933. }
  1934. };
  1935. /**
  1936. * This function cleans the support nodes if they are not needed and adds them when they are.
  1937. *
  1938. * @param {boolean} [disableStart]
  1939. * @private
  1940. */
  1941. Network.prototype._configureSmoothCurves = function(disableStart) {
  1942. if (disableStart === undefined) {
  1943. disableStart = true;
  1944. }
  1945. if (this.constants.smoothCurves.enabled == true && this.constants.smoothCurves.dynamic == true) {
  1946. this._createBezierNodes();
  1947. // cleanup unused support nodes
  1948. for (var nodeId in this.sectors['support']['nodes']) {
  1949. if (this.sectors['support']['nodes'].hasOwnProperty(nodeId)) {
  1950. if (this.edges[this.sectors['support']['nodes'][nodeId].parentEdgeId] === undefined) {
  1951. delete this.sectors['support']['nodes'][nodeId];
  1952. }
  1953. }
  1954. }
  1955. }
  1956. else {
  1957. // delete the support nodes
  1958. this.sectors['support']['nodes'] = {};
  1959. for (var edgeId in this.edges) {
  1960. if (this.edges.hasOwnProperty(edgeId)) {
  1961. this.edges[edgeId].via = null;
  1962. }
  1963. }
  1964. }
  1965. this._updateCalculationNodes();
  1966. if (!disableStart) {
  1967. this.moving = true;
  1968. this.start();
  1969. }
  1970. };
  1971. /**
  1972. * Bezier curves require an anchor point to calculate the smooth flow. These points are nodes. These nodes are invisible but
  1973. * are used for the force calculation.
  1974. *
  1975. * @private
  1976. */
  1977. Network.prototype._createBezierNodes = function() {
  1978. if (this.constants.smoothCurves.enabled == true && this.constants.smoothCurves.dynamic == true) {
  1979. for (var edgeId in this.edges) {
  1980. if (this.edges.hasOwnProperty(edgeId)) {
  1981. var edge = this.edges[edgeId];
  1982. if (edge.via == null) {
  1983. var nodeId = "edgeId:".concat(edge.id);
  1984. this.sectors['support']['nodes'][nodeId] = new Node(
  1985. {id:nodeId,
  1986. mass:1,
  1987. shape:'circle',
  1988. image:"",
  1989. internalMultiplier:1
  1990. },{},{},this.constants);
  1991. edge.via = this.sectors['support']['nodes'][nodeId];
  1992. edge.via.parentEdgeId = edge.id;
  1993. edge.positionBezierNode();
  1994. }
  1995. }
  1996. }
  1997. }
  1998. };
  1999. /**
  2000. * load the functions that load the mixins into the prototype.
  2001. *
  2002. * @private
  2003. */
  2004. Network.prototype._initializeMixinLoaders = function () {
  2005. for (var mixin in MixinLoader) {
  2006. if (MixinLoader.hasOwnProperty(mixin)) {
  2007. Network.prototype[mixin] = MixinLoader[mixin];
  2008. }
  2009. }
  2010. };
  2011. /**
  2012. * Load the XY positions of the nodes into the dataset.
  2013. */
  2014. Network.prototype.storePosition = function() {
  2015. console.log("storePosition is depricated: use .storePositions() from now on.")
  2016. this.storePositions();
  2017. };
  2018. /**
  2019. * Load the XY positions of the nodes into the dataset.
  2020. */
  2021. Network.prototype.storePositions = function() {
  2022. var dataArray = [];
  2023. for (var nodeId in this.nodes) {
  2024. if (this.nodes.hasOwnProperty(nodeId)) {
  2025. var node = this.nodes[nodeId];
  2026. var allowedToMoveX = !this.nodes.xFixed;
  2027. var allowedToMoveY = !this.nodes.yFixed;
  2028. if (this.nodesData._data[nodeId].x != Math.round(node.x) || this.nodesData._data[nodeId].y != Math.round(node.y)) {
  2029. dataArray.push({id:nodeId,x:Math.round(node.x),y:Math.round(node.y),allowedToMoveX:allowedToMoveX,allowedToMoveY:allowedToMoveY});
  2030. }
  2031. }
  2032. }
  2033. this.nodesData.update(dataArray);
  2034. };
  2035. /**
  2036. * Return the positions of the nodes.
  2037. */
  2038. Network.prototype.getPositions = function(ids) {
  2039. var dataArray = {};
  2040. if (ids !== undefined) {
  2041. if (Array.isArray(ids) == true) {
  2042. for (var i = 0; i < ids.length; i++) {
  2043. if (this.nodes[ids[i]] !== undefined) {
  2044. var node = this.nodes[ids[i]];
  2045. dataArray[ids[i]] = {x: Math.round(node.x), y: Math.round(node.y)};
  2046. }
  2047. }
  2048. }
  2049. else {
  2050. if (this.nodes[ids] !== undefined) {
  2051. var node = this.nodes[ids];
  2052. dataArray[ids] = {x: Math.round(node.x), y: Math.round(node.y)};
  2053. }
  2054. }
  2055. }
  2056. else {
  2057. for (var nodeId in this.nodes) {
  2058. if (this.nodes.hasOwnProperty(nodeId)) {
  2059. var node = this.nodes[nodeId];
  2060. dataArray[nodeId] = {x: Math.round(node.x), y: Math.round(node.y)};
  2061. }
  2062. }
  2063. }
  2064. return dataArray;
  2065. };
  2066. /**
  2067. * Center a node in view.
  2068. *
  2069. * @param {Number} nodeId
  2070. * @param {Number} [options]
  2071. */
  2072. Network.prototype.focusOnNode = function (nodeId, options) {
  2073. if (this.nodes.hasOwnProperty(nodeId)) {
  2074. if (options === undefined) {
  2075. options = {};
  2076. }
  2077. var nodePosition = {x: this.nodes[nodeId].x, y: this.nodes[nodeId].y};
  2078. options.position = nodePosition;
  2079. options.lockedOnNode = nodeId;
  2080. this.moveTo(options)
  2081. }
  2082. else {
  2083. console.log("This nodeId cannot be found.");
  2084. }
  2085. };
  2086. /**
  2087. *
  2088. * @param {Object} options | options.offset = {x:Number, y:Number} // offset from the center in DOM pixels
  2089. * | options.scale = Number // scale to move to
  2090. * | options.position = {x:Number, y:Number} // position to move to
  2091. * | options.animation = {duration:Number, easingFunction:String} || Boolean // position to move to
  2092. */
  2093. Network.prototype.moveTo = function (options) {
  2094. if (options === undefined) {
  2095. options = {};
  2096. return;
  2097. }
  2098. if (options.offset === undefined) {options.offset = {x: 0, y: 0}; }
  2099. if (options.offset.x === undefined) {options.offset.x = 0; }
  2100. if (options.offset.y === undefined) {options.offset.y = 0; }
  2101. if (options.scale === undefined) {options.scale = this._getScale(); }
  2102. if (options.position === undefined) {options.position = this._getTranslation();}
  2103. if (options.animation === undefined) {options.animation = {duration:0}; }
  2104. if (options.animation === false ) {options.animation = {duration:0}; }
  2105. if (options.animation === true ) {options.animation = {}; }
  2106. if (options.animation.duration === undefined) {options.animation.duration = 1000; } // default duration
  2107. if (options.animation.easingFunction === undefined) {options.animation.easingFunction = "easeInOutQuad"; } // default easing function
  2108. this.animateView(options);
  2109. };
  2110. /**
  2111. *
  2112. * @param {Object} options | options.offset = {x:Number, y:Number} // offset from the center in DOM pixels
  2113. * | options.time = Number // animation time in milliseconds
  2114. * | options.scale = Number // scale to animate to
  2115. * | options.position = {x:Number, y:Number} // position to animate to
  2116. * | options.easingFunction = String // linear, easeInQuad, easeOutQuad, easeInOutQuad,
  2117. * // easeInCubic, easeOutCubic, easeInOutCubic,
  2118. * // easeInQuart, easeOutQuart, easeInOutQuart,
  2119. * // easeInQuint, easeOutQuint, easeInOutQuint
  2120. */
  2121. Network.prototype.animateView = function (options) {
  2122. if (options === undefined) {
  2123. options = {};
  2124. return;
  2125. }
  2126. // release if something focussed on the node
  2127. this.releaseNode();
  2128. if (options.locked == true) {
  2129. this.lockedOnNodeId = options.lockedOnNode;
  2130. this.lockedOnNodeOffset = options.offset;
  2131. }
  2132. // forcefully complete the old animation if it was still running
  2133. if (this.easingTime != 0) {
  2134. this._transitionRedraw(1); // by setting easingtime to 1, we finish the animation.
  2135. }
  2136. this.sourceScale = this._getScale();
  2137. this.sourceTranslation = this._getTranslation();
  2138. this.targetScale = options.scale;
  2139. // set the scale so the viewCenter is based on the correct zoom level. This is overridden in the transitionRedraw
  2140. // but at least then we'll have the target transition
  2141. this._setScale(this.targetScale);
  2142. var viewCenter = this.DOMtoCanvas({x: 0.5 * this.frame.canvas.clientWidth, y: 0.5 * this.frame.canvas.clientHeight});
  2143. var distanceFromCenter = { // offset from view, distance view has to change by these x and y to center the node
  2144. x: viewCenter.x - options.position.x,
  2145. y: viewCenter.y - options.position.y
  2146. };
  2147. this.targetTranslation = {
  2148. x: this.sourceTranslation.x + distanceFromCenter.x * this.targetScale + options.offset.x,
  2149. y: this.sourceTranslation.y + distanceFromCenter.y * this.targetScale + options.offset.y
  2150. };
  2151. // if the time is set to 0, don't do an animation
  2152. if (options.animation.duration == 0) {
  2153. if (this.lockedOnNodeId != null) {
  2154. this._classicRedraw = this._redraw;
  2155. this._redraw = this._lockedRedraw;
  2156. }
  2157. else {
  2158. this._setScale(this.targetScale);
  2159. this._setTranslation(this.targetTranslation.x, this.targetTranslation.y);
  2160. this._redraw();
  2161. }
  2162. }
  2163. else {
  2164. this.animationSpeed = 1 / (this.renderRefreshRate * options.animation.duration * 0.001) || 1 / this.renderRefreshRate;
  2165. this.animationEasingFunction = options.animation.easingFunction;
  2166. this._classicRedraw = this._redraw;
  2167. this._redraw = this._transitionRedraw;
  2168. this._redraw();
  2169. this.moving = true;
  2170. this.start();
  2171. }
  2172. };
  2173. Network.prototype._lockedRedraw = function () {
  2174. var nodePosition = {x: this.nodes[this.lockedOnNodeId].x, y: this.nodes[this.lockedOnNodeId].y};
  2175. var viewCenter = this.DOMtoCanvas({x: 0.5 * this.frame.canvas.clientWidth, y: 0.5 * this.frame.canvas.clientHeight});
  2176. var distanceFromCenter = { // offset from view, distance view has to change by these x and y to center the node
  2177. x: viewCenter.x - nodePosition.x,
  2178. y: viewCenter.y - nodePosition.y
  2179. };
  2180. var sourceTranslation = this._getTranslation();
  2181. var targetTranslation = {
  2182. x: sourceTranslation.x + distanceFromCenter.x * this.scale + this.lockedOnNodeOffset.x,
  2183. y: sourceTranslation.y + distanceFromCenter.y * this.scale + this.lockedOnNodeOffset.y
  2184. };
  2185. this._setTranslation(targetTranslation.x,targetTranslation.y);
  2186. this._classicRedraw();
  2187. }
  2188. Network.prototype.releaseNode = function () {
  2189. if (this.lockedOnNodeId != null) {
  2190. this._redraw = this._classicRedraw;
  2191. this.lockedOnNodeId = null;
  2192. this.lockedOnNodeOffset = null;
  2193. }
  2194. }
  2195. /**
  2196. *
  2197. * @param easingTime
  2198. * @private
  2199. */
  2200. Network.prototype._transitionRedraw = function (easingTime) {
  2201. this.easingTime = easingTime || this.easingTime + this.animationSpeed;
  2202. this.easingTime += this.animationSpeed;
  2203. var progress = util.easingFunctions[this.animationEasingFunction](this.easingTime);
  2204. this._setScale(this.sourceScale + (this.targetScale - this.sourceScale) * progress);
  2205. this._setTranslation(
  2206. this.sourceTranslation.x + (this.targetTranslation.x - this.sourceTranslation.x) * progress,
  2207. this.sourceTranslation.y + (this.targetTranslation.y - this.sourceTranslation.y) * progress
  2208. );
  2209. this._classicRedraw();
  2210. this.moving = true;
  2211. // cleanup
  2212. if (this.easingTime >= 1.0) {
  2213. this.easingTime = 0;
  2214. if (this.lockedOnNodeId != null) {
  2215. this._redraw = this._lockedRedraw;
  2216. }
  2217. else {
  2218. this._redraw = this._classicRedraw;
  2219. }
  2220. this.emit("animationFinished");
  2221. }
  2222. };
  2223. Network.prototype._classicRedraw = function () {
  2224. // placeholder function to be overloaded by animations;
  2225. };
  2226. /**
  2227. * Returns true when the Network is active.
  2228. * @returns {boolean}
  2229. */
  2230. Network.prototype.isActive = function () {
  2231. return !this.activator || this.activator.active;
  2232. };
  2233. /**
  2234. * Sets the scale
  2235. * @returns {Number}
  2236. */
  2237. Network.prototype.setScale = function () {
  2238. return this._setScale();
  2239. };
  2240. /**
  2241. * Returns the scale
  2242. * @returns {Number}
  2243. */
  2244. Network.prototype.getScale = function () {
  2245. return this._getScale();
  2246. };
  2247. /**
  2248. * Returns the scale
  2249. * @returns {Number}
  2250. */
  2251. Network.prototype.getCenterCoordinates = function () {
  2252. return this.DOMtoCanvas({x: 0.5 * this.frame.canvas.clientWidth, y: 0.5 * this.frame.canvas.clientHeight});
  2253. };
  2254. module.exports = Network;