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.

1928 lines
53 KiB

11 years ago
10 years ago
10 years ago
11 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
  1. var Emitter = require('emitter-component');
  2. var Hammer = require('../module/hammer');
  3. var keycharm = require('keycharm');
  4. var util = require('../util');
  5. var hammerUtil = require('../hammerUtil');
  6. var DataSet = require('../DataSet');
  7. var DataView = require('../DataView');
  8. var dotparser = require('./dotparser');
  9. var gephiParser = require('./gephiParser');
  10. var Groups = require('./Groups');
  11. var Images = require('./Images');
  12. var Node = require('./Node');
  13. var Edge = require('./Edge');
  14. var Popup = require('./Popup');
  15. var MixinLoader = require('./mixins/MixinLoader');
  16. var Activator = require('../shared/Activator');
  17. var locales = require('./locales');
  18. // Load custom shapes into CanvasRenderingContext2D
  19. require('./shapes');
  20. import { PhysicsEngine } from './modules/PhysicsEngine'
  21. import { ClusterEngine } from './modules/Clustering'
  22. import { CanvasRenderer } from './modules/CanvasRenderer'
  23. import { Canvas } from './modules/Canvas'
  24. import { View } from './modules/View'
  25. /**
  26. * @constructor Network
  27. * Create a network visualization, displaying nodes and edges.
  28. *
  29. * @param {Element} container The DOM element in which the Network will
  30. * be created. Normally a div element.
  31. * @param {Object} data An object containing parameters
  32. * {Array} nodes
  33. * {Array} edges
  34. * @param {Object} options Options
  35. */
  36. function Network (container, data, options) {
  37. if (!(this instanceof Network)) {
  38. throw new SyntaxError('Constructor must be called with the new operator');
  39. }
  40. this._initializeMixinLoaders();
  41. // render and calculation settings
  42. this.initializing = true;
  43. this.triggerFunctions = {add:null,edit:null,editEdge:null,connect:null,del:null};
  44. var customScalingFunction = function (min,max,total,value) {
  45. if (max == min) {
  46. return 0.5;
  47. }
  48. else {
  49. var scale = 1 / (max - min);
  50. return Math.max(0,(value - min)*scale);
  51. }
  52. };
  53. // set constant values
  54. this.defaultOptions = {
  55. nodes: {
  56. customScalingFunction: customScalingFunction,
  57. mass: 1,
  58. radiusMin: 10,
  59. radiusMax: 30,
  60. radius: 10,
  61. shape: 'ellipse',
  62. image: undefined,
  63. widthMin: 16, // px
  64. widthMax: 64, // px
  65. fontColor: 'black',
  66. fontSize: 14, // px
  67. fontFace: 'verdana',
  68. fontFill: undefined,
  69. fontStrokeWidth: 0, // px
  70. fontStrokeColor: '#ffffff',
  71. fontDrawThreshold: 3,
  72. scaleFontWithValue: false,
  73. fontSizeMin: 14,
  74. fontSizeMax: 30,
  75. fontSizeMaxVisible: 30,
  76. value: 1,
  77. level: -1,
  78. color: {
  79. border: '#2B7CE9',
  80. background: '#97C2FC',
  81. highlight: {
  82. border: '#2B7CE9',
  83. background: '#D2E5FF'
  84. },
  85. hover: {
  86. border: '#2B7CE9',
  87. background: '#D2E5FF'
  88. }
  89. },
  90. group: undefined,
  91. borderWidth: 1,
  92. borderWidthSelected: undefined
  93. },
  94. edges: {
  95. customScalingFunction: customScalingFunction,
  96. widthMin: 1, //
  97. widthMax: 15,//
  98. width: 1,
  99. widthSelectionMultiplier: 2,
  100. hoverWidth: 1.5,
  101. value:1,
  102. style: 'line',
  103. color: {
  104. color:'#848484',
  105. highlight:'#848484',
  106. hover: '#848484'
  107. },
  108. opacity:1.0,
  109. fontColor: '#343434',
  110. fontSize: 14, // px
  111. fontFace: 'arial',
  112. fontFill: 'white',
  113. fontStrokeWidth: 0, // px
  114. fontStrokeColor: 'white',
  115. labelAlignment:'horizontal',
  116. arrowScaleFactor: 1,
  117. dash: {
  118. length: 10,
  119. gap: 5,
  120. altLength: undefined
  121. },
  122. inheritColor: "from", // to, from, false, true (== from)
  123. useGradients: false // release in 4.0
  124. },
  125. configurePhysics:false,
  126. navigation: {
  127. enabled: false
  128. },
  129. keyboard: {
  130. enabled: false,
  131. speed: {x: 10, y: 10, zoom: 0.02},
  132. bindToWindow: true
  133. },
  134. dataManipulation: {
  135. enabled: false,
  136. initiallyVisible: false
  137. },
  138. hierarchicalLayout: {
  139. enabled:false,
  140. levelSeparation: 150,
  141. nodeSpacing: 100,
  142. direction: "UD", // UD, DU, LR, RL
  143. layout: "hubsize" // hubsize, directed
  144. },
  145. smoothCurves: {
  146. enabled: true,
  147. dynamic: true,
  148. type: "continuous",
  149. roundness: 0.5
  150. },
  151. locale: 'en',
  152. locales: locales,
  153. tooltip: {
  154. delay: 300,
  155. fontColor: 'black',
  156. fontSize: 14, // px
  157. fontFace: 'verdana',
  158. color: {
  159. border: '#666',
  160. background: '#FFFFC6'
  161. }
  162. },
  163. dragNetwork: true,
  164. dragNodes: true,
  165. zoomable: true,
  166. hover: false,
  167. hideEdgesOnDrag: false,
  168. hideNodesOnDrag: false,
  169. width : '100%',
  170. height : '100%',
  171. selectable: true,
  172. useDefaultGroups: true
  173. };
  174. this.constants = util.extend({}, this.defaultOptions);
  175. // containers for nodes and edges
  176. this.body = {
  177. nodes: {},
  178. nodeIndices: [],
  179. supportNodes: {},
  180. supportNodeIndices: [],
  181. edges: {},
  182. data: {
  183. nodes: null, // A DataSet or DataView
  184. edges: null // A DataSet or DataView
  185. },
  186. functions:{
  187. createNode: this._createNode.bind(this),
  188. createEdge: this._createEdge.bind(this)
  189. },
  190. emitter: {
  191. on: this.on.bind(this),
  192. off: this.off.bind(this),
  193. emit: this.emit.bind(this),
  194. once: this.once.bind(this)
  195. },
  196. eventListeners: {
  197. onTap: function() {},
  198. onTouch: function() {},
  199. onDoubleTap: function() {},
  200. onHold: function() {},
  201. onDragStart: function() {},
  202. onDrag: function() {},
  203. onDragEnd: function() {},
  204. onMouseWheel: function() {},
  205. onPinch: function() {},
  206. onMouseMove: function() {},
  207. onRelease: function() {}
  208. },
  209. container: container
  210. };
  211. // modules
  212. this.view = new View(this.body);
  213. this.renderer = new CanvasRenderer(this.body);
  214. this.clustering = new ClusterEngine(this.body);
  215. this.physics = new PhysicsEngine(this.body);
  216. this.canvas = new Canvas(this.body);
  217. this.renderer.setCanvas(this.canvas);
  218. this.view.setCanvas(this.canvas);
  219. this.hoverObj = {nodes:{},edges:{}};
  220. this.controlNodesActive = false;
  221. this.navigationHammers = [];
  222. this.manipulationHammers = [];
  223. // Node variables
  224. var me = this;
  225. this.groups = new Groups(); // object with groups
  226. this.images = new Images(); // object with images
  227. this.images.setOnloadCallback(function (status) {
  228. me._requestRedraw();
  229. });
  230. // keyboard navigation variables
  231. this.xIncrement = 0;
  232. this.yIncrement = 0;
  233. this.zoomIncrement = 0;
  234. // loading all the mixins:
  235. // load the force calculation functions, grouped under the physics system.
  236. //this._loadPhysicsSystem();
  237. // create a frame and canvas
  238. // load the cluster system. (mandatory, even when not using the cluster system, there are function calls to it)
  239. // load the selection system. (mandatory, required by Network)
  240. this._loadSelectionSystem();
  241. // load the selection system. (mandatory, required by Network)
  242. //this._loadHierarchySystem();
  243. // apply options
  244. this.setOptions(options);
  245. // other vars
  246. this.cachedFunctions = {};
  247. this.startedStabilization = false;
  248. this.stabilized = false;
  249. this.stabilizationIterations = null;
  250. this.draggingNodes = false;
  251. // position and scale variables and objects
  252. this.pointerPosition = {"x": 0,"y": 0}; // coordinates of the bottom right of the canvas. they will be set during _redraw
  253. this.scale = 1; // defining the global scale variable in the constructor
  254. // create event listeners used to subscribe on the DataSets of the nodes and edges
  255. this.nodesListeners = {
  256. 'add': function (event, params) {
  257. me._addNodes(params.items);
  258. me.start();
  259. },
  260. 'update': function (event, params) {
  261. me._updateNodes(params.items, params.data);
  262. me.start();
  263. },
  264. 'remove': function (event, params) {
  265. me._removeNodes(params.items);
  266. me.start();
  267. }
  268. };
  269. this.edgesListeners = {
  270. 'add': function (event, params) {
  271. me._addEdges(params.items);
  272. me.start();
  273. },
  274. 'update': function (event, params) {
  275. me._updateEdges(params.items);
  276. me.start();
  277. },
  278. 'remove': function (event, params) {
  279. me._removeEdges(params.items);
  280. me.start();
  281. }
  282. };
  283. // properties for the animation
  284. this.moving = true;
  285. this.renderTimer = undefined; // Scheduling function. Is definded in this.start();
  286. // load data (the disable start variable will be the same as the enabled clustering)
  287. this.setData(data, this.constants.hierarchicalLayout.enabled);
  288. // hierarchical layout
  289. if (this.constants.hierarchicalLayout.enabled == true) {
  290. this._setupHierarchicalLayout();
  291. }
  292. else {
  293. // zoom so all data will fit on the screen, if clustering is enabled, we do not want start to be called here.
  294. if (this.constants.stabilize == false) {
  295. this.zoomExtent({duration:0}, true, this.constants.clustering.enabled);
  296. }
  297. }
  298. if (this.constants.stabilize == false) {
  299. this.initializing = false;
  300. }
  301. var me = this;
  302. // this event will trigger a rebuilding of the cache of colors, nodes etc.
  303. this.on("_dataChanged", function () {
  304. me._updateNodeIndexList();
  305. me.physics._updateCalculationNodes();
  306. me._markAllEdgesAsDirty();
  307. if (me.initializing !== true) {
  308. me.moving = true;
  309. me.start();
  310. }
  311. })
  312. this.on("_newEdgesCreated", this._createBezierNodes.bind(this));
  313. //this.on("stabilizationIterationsDone", function () {me.initializing = false; me.start();}.bind(this));
  314. }
  315. // Extend Network with an Emitter mixin
  316. Emitter(Network.prototype);
  317. Network.prototype._createNode = function(properties) {
  318. return new Node(properties, this.images, this.groups, this.constants)
  319. }
  320. Network.prototype._createEdge = function(properties) {
  321. return new Edge(properties, this.body, this.constants)
  322. }
  323. /**
  324. * Update the this.body.nodeIndices with the most recent node index list
  325. * @private
  326. */
  327. Network.prototype._updateNodeIndexList = function() {
  328. this.body.supportNodeIndices = Object.keys(this.body.supportNodes)
  329. this.body.nodeIndices = Object.keys(this.body.nodes);
  330. };
  331. /**
  332. * Set nodes and edges, and optionally options as well.
  333. *
  334. * @param {Object} data Object containing parameters:
  335. * {Array | DataSet | DataView} [nodes] Array with nodes
  336. * {Array | DataSet | DataView} [edges] Array with edges
  337. * {String} [dot] String containing data in DOT format
  338. * {String} [gephi] String containing data in gephi JSON format
  339. * {Options} [options] Object with options
  340. * @param {Boolean} [disableStart] | optional: disable the calling of the start function.
  341. */
  342. Network.prototype.setData = function(data, disableStart) {
  343. if (disableStart === undefined) {
  344. disableStart = false;
  345. }
  346. // unselect all to ensure no selections from old data are carried over.
  347. this._unselectAll(true);
  348. // we set initializing to true to ensure that the hierarchical layout is not performed until both nodes and edges are added.
  349. this.initializing = true;
  350. if (data && data.dot && (data.nodes || data.edges)) {
  351. throw new SyntaxError('Data must contain either parameter "dot" or ' +
  352. ' parameter pair "nodes" and "edges", but not both.');
  353. }
  354. // clean up in case there is anyone in an active mode of the manipulation. This is the same option as bound to the escape button.
  355. if (this.constants.dataManipulation.enabled == true) {
  356. this._createManipulatorBar();
  357. }
  358. // set options
  359. this.setOptions(data && data.options);
  360. // set all data
  361. if (data && data.dot) {
  362. // parse DOT file
  363. if(data && data.dot) {
  364. var dotData = dotparser.DOTToGraph(data.dot);
  365. this.setData(dotData);
  366. return;
  367. }
  368. }
  369. else if (data && data.gephi) {
  370. // parse DOT file
  371. if(data && data.gephi) {
  372. var gephiData = gephiParser.parseGephi(data.gephi);
  373. this.setData(gephiData);
  374. return;
  375. }
  376. }
  377. else {
  378. this._setNodes(data && data.nodes);
  379. this._setEdges(data && data.edges);
  380. }
  381. if (disableStart == false) {
  382. if (this.constants.hierarchicalLayout.enabled == true) {
  383. this._resetLevels();
  384. this._setupHierarchicalLayout();
  385. }
  386. else {
  387. // find a stable position or start animating to a stable position
  388. this.physics.startSimulation()
  389. }
  390. }
  391. else {
  392. this.initializing = false;
  393. }
  394. };
  395. /**
  396. * Set options
  397. * @param {Object} options
  398. */
  399. Network.prototype.setOptions = function (options) {
  400. if (options) {
  401. var prop;
  402. var fields = ['nodes','edges','smoothCurves','hierarchicalLayout','navigation',
  403. 'keyboard','dataManipulation','onAdd','onEdit','onEditEdge','onConnect','onDelete','clickToUse'
  404. ];
  405. // extend all but the values in fields
  406. util.selectiveNotDeepExtend(fields,this.constants, options);
  407. util.selectiveNotDeepExtend(['color'],this.constants.nodes, options.nodes);
  408. util.selectiveNotDeepExtend(['color','length'],this.constants.edges, options.edges);
  409. this.groups.useDefaultGroups = this.constants.useDefaultGroups;
  410. this.physics.setOptions(options.physics);
  411. this.canvas.setOptions(this.constants);
  412. if (options.onAdd) {this.triggerFunctions.add = options.onAdd;}
  413. if (options.onEdit) {this.triggerFunctions.edit = options.onEdit;}
  414. if (options.onEditEdge) {this.triggerFunctions.editEdge = options.onEditEdge;}
  415. if (options.onConnect) {this.triggerFunctions.connect = options.onConnect;}
  416. if (options.onDelete) {this.triggerFunctions.del = options.onDelete;}
  417. util.mergeOptions(this.constants, options,'smoothCurves');
  418. util.mergeOptions(this.constants, options,'hierarchicalLayout');
  419. util.mergeOptions(this.constants, options,'clustering');
  420. util.mergeOptions(this.constants, options,'navigation');
  421. util.mergeOptions(this.constants, options,'keyboard');
  422. util.mergeOptions(this.constants, options,'dataManipulation');
  423. if (options.dataManipulation) {
  424. this.editMode = this.constants.dataManipulation.initiallyVisible;
  425. }
  426. // TODO: work out these options and document them
  427. if (options.edges) {
  428. if (options.edges.color !== undefined) {
  429. if (util.isString(options.edges.color)) {
  430. this.constants.edges.color = {};
  431. this.constants.edges.color.color = options.edges.color;
  432. this.constants.edges.color.highlight = options.edges.color;
  433. this.constants.edges.color.hover = options.edges.color;
  434. }
  435. else {
  436. if (options.edges.color.color !== undefined) {this.constants.edges.color.color = options.edges.color.color;}
  437. if (options.edges.color.highlight !== undefined) {this.constants.edges.color.highlight = options.edges.color.highlight;}
  438. if (options.edges.color.hover !== undefined) {this.constants.edges.color.hover = options.edges.color.hover;}
  439. }
  440. this.constants.edges.inheritColor = false;
  441. }
  442. if (!options.edges.fontColor) {
  443. if (options.edges.color !== undefined) {
  444. if (util.isString(options.edges.color)) {this.constants.edges.fontColor = options.edges.color;}
  445. else if (options.edges.color.color !== undefined) {this.constants.edges.fontColor = options.edges.color.color;}
  446. }
  447. }
  448. }
  449. if (options.nodes) {
  450. if (options.nodes.color) {
  451. var newColorObj = util.parseColor(options.nodes.color);
  452. this.constants.nodes.color.background = newColorObj.background;
  453. this.constants.nodes.color.border = newColorObj.border;
  454. this.constants.nodes.color.highlight.background = newColorObj.highlight.background;
  455. this.constants.nodes.color.highlight.border = newColorObj.highlight.border;
  456. this.constants.nodes.color.hover.background = newColorObj.hover.background;
  457. this.constants.nodes.color.hover.border = newColorObj.hover.border;
  458. }
  459. }
  460. if (options.groups) {
  461. for (var groupname in options.groups) {
  462. if (options.groups.hasOwnProperty(groupname)) {
  463. var group = options.groups[groupname];
  464. this.groups.add(groupname, group);
  465. }
  466. }
  467. }
  468. if (options.tooltip) {
  469. for (prop in options.tooltip) {
  470. if (options.tooltip.hasOwnProperty(prop)) {
  471. this.constants.tooltip[prop] = options.tooltip[prop];
  472. }
  473. }
  474. if (options.tooltip.color) {
  475. this.constants.tooltip.color = util.parseColor(options.tooltip.color);
  476. }
  477. }
  478. if ('clickToUse' in options) {
  479. if (options.clickToUse) {
  480. if (!this.activator) {
  481. this.activator = new Activator(this.frame);
  482. this.activator.on('change', this._createKeyBinds.bind(this));
  483. }
  484. }
  485. else {
  486. if (this.activator) {
  487. this.activator.destroy();
  488. delete this.activator;
  489. }
  490. }
  491. }
  492. if (options.labels) {
  493. throw new Error('Option "labels" is deprecated. Use options "locale" and "locales" instead.');
  494. }
  495. // (Re)loading the mixins that can be enabled or disabled in the options.
  496. // load the force calculation functions, grouped under the physics system.
  497. // load the navigation system.
  498. //this._loadNavigationControls();
  499. //// load the data manipulation system
  500. //this._loadManipulationSystem();
  501. //// configure the smooth curves
  502. //this._configureSmoothCurves();
  503. // bind hammer
  504. this.canvas._bindHammer();
  505. // bind keys. If disabled, this will not do anything;
  506. //this._createKeyBinds();
  507. this._markAllEdgesAsDirty();
  508. this.canvas.setSize(this.constants.width, this.constants.height);
  509. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  510. this._resetLevels();
  511. this._setupHierarchicalLayout();
  512. }
  513. if (this.initializing !== true) {
  514. this.moving = true;
  515. this.start();
  516. }
  517. }
  518. };
  519. /**
  520. * Binding the keys for keyboard navigation. These functions are defined in the NavigationMixin
  521. * @private
  522. */
  523. Network.prototype._createKeyBinds = function() {
  524. return;
  525. //var me = this;
  526. //if (this.keycharm !== undefined) {
  527. // this.keycharm.destroy();
  528. //}
  529. //
  530. //if (this.constants.keyboard.bindToWindow == true) {
  531. // this.keycharm = keycharm({container: window, preventDefault: false});
  532. //}
  533. //else {
  534. // this.keycharm = keycharm({container: this.frame, preventDefault: false});
  535. //}
  536. //
  537. //this.keycharm.reset();
  538. //
  539. //if (this.constants.keyboard.enabled && this.isActive()) {
  540. // this.keycharm.bind("up", this._moveUp.bind(me) , "keydown");
  541. // this.keycharm.bind("up", this._yStopMoving.bind(me), "keyup");
  542. // this.keycharm.bind("down", this._moveDown.bind(me) , "keydown");
  543. // this.keycharm.bind("down", this._yStopMoving.bind(me), "keyup");
  544. // this.keycharm.bind("left", this._moveLeft.bind(me) , "keydown");
  545. // this.keycharm.bind("left", this._xStopMoving.bind(me), "keyup");
  546. // this.keycharm.bind("right",this._moveRight.bind(me), "keydown");
  547. // this.keycharm.bind("right",this._xStopMoving.bind(me), "keyup");
  548. // this.keycharm.bind("=", this._zoomIn.bind(me), "keydown");
  549. // this.keycharm.bind("=", this._stopZoom.bind(me), "keyup");
  550. // this.keycharm.bind("num+", this._zoomIn.bind(me), "keydown");
  551. // this.keycharm.bind("num+", this._stopZoom.bind(me), "keyup");
  552. // this.keycharm.bind("num-", this._zoomOut.bind(me), "keydown");
  553. // this.keycharm.bind("num-", this._stopZoom.bind(me), "keyup");
  554. // this.keycharm.bind("-", this._zoomOut.bind(me), "keydown");
  555. // this.keycharm.bind("-", this._stopZoom.bind(me), "keyup");
  556. // this.keycharm.bind("[", this._zoomIn.bind(me), "keydown");
  557. // this.keycharm.bind("[", this._stopZoom.bind(me), "keyup");
  558. // this.keycharm.bind("]", this._zoomOut.bind(me), "keydown");
  559. // this.keycharm.bind("]", this._stopZoom.bind(me), "keyup");
  560. // this.keycharm.bind("pageup",this._zoomIn.bind(me), "keydown");
  561. // this.keycharm.bind("pageup",this._stopZoom.bind(me), "keyup");
  562. // this.keycharm.bind("pagedown",this._zoomOut.bind(me),"keydown");
  563. // this.keycharm.bind("pagedown",this._stopZoom.bind(me), "keyup");
  564. //}
  565. //
  566. //if (this.constants.dataManipulation.enabled == true) {
  567. // this.keycharm.bind("esc",this._createManipulatorBar.bind(me));
  568. // this.keycharm.bind("delete",this._deleteSelected.bind(me));
  569. //}
  570. };
  571. /**
  572. * Cleans up all bindings of the network, removing it fully from the memory IF the variable is set to null after calling this function.
  573. * var network = new vis.Network(..);
  574. * network.destroy();
  575. * network = null;
  576. */
  577. Network.prototype.destroy = function() {
  578. this.start = function () {};
  579. this.redraw = function () {};
  580. this.renderTimer = false;
  581. // cleanup physicsConfiguration if it exists
  582. this._cleanupPhysicsConfiguration();
  583. // remove keybindings
  584. this.keycharm.reset();
  585. // clear hammer bindings
  586. this.hammer.dispose();
  587. // clear events
  588. this.off();
  589. this._recursiveDOMDelete(this.containerElement);
  590. }
  591. Network.prototype._recursiveDOMDelete = function(DOMobject) {
  592. while (DOMobject.hasChildNodes() == true) {
  593. this._recursiveDOMDelete(DOMobject.firstChild);
  594. DOMobject.removeChild(DOMobject.firstChild);
  595. }
  596. }
  597. /**
  598. * Get the pointer location from a touch location
  599. * @param {{pageX: Number, pageY: Number}} touch
  600. * @return {{x: Number, y: Number}} pointer
  601. * @private
  602. */
  603. Network.prototype._getPointer = function (touch) {
  604. return {
  605. x: touch.pageX - util.getAbsoluteLeft(this.frame.canvas),
  606. y: touch.pageY - util.getAbsoluteTop(this.frame.canvas)
  607. };
  608. };
  609. /**
  610. * On start of a touch gesture, store the pointer
  611. * @param event
  612. * @private
  613. */
  614. Network.prototype._onTouch = function (event) {
  615. if (new Date().valueOf() - this.touchTime > 100) {
  616. this.drag.pointer = this._getPointer(event.gesture.center);
  617. this.drag.pinched = false;
  618. this.pinch.scale = this._getScale();
  619. // to avoid double fireing of this event because we have two hammer instances. (on canvas and on frame)
  620. this.touchTime = new Date().valueOf();
  621. this._handleTouch(this.drag.pointer);
  622. }
  623. };
  624. /**
  625. * handle drag start event
  626. * @private
  627. */
  628. Network.prototype._onDragStart = function (event) {
  629. this._handleDragStart(event);
  630. };
  631. /**
  632. * This function is called by _onDragStart.
  633. * It is separated out because we can then overload it for the datamanipulation system.
  634. *
  635. * @private
  636. */
  637. Network.prototype._handleDragStart = function(event) {
  638. // in case the touch event was triggered on an external div, do the initial touch now.
  639. if (this.drag.pointer === undefined) {
  640. this._onTouch(event);
  641. }
  642. var node = this._getNodeAt(this.drag.pointer);
  643. // note: drag.pointer is set in _onTouch to get the initial touch location
  644. this.drag.dragging = true;
  645. this.drag.selection = [];
  646. this.drag.translation = this._getTranslation();
  647. this.drag.nodeId = null;
  648. this.draggingNodes = false;
  649. if (node != null && this.constants.dragNodes == true) {
  650. this.draggingNodes = true;
  651. this.drag.nodeId = node.id;
  652. // select the clicked node if not yet selected
  653. if (!node.isSelected()) {
  654. this._selectObject(node,false);
  655. }
  656. this.emit("dragStart",{nodeIds:this.getSelection().nodes});
  657. // create an array with the selected nodes and their original location and status
  658. for (var objectId in this.selectionObj.nodes) {
  659. if (this.selectionObj.nodes.hasOwnProperty(objectId)) {
  660. var object = this.selectionObj.nodes[objectId];
  661. var s = {
  662. id: object.id,
  663. node: object,
  664. // store original x, y, xFixed and yFixed, make the node temporarily Fixed
  665. x: object.x,
  666. y: object.y,
  667. xFixed: object.xFixed,
  668. yFixed: object.yFixed
  669. };
  670. object.xFixed = true;
  671. object.yFixed = true;
  672. this.drag.selection.push(s);
  673. }
  674. }
  675. }
  676. };
  677. /**
  678. * handle drag event
  679. * @private
  680. */
  681. Network.prototype._onDrag = function (event) {
  682. this._handleOnDrag(event)
  683. };
  684. /**
  685. * This function is called by _onDrag.
  686. * It is separated out because we can then overload it for the datamanipulation system.
  687. *
  688. * @private
  689. */
  690. Network.prototype._handleOnDrag = function(event) {
  691. if (this.drag.pinched) {
  692. return;
  693. }
  694. // remove the focus on node if it is focussed on by the focusOnNode
  695. this.releaseNode();
  696. var pointer = this._getPointer(event.gesture.center);
  697. var me = this;
  698. var drag = this.drag;
  699. var selection = drag.selection;
  700. if (selection && selection.length && this.constants.dragNodes == true) {
  701. // calculate delta's and new location
  702. var deltaX = pointer.x - drag.pointer.x;
  703. var deltaY = pointer.y - drag.pointer.y;
  704. // update position of all selected nodes
  705. selection.forEach(function (s) {
  706. var node = s.node;
  707. if (!s.xFixed) {
  708. node.x = me._XconvertDOMtoCanvas(me._XconvertCanvasToDOM(s.x) + deltaX);
  709. }
  710. if (!s.yFixed) {
  711. node.y = me._YconvertDOMtoCanvas(me._YconvertCanvasToDOM(s.y) + deltaY);
  712. }
  713. });
  714. // start _animationStep if not yet running
  715. if (!this.moving) {
  716. this.moving = true;
  717. this.start();
  718. }
  719. }
  720. else {
  721. // move the network
  722. if (this.constants.dragNetwork == true) {
  723. // if the drag was not started properly because the click started outside the network div, start it now.
  724. if (this.drag.pointer === undefined) {
  725. this._handleDragStart(event);
  726. return;
  727. }
  728. var diffX = pointer.x - this.drag.pointer.x;
  729. var diffY = pointer.y - this.drag.pointer.y;
  730. this._setTranslation(
  731. this.drag.translation.x + diffX,
  732. this.drag.translation.y + diffY
  733. );
  734. this._redraw();
  735. }
  736. }
  737. };
  738. /**
  739. * handle drag start event
  740. * @private
  741. */
  742. Network.prototype._onDragEnd = function (event) {
  743. this._handleDragEnd(event);
  744. };
  745. Network.prototype._handleDragEnd = function(event) {
  746. this.drag.dragging = false;
  747. var selection = this.drag.selection;
  748. if (selection && selection.length) {
  749. selection.forEach(function (s) {
  750. // restore original xFixed and yFixed
  751. s.node.xFixed = s.xFixed;
  752. s.node.yFixed = s.yFixed;
  753. });
  754. this.moving = true;
  755. this.start();
  756. }
  757. else {
  758. this._redraw();
  759. }
  760. if (this.draggingNodes == false) {
  761. this.emit("dragEnd",{nodeIds:[]});
  762. }
  763. else {
  764. this.emit("dragEnd",{nodeIds:this.getSelection().nodes});
  765. }
  766. }
  767. /**
  768. * handle tap/click event: select/unselect a node
  769. * @private
  770. */
  771. Network.prototype._onTap = function (event) {
  772. var pointer = this._getPointer(event.gesture.center);
  773. this.pointerPosition = pointer;
  774. this._handleTap(pointer);
  775. };
  776. /**
  777. * handle doubletap event
  778. * @private
  779. */
  780. Network.prototype._onDoubleTap = function (event) {
  781. var pointer = this._getPointer(event.gesture.center);
  782. this._handleDoubleTap(pointer);
  783. };
  784. /**
  785. * handle long tap event: multi select nodes
  786. * @private
  787. */
  788. Network.prototype._onHold = function (event) {
  789. var pointer = this._getPointer(event.gesture.center);
  790. this.pointerPosition = pointer;
  791. this._handleOnHold(pointer);
  792. };
  793. /**
  794. * handle the release of the screen
  795. *
  796. * @private
  797. */
  798. Network.prototype._onRelease = function (event) {
  799. var pointer = this._getPointer(event.gesture.center);
  800. this._handleOnRelease(pointer);
  801. };
  802. /**
  803. * Handle pinch event
  804. * @param event
  805. * @private
  806. */
  807. Network.prototype._onPinch = function (event) {
  808. var pointer = this._getPointer(event.gesture.center);
  809. this.drag.pinched = true;
  810. if (!('scale' in this.pinch)) {
  811. this.pinch.scale = 1;
  812. }
  813. // TODO: enabled moving while pinching?
  814. var scale = this.pinch.scale * event.gesture.scale;
  815. this._zoom(scale, pointer)
  816. };
  817. /**
  818. * Zoom the network in or out
  819. * @param {Number} scale a number around 1, and between 0.01 and 10
  820. * @param {{x: Number, y: Number}} pointer Position on screen
  821. * @return {Number} appliedScale scale is limited within the boundaries
  822. * @private
  823. */
  824. Network.prototype._zoom = function(scale, pointer) {
  825. if (this.constants.zoomable == true) {
  826. var scaleOld = this._getScale();
  827. if (scale < 0.00001) {
  828. scale = 0.00001;
  829. }
  830. if (scale > 10) {
  831. scale = 10;
  832. }
  833. var preScaleDragPointer = null;
  834. if (this.drag !== undefined) {
  835. if (this.drag.dragging == true) {
  836. preScaleDragPointer = this.DOMtoCanvas(this.drag.pointer);
  837. }
  838. }
  839. // + this.frame.canvas.clientHeight / 2
  840. var translation = this._getTranslation();
  841. var scaleFrac = scale / scaleOld;
  842. var tx = (1 - scaleFrac) * pointer.x + translation.x * scaleFrac;
  843. var ty = (1 - scaleFrac) * pointer.y + translation.y * scaleFrac;
  844. this.areaCenter = {"x" : this._XconvertDOMtoCanvas(pointer.x),
  845. "y" : this._YconvertDOMtoCanvas(pointer.y)};
  846. this._setScale(scale);
  847. this._setTranslation(tx, ty);
  848. if (preScaleDragPointer != null) {
  849. var postScaleDragPointer = this.canvasToDOM(preScaleDragPointer);
  850. this.drag.pointer.x = postScaleDragPointer.x;
  851. this.drag.pointer.y = postScaleDragPointer.y;
  852. }
  853. this._redraw();
  854. if (scaleOld < scale) {
  855. this.emit("zoom", {direction:"+"});
  856. }
  857. else {
  858. this.emit("zoom", {direction:"-"});
  859. }
  860. return scale;
  861. }
  862. };
  863. /**
  864. * Event handler for mouse wheel event, used to zoom the timeline
  865. * See http://adomas.org/javascript-mouse-wheel/
  866. * https://github.com/EightMedia/hammer.js/issues/256
  867. * @param {MouseEvent} event
  868. * @private
  869. */
  870. Network.prototype._onMouseWheel = function(event) {
  871. // retrieve delta
  872. var delta = 0;
  873. if (event.wheelDelta) { /* IE/Opera. */
  874. delta = event.wheelDelta/120;
  875. } else if (event.detail) { /* Mozilla case. */
  876. // In Mozilla, sign of delta is different than in IE.
  877. // Also, delta is multiple of 3.
  878. delta = -event.detail/3;
  879. }
  880. // If delta is nonzero, handle it.
  881. // Basically, delta is now positive if wheel was scrolled up,
  882. // and negative, if wheel was scrolled down.
  883. if (delta) {
  884. // calculate the new scale
  885. var scale = this._getScale();
  886. var zoom = delta / 10;
  887. if (delta < 0) {
  888. zoom = zoom / (1 - zoom);
  889. }
  890. scale *= (1 + zoom);
  891. // calculate the pointer location
  892. var gesture = hammerUtil.fakeGesture(this, event);
  893. var pointer = this._getPointer(gesture.center);
  894. // apply the new scale
  895. this._zoom(scale, pointer);
  896. }
  897. // Prevent default actions caused by mouse wheel.
  898. event.preventDefault();
  899. };
  900. /**
  901. * Mouse move handler for checking whether the title moves over a node with a title.
  902. * @param {Event} event
  903. * @private
  904. */
  905. Network.prototype._onMouseMoveTitle = function (event) {
  906. var gesture = hammerUtil.fakeGesture(this, event);
  907. var pointer = this._getPointer(gesture.center);
  908. var popupVisible = false;
  909. // check if the previously selected node is still selected
  910. if (this.popup !== undefined) {
  911. if (this.popup.hidden === false) {
  912. this._checkHidePopup(pointer);
  913. }
  914. // if the popup was not hidden above
  915. if (this.popup.hidden === false) {
  916. popupVisible = true;
  917. this.popup.setPosition(pointer.x + 3,pointer.y - 5)
  918. this.popup.show();
  919. }
  920. }
  921. // if we bind the keyboard to the div, we have to highlight it to use it. This highlights it on mouse over
  922. if (this.constants.keyboard.bindToWindow == false && this.constants.keyboard.enabled == true) {
  923. this.frame.focus();
  924. }
  925. // start a timeout that will check if the mouse is positioned above an element
  926. if (popupVisible === false) {
  927. var me = this;
  928. var checkShow = function () {
  929. me._checkShowPopup(pointer);
  930. };
  931. if (this.popupTimer) {
  932. clearInterval(this.popupTimer); // stop any running calculationTimer
  933. }
  934. if (!this.drag.dragging) {
  935. this.popupTimer = setTimeout(checkShow, this.constants.tooltip.delay);
  936. }
  937. }
  938. /**
  939. * Adding hover highlights
  940. */
  941. if (this.constants.hover == true) {
  942. // removing all hover highlights
  943. for (var edgeId in this.hoverObj.edges) {
  944. if (this.hoverObj.edges.hasOwnProperty(edgeId)) {
  945. this.hoverObj.edges[edgeId].hover = false;
  946. delete this.hoverObj.edges[edgeId];
  947. }
  948. }
  949. // adding hover highlights
  950. var obj = this._getNodeAt(pointer);
  951. if (obj == null) {
  952. obj = this._getEdgeAt(pointer);
  953. }
  954. if (obj != null) {
  955. this._hoverObject(obj);
  956. }
  957. // removing all node hover highlights except for the selected one.
  958. for (var nodeId in this.hoverObj.nodes) {
  959. if (this.hoverObj.nodes.hasOwnProperty(nodeId)) {
  960. if (obj instanceof Node && obj.id != nodeId || obj instanceof Edge || obj == null) {
  961. this._blurObject(this.hoverObj.nodes[nodeId]);
  962. delete this.hoverObj.nodes[nodeId];
  963. }
  964. }
  965. }
  966. this.redraw();
  967. }
  968. };
  969. /**
  970. * Check if there is an element on the given position in the network
  971. * (a node or edge). If so, and if this element has a title,
  972. * show a popup window with its title.
  973. *
  974. * @param {{x:Number, y:Number}} pointer
  975. * @private
  976. */
  977. Network.prototype._checkShowPopup = function (pointer) {
  978. var obj = {
  979. left: this._XconvertDOMtoCanvas(pointer.x),
  980. top: this._YconvertDOMtoCanvas(pointer.y),
  981. right: this._XconvertDOMtoCanvas(pointer.x),
  982. bottom: this._YconvertDOMtoCanvas(pointer.y)
  983. };
  984. var id;
  985. var previousPopupObjId = this.popupObj === undefined ? "" : this.popupObj.id;
  986. var nodeUnderCursor = false;
  987. var popupType = "node";
  988. if (this.popupObj == undefined) {
  989. // search the nodes for overlap, select the top one in case of multiple nodes
  990. var nodes = this.body.nodes;
  991. var overlappingNodes = [];
  992. for (id in nodes) {
  993. if (nodes.hasOwnProperty(id)) {
  994. var node = nodes[id];
  995. if (node.isOverlappingWith(obj)) {
  996. if (node.getTitle() !== undefined) {
  997. overlappingNodes.push(id);
  998. }
  999. }
  1000. }
  1001. }
  1002. if (overlappingNodes.length > 0) {
  1003. // if there are overlapping nodes, select the last one, this is the
  1004. // one which is drawn on top of the others
  1005. this.popupObj = this.body.nodes[overlappingNodes[overlappingNodes.length - 1]];
  1006. // if you hover over a node, the title of the edge is not supposed to be shown.
  1007. nodeUnderCursor = true;
  1008. }
  1009. }
  1010. if (this.popupObj === undefined && nodeUnderCursor == false) {
  1011. // search the edges for overlap
  1012. var edges = this.body.edges;
  1013. var overlappingEdges = [];
  1014. for (id in edges) {
  1015. if (edges.hasOwnProperty(id)) {
  1016. var edge = edges[id];
  1017. if (edge.connected === true && (edge.getTitle() !== undefined) &&
  1018. edge.isOverlappingWith(obj)) {
  1019. overlappingEdges.push(id);
  1020. }
  1021. }
  1022. }
  1023. if (overlappingEdges.length > 0) {
  1024. this.popupObj = this.body.edges[overlappingEdges[overlappingEdges.length - 1]];
  1025. popupType = "edge";
  1026. }
  1027. }
  1028. if (this.popupObj) {
  1029. // show popup message window
  1030. if (this.popupObj.id != previousPopupObjId) {
  1031. if (this.popup === undefined) {
  1032. this.popup = new Popup(this.frame, this.constants.tooltip);
  1033. }
  1034. this.popup.popupTargetType = popupType;
  1035. this.popup.popupTargetId = this.popupObj.id;
  1036. // adjust a small offset such that the mouse cursor is located in the
  1037. // bottom left location of the popup, and you can easily move over the
  1038. // popup area
  1039. this.popup.setPosition(pointer.x + 3, pointer.y - 5);
  1040. this.popup.setText(this.popupObj.getTitle());
  1041. this.popup.show();
  1042. }
  1043. }
  1044. else {
  1045. if (this.popup) {
  1046. this.popup.hide();
  1047. }
  1048. }
  1049. };
  1050. /**
  1051. * Check if the popup must be hidden, which is the case when the mouse is no
  1052. * longer hovering on the object
  1053. * @param {{x:Number, y:Number}} pointer
  1054. * @private
  1055. */
  1056. Network.prototype._checkHidePopup = function (pointer) {
  1057. var pointerObj = {
  1058. left: this._XconvertDOMtoCanvas(pointer.x),
  1059. top: this._YconvertDOMtoCanvas(pointer.y),
  1060. right: this._XconvertDOMtoCanvas(pointer.x),
  1061. bottom: this._YconvertDOMtoCanvas(pointer.y)
  1062. };
  1063. var stillOnObj = false;
  1064. if (this.popup.popupTargetType == 'node') {
  1065. stillOnObj = this.body.nodes[this.popup.popupTargetId].isOverlappingWith(pointerObj);
  1066. if (stillOnObj === true) {
  1067. var overNode = this._getNodeAt(pointer);
  1068. stillOnObj = overNode.id == this.popup.popupTargetId;
  1069. }
  1070. }
  1071. else {
  1072. if (this._getNodeAt(pointer) === null) {
  1073. stillOnObj = this.body.edges[this.popup.popupTargetId].isOverlappingWith(pointerObj);
  1074. }
  1075. }
  1076. if (stillOnObj === false) {
  1077. this.popupObj = undefined;
  1078. this.popup.hide();
  1079. }
  1080. };
  1081. /**
  1082. * Set a data set with nodes for the network
  1083. * @param {Array | DataSet | DataView} nodes The data containing the nodes.
  1084. * @private
  1085. */
  1086. Network.prototype._setNodes = function(nodes) {
  1087. var oldNodesData = this.body.data.nodes;
  1088. if (nodes instanceof DataSet || nodes instanceof DataView) {
  1089. this.body.data.nodes = nodes;
  1090. }
  1091. else if (Array.isArray(nodes)) {
  1092. this.body.data.nodes = new DataSet();
  1093. this.body.data.nodes.add(nodes);
  1094. }
  1095. else if (!nodes) {
  1096. this.body.data.nodes = new DataSet();
  1097. }
  1098. else {
  1099. throw new TypeError('Array or DataSet expected');
  1100. }
  1101. if (oldNodesData) {
  1102. // unsubscribe from old dataset
  1103. util.forEach(this.nodesListeners, function (callback, event) {
  1104. oldNodesData.off(event, callback);
  1105. });
  1106. }
  1107. // remove drawn nodes
  1108. this.body.nodes = {};
  1109. if (this.body.data.nodes) {
  1110. // subscribe to new dataset
  1111. var me = this;
  1112. util.forEach(this.nodesListeners, function (callback, event) {
  1113. me.body.data.nodes.on(event, callback);
  1114. });
  1115. // draw all new nodes
  1116. var ids = this.body.data.nodes.getIds();
  1117. this._addNodes(ids);
  1118. }
  1119. this._updateSelection();
  1120. };
  1121. /**
  1122. * Add nodes
  1123. * @param {Number[] | String[]} ids
  1124. * @private
  1125. */
  1126. Network.prototype._addNodes = function(ids) {
  1127. var id;
  1128. for (var i = 0, len = ids.length; i < len; i++) {
  1129. id = ids[i];
  1130. var data = this.body.data.nodes.get(id);
  1131. var node = new Node(data, this.images, this.groups, this.constants);
  1132. this.body.nodes[id] = node; // note: this may replace an existing node
  1133. if ((node.xFixed == false || node.yFixed == false) && (node.x === null || node.y === null)) {
  1134. var radius = 10 * 0.1*ids.length + 10;
  1135. var angle = 2 * Math.PI * Math.random();
  1136. if (node.xFixed == false) {node.x = radius * Math.cos(angle);}
  1137. if (node.yFixed == false) {node.y = radius * Math.sin(angle);}
  1138. }
  1139. this.moving = true;
  1140. }
  1141. this._updateNodeIndexList();
  1142. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  1143. this._resetLevels();
  1144. this._setupHierarchicalLayout();
  1145. }
  1146. this.physics._updateCalculationNodes();
  1147. this._reconnectEdges();
  1148. this._updateValueRange(this.body.nodes);
  1149. };
  1150. /**
  1151. * Update existing nodes, or create them when not yet existing
  1152. * @param {Number[] | String[]} ids
  1153. * @private
  1154. */
  1155. Network.prototype._updateNodes = function(ids,changedData) {
  1156. var nodes = this.body.nodes;
  1157. for (var i = 0, len = ids.length; i < len; i++) {
  1158. var id = ids[i];
  1159. var node = nodes[id];
  1160. var data = changedData[i];
  1161. if (node) {
  1162. // update node
  1163. node.setProperties(data, this.constants);
  1164. }
  1165. else {
  1166. // create node
  1167. node = new Node(properties, this.images, this.groups, this.constants);
  1168. nodes[id] = node;
  1169. }
  1170. }
  1171. this.moving = true;
  1172. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  1173. this._resetLevels();
  1174. this._setupHierarchicalLayout();
  1175. }
  1176. this._updateNodeIndexList();
  1177. this._updateValueRange(nodes);
  1178. this._markAllEdgesAsDirty();
  1179. };
  1180. Network.prototype._markAllEdgesAsDirty = function() {
  1181. for (var edgeId in this.body.edges) {
  1182. this.body.edges[edgeId].colorDirty = true;
  1183. }
  1184. }
  1185. /**
  1186. * Remove existing nodes. If nodes do not exist, the method will just ignore it.
  1187. * @param {Number[] | String[]} ids
  1188. * @private
  1189. */
  1190. Network.prototype._removeNodes = function(ids) {
  1191. var nodes = this.body.nodes;
  1192. // remove from selection
  1193. for (var i = 0, len = ids.length; i < len; i++) {
  1194. if (this.selectionObj.nodes[ids[i]] !== undefined) {
  1195. this.body.nodes[ids[i]].unselect();
  1196. this._removeFromSelection(this.body.nodes[ids[i]]);
  1197. }
  1198. }
  1199. for (var i = 0, len = ids.length; i < len; i++) {
  1200. var id = ids[i];
  1201. delete nodes[id];
  1202. }
  1203. this._updateNodeIndexList();
  1204. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  1205. this._resetLevels();
  1206. this._setupHierarchicalLayout();
  1207. }
  1208. this.physics._updateCalculationNodes();
  1209. this._reconnectEdges();
  1210. this._updateSelection();
  1211. this._updateValueRange(nodes);
  1212. };
  1213. /**
  1214. * Load edges by reading the data table
  1215. * @param {Array | DataSet | DataView} edges The data containing the edges.
  1216. * @private
  1217. * @private
  1218. */
  1219. Network.prototype._setEdges = function(edges) {
  1220. var oldEdgesData = this.body.data.edges;
  1221. if (edges instanceof DataSet || edges instanceof DataView) {
  1222. this.body.data.edges = edges;
  1223. }
  1224. else if (Array.isArray(edges)) {
  1225. this.body.data.edges = new DataSet();
  1226. this.body.data.edges.add(edges);
  1227. }
  1228. else if (!edges) {
  1229. this.body.data.edges = new DataSet();
  1230. }
  1231. else {
  1232. throw new TypeError('Array or DataSet expected');
  1233. }
  1234. if (oldEdgesData) {
  1235. // unsubscribe from old dataset
  1236. util.forEach(this.edgesListeners, function (callback, event) {
  1237. oldEdgesData.off(event, callback);
  1238. });
  1239. }
  1240. // remove drawn edges
  1241. this.body.edges = {};
  1242. if (this.body.data.edges) {
  1243. // subscribe to new dataset
  1244. var me = this;
  1245. util.forEach(this.edgesListeners, function (callback, event) {
  1246. me.body.data.edges.on(event, callback);
  1247. });
  1248. // draw all new nodes
  1249. var ids = this.body.data.edges.getIds();
  1250. this._addEdges(ids);
  1251. }
  1252. this._reconnectEdges();
  1253. };
  1254. /**
  1255. * Add edges
  1256. * @param {Number[] | String[]} ids
  1257. * @private
  1258. */
  1259. Network.prototype._addEdges = function (ids) {
  1260. var edges = this.body.edges,
  1261. edgesData = this.body.data.edges;
  1262. for (var i = 0, len = ids.length; i < len; i++) {
  1263. var id = ids[i];
  1264. var oldEdge = edges[id];
  1265. if (oldEdge) {
  1266. oldEdge.disconnect();
  1267. }
  1268. var data = edgesData.get(id, {"showInternalIds" : true});
  1269. edges[id] = new Edge(data, this.body, this.constants);
  1270. }
  1271. this.moving = true;
  1272. this._updateValueRange(edges);
  1273. this._createBezierNodes();
  1274. this.physics._updateCalculationNodes();
  1275. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  1276. this._resetLevels();
  1277. this._setupHierarchicalLayout();
  1278. }
  1279. };
  1280. /**
  1281. * Update existing edges, or create them when not yet existing
  1282. * @param {Number[] | String[]} ids
  1283. * @private
  1284. */
  1285. Network.prototype._updateEdges = function (ids) {
  1286. var edges = this.body.edges;
  1287. var edgesData = this.body.data.edges;
  1288. for (var i = 0, len = ids.length; i < len; i++) {
  1289. var id = ids[i];
  1290. var data = edgesData.get(id);
  1291. var edge = edges[id];
  1292. if (edge) {
  1293. // update edge
  1294. edge.disconnect();
  1295. edge.setProperties(data);
  1296. edge.connect();
  1297. }
  1298. else {
  1299. // create edge
  1300. edge = new Edge(data, this.body, this.constants);
  1301. this.body.edges[id] = edge;
  1302. }
  1303. }
  1304. this._createBezierNodes();
  1305. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  1306. this._resetLevels();
  1307. this._setupHierarchicalLayout();
  1308. }
  1309. this.moving = true;
  1310. this._updateValueRange(edges);
  1311. };
  1312. /**
  1313. * Remove existing edges. Non existing ids will be ignored
  1314. * @param {Number[] | String[]} ids
  1315. * @private
  1316. */
  1317. Network.prototype._removeEdges = function (ids) {
  1318. var edges = this.body.edges;
  1319. // remove from selection
  1320. for (var i = 0, len = ids.length; i < len; i++) {
  1321. if (this.selectionObj.edges[ids[i]] !== undefined) {
  1322. edges[ids[i]].unselect();
  1323. this._removeFromSelection(edges[ids[i]]);
  1324. }
  1325. }
  1326. for (var i = 0, len = ids.length; i < len; i++) {
  1327. var id = ids[i];
  1328. var edge = edges[id];
  1329. if (edge) {
  1330. if (edge.via != null) {
  1331. delete this.body.supportNodes[edge.via.id];
  1332. }
  1333. edge.disconnect();
  1334. delete edges[id];
  1335. }
  1336. }
  1337. this.moving = true;
  1338. this._updateValueRange(edges);
  1339. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  1340. this._resetLevels();
  1341. this._setupHierarchicalLayout();
  1342. }
  1343. this.physics._updateCalculationNodes();
  1344. };
  1345. /**
  1346. * Reconnect all edges
  1347. * @private
  1348. */
  1349. Network.prototype._reconnectEdges = function() {
  1350. var id,
  1351. nodes = this.body.nodes,
  1352. edges = this.body.edges;
  1353. for (id in nodes) {
  1354. if (nodes.hasOwnProperty(id)) {
  1355. nodes[id].edges = [];
  1356. }
  1357. }
  1358. for (id in edges) {
  1359. if (edges.hasOwnProperty(id)) {
  1360. var edge = edges[id];
  1361. edge.from = null;
  1362. edge.to = null;
  1363. edge.connect();
  1364. }
  1365. }
  1366. };
  1367. /**
  1368. * Update the values of all object in the given array according to the current
  1369. * value range of the objects in the array.
  1370. * @param {Object} obj An object containing a set of Edges or Nodes
  1371. * The objects must have a method getValue() and
  1372. * setValueRange(min, max).
  1373. * @private
  1374. */
  1375. Network.prototype._updateValueRange = function(obj) {
  1376. var id;
  1377. // determine the range of the objects
  1378. var valueMin = undefined;
  1379. var valueMax = undefined;
  1380. var valueTotal = 0;
  1381. for (id in obj) {
  1382. if (obj.hasOwnProperty(id)) {
  1383. var value = obj[id].getValue();
  1384. if (value !== undefined) {
  1385. valueMin = (valueMin === undefined) ? value : Math.min(value, valueMin);
  1386. valueMax = (valueMax === undefined) ? value : Math.max(value, valueMax);
  1387. valueTotal += value;
  1388. }
  1389. }
  1390. }
  1391. // adjust the range of all objects
  1392. if (valueMin !== undefined && valueMax !== undefined) {
  1393. for (id in obj) {
  1394. if (obj.hasOwnProperty(id)) {
  1395. obj[id].setValueRange(valueMin, valueMax, valueTotal);
  1396. }
  1397. }
  1398. }
  1399. };
  1400. /**
  1401. * Set the translation of the network
  1402. * @param {Number} offsetX Horizontal offset
  1403. * @param {Number} offsetY Vertical offset
  1404. * @private
  1405. */
  1406. Network.prototype._setTranslation = function(offsetX, offsetY) {
  1407. if (this.translation === undefined) {
  1408. this.translation = {
  1409. x: 0,
  1410. y: 0
  1411. };
  1412. }
  1413. if (offsetX !== undefined) {
  1414. this.translation.x = offsetX;
  1415. }
  1416. if (offsetY !== undefined) {
  1417. this.translation.y = offsetY;
  1418. }
  1419. this.emit('viewChanged');
  1420. };
  1421. /**
  1422. * Get the translation of the network
  1423. * @return {Object} translation An object with parameters x and y, both a number
  1424. * @private
  1425. */
  1426. Network.prototype._getTranslation = function() {
  1427. return {
  1428. x: this.translation.x,
  1429. y: this.translation.y
  1430. };
  1431. };
  1432. /**
  1433. * Scale the network
  1434. * @param {Number} scale Scaling factor 1.0 is unscaled
  1435. * @private
  1436. */
  1437. Network.prototype._setScale = function(scale) {
  1438. this.scale = scale;
  1439. };
  1440. /**
  1441. * Get the current scale of the network
  1442. * @return {Number} scale Scaling factor 1.0 is unscaled
  1443. * @private
  1444. */
  1445. Network.prototype._getScale = function() {
  1446. return this.scale;
  1447. };
  1448. /**
  1449. * Move the network according to the keyboard presses.
  1450. *
  1451. * @private
  1452. */
  1453. Network.prototype._handleNavigation = function() {
  1454. if (this.xIncrement != 0 || this.yIncrement != 0) {
  1455. var translation = this._getTranslation();
  1456. this._setTranslation(translation.x+this.xIncrement, translation.y+this.yIncrement);
  1457. }
  1458. if (this.zoomIncrement != 0) {
  1459. var center = {
  1460. x: this.frame.canvas.clientWidth / 2,
  1461. y: this.frame.canvas.clientHeight / 2
  1462. };
  1463. this._zoom(this.scale*(1 + this.zoomIncrement), center);
  1464. }
  1465. };
  1466. /**
  1467. * Freeze the _animationStep
  1468. */
  1469. Network.prototype.freezeSimulation = function(freeze) {
  1470. if (freeze == true) {
  1471. this.freezeSimulationEnabled = true;
  1472. this.moving = false;
  1473. }
  1474. else {
  1475. this.freezeSimulationEnabled = false;
  1476. this.moving = true;
  1477. this.start();
  1478. }
  1479. };
  1480. /**
  1481. * This function cleans the support nodes if they are not needed and adds them when they are.
  1482. *
  1483. * @param {boolean} [disableStart]
  1484. * @private
  1485. */
  1486. Network.prototype._configureSmoothCurves = function(disableStart = true) {
  1487. if (this.constants.smoothCurves.enabled == true && this.constants.smoothCurves.dynamic == true) {
  1488. this._createBezierNodes();
  1489. // cleanup unused support nodes
  1490. for (let i = 0; i < this.body.supportNodeIndices.length; i++) {
  1491. let nodeId = this.body.supportNodeIndices[i];
  1492. // delete support nodes for edges that have been deleted
  1493. if (this.body.edges[this.body.supportNodes[nodeId].parentEdgeId] === undefined) {
  1494. delete this.body.supportNodes[nodeId];
  1495. }
  1496. }
  1497. }
  1498. else {
  1499. // delete the support nodes
  1500. this.body.supportNodes = {};
  1501. for (var edgeId in this.body.edges) {
  1502. if (this.body.edges.hasOwnProperty(edgeId)) {
  1503. this.body.edges[edgeId].via = null;
  1504. }
  1505. }
  1506. }
  1507. this._updateNodeIndexList();
  1508. this.physics._updateCalculationNodes();
  1509. if (!disableStart) {
  1510. this.moving = true;
  1511. this.start();
  1512. }
  1513. };
  1514. /**
  1515. * Bezier curves require an anchor point to calculate the smooth flow. These points are nodes. These nodes are invisible but
  1516. * are used for the force calculation.
  1517. *
  1518. * @private
  1519. */
  1520. Network.prototype._createBezierNodes = function(specificEdges = this.body.edges) {
  1521. if (this.constants.smoothCurves.enabled == true && this.constants.smoothCurves.dynamic == true) {
  1522. for (var edgeId in specificEdges) {
  1523. if (specificEdges.hasOwnProperty(edgeId)) {
  1524. var edge = specificEdges[edgeId];
  1525. if (edge.via == null) {
  1526. var nodeId = "edgeId:".concat(edge.id);
  1527. var node = new Node(
  1528. {id:nodeId,
  1529. mass:1,
  1530. shape:'circle',
  1531. image:"",
  1532. internalMultiplier:1
  1533. },{},{},this.constants);
  1534. this.body.supportNodes[nodeId] = node;
  1535. edge.via = node;
  1536. edge.via.parentEdgeId = edge.id;
  1537. edge.positionBezierNode();
  1538. }
  1539. }
  1540. }
  1541. this._updateNodeIndexList();
  1542. }
  1543. };
  1544. /**
  1545. * load the functions that load the mixins into the prototype.
  1546. *
  1547. * @private
  1548. */
  1549. Network.prototype._initializeMixinLoaders = function () {
  1550. for (var mixin in MixinLoader) {
  1551. if (MixinLoader.hasOwnProperty(mixin)) {
  1552. Network.prototype[mixin] = MixinLoader[mixin];
  1553. }
  1554. }
  1555. };
  1556. /**
  1557. * Load the XY positions of the nodes into the dataset.
  1558. */
  1559. Network.prototype.storePosition = function() {
  1560. console.log("storePosition is depricated: use .storePositions() from now on.")
  1561. this.storePositions();
  1562. };
  1563. /**
  1564. * Load the XY positions of the nodes into the dataset.
  1565. */
  1566. Network.prototype.storePositions = function() {
  1567. var dataArray = [];
  1568. for (var nodeId in this.body.nodes) {
  1569. if (this.body.nodes.hasOwnProperty(nodeId)) {
  1570. var node = this.body.nodes[nodeId];
  1571. var allowedToMoveX = !this.body.nodes.xFixed;
  1572. var allowedToMoveY = !this.body.nodes.yFixed;
  1573. if (this.body.data.nodes._data[nodeId].x != Math.round(node.x) || this.body.data.nodes._data[nodeId].y != Math.round(node.y)) {
  1574. dataArray.push({id:nodeId,x:Math.round(node.x),y:Math.round(node.y),allowedToMoveX:allowedToMoveX,allowedToMoveY:allowedToMoveY});
  1575. }
  1576. }
  1577. }
  1578. this.body.data.nodes.update(dataArray);
  1579. };
  1580. /**
  1581. * Return the positions of the nodes.
  1582. */
  1583. Network.prototype.getPositions = function(ids) {
  1584. var dataArray = {};
  1585. if (ids !== undefined) {
  1586. if (Array.isArray(ids) == true) {
  1587. for (var i = 0; i < ids.length; i++) {
  1588. if (this.body.nodes[ids[i]] !== undefined) {
  1589. var node = this.body.nodes[ids[i]];
  1590. dataArray[ids[i]] = {x: Math.round(node.x), y: Math.round(node.y)};
  1591. }
  1592. }
  1593. }
  1594. else {
  1595. if (this.body.nodes[ids] !== undefined) {
  1596. var node = this.body.nodes[ids];
  1597. dataArray[ids] = {x: Math.round(node.x), y: Math.round(node.y)};
  1598. }
  1599. }
  1600. }
  1601. else {
  1602. for (var nodeId in this.body.nodes) {
  1603. if (this.body.nodes.hasOwnProperty(nodeId)) {
  1604. var node = this.body.nodes[nodeId];
  1605. dataArray[nodeId] = {x: Math.round(node.x), y: Math.round(node.y)};
  1606. }
  1607. }
  1608. }
  1609. return dataArray;
  1610. };
  1611. /**
  1612. * Returns true when the Network is active.
  1613. * @returns {boolean}
  1614. */
  1615. Network.prototype.isActive = function () {
  1616. return !this.activator || this.activator.active;
  1617. };
  1618. /**
  1619. * Sets the scale
  1620. * @returns {Number}
  1621. */
  1622. Network.prototype.setScale = function () {
  1623. return this._setScale();
  1624. };
  1625. /**
  1626. * Returns the scale
  1627. * @returns {Number}
  1628. */
  1629. Network.prototype.getScale = function () {
  1630. return this._getScale();
  1631. };
  1632. /**
  1633. * Check if a node is a cluster.
  1634. * @param nodeId
  1635. * @returns {*}
  1636. */
  1637. Network.prototype.isCluster = function(nodeId) {
  1638. if (this.body.nodes[nodeId] !== undefined) {
  1639. return this.body.nodes[nodeId].isCluster;
  1640. }
  1641. else {
  1642. console.log("Node does not exist.")
  1643. return false;
  1644. }
  1645. };
  1646. /**
  1647. * Returns the scale
  1648. * @returns {Number}
  1649. */
  1650. Network.prototype.getCenterCoordinates = function () {
  1651. return this.DOMtoCanvas({x: 0.5 * this.frame.canvas.clientWidth, y: 0.5 * this.frame.canvas.clientHeight});
  1652. };
  1653. Network.prototype.getBoundingBox = function(nodeId) {
  1654. if (this.body.nodes[nodeId] !== undefined) {
  1655. return this.body.nodes[nodeId].boundingBox;
  1656. }
  1657. }
  1658. Network.prototype.getConnectedNodes = function(nodeId) {
  1659. var nodeList = [];
  1660. if (this.body.nodes[nodeId] !== undefined) {
  1661. var node = this.body.nodes[nodeId];
  1662. var nodeObj = {nodeId : true}; // used to quickly check if node already exists
  1663. for (var i = 0; i < node.edges.length; i++) {
  1664. var edge = node.edges[i];
  1665. if (edge.toId == nodeId) {
  1666. if (nodeObj[edge.fromId] === undefined) {
  1667. nodeList.push(edge.fromId);
  1668. nodeObj[edge.fromId] = true;
  1669. }
  1670. }
  1671. else if (edge.fromId == nodeId) {
  1672. if (nodeObj[edge.toId] === undefined) {
  1673. nodeList.push(edge.toId)
  1674. nodeObj[edge.toId] = true;
  1675. }
  1676. }
  1677. }
  1678. }
  1679. return nodeList;
  1680. }
  1681. Network.prototype.getEdgesFromNode = function(nodeId) {
  1682. var edgesList = [];
  1683. if (this.body.nodes[nodeId] !== undefined) {
  1684. var node = this.body.nodes[nodeId];
  1685. for (var i = 0; i < node.edges.length; i++) {
  1686. edgesList.push(node.edges[i].id);
  1687. }
  1688. }
  1689. return edgesList;
  1690. }
  1691. Network.prototype.generateColorObject = function(color) {
  1692. return util.parseColor(color);
  1693. }
  1694. module.exports = Network;