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.

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