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.

2018 lines
57 KiB

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