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.

2611 lines
78 KiB

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