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.

2646 lines
79 KiB

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