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.

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