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.

2709 lines
81 KiB

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