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.

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