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.

2475 lines
74 KiB

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