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.

2621 lines
78 KiB

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