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.

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