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.

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