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.

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