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.

2425 lines
72 KiB

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