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.

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