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.

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