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.

2690 lines
80 KiB

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