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.

1020 lines
32 KiB

  1. let util = require('../../util');
  2. let Hammer = require('../../module/hammer');
  3. let hammerUtil = require('../../hammerUtil');
  4. let locales = require('../locales');
  5. /**
  6. * clears the toolbar div element of children
  7. *
  8. * @private
  9. */
  10. class ManipulationSystem {
  11. constructor(body, canvas, selectionHandler) {
  12. this.body = body;
  13. this.canvas = canvas;
  14. this.selectionHandler = selectionHandler;
  15. this.editMode = false;
  16. this.manipulationDiv = undefined;
  17. this.editModeDiv = undefined;
  18. this.closeDiv = undefined;
  19. this.manipulationHammers = [];
  20. this.temporaryUIFunctions = {};
  21. this.temporaryEventFunctions = [];
  22. this.touchTime = 0;
  23. this.temporaryIds = {nodes: [], edges:[]};
  24. this.guiEnabled = false;
  25. this.selectedControlNode = undefined;
  26. this.options = {};
  27. this.defaultOptions = {
  28. enabled: false,
  29. initiallyVisible: false,
  30. locale: 'en',
  31. locales: locales,
  32. functionality:{
  33. addNode: true,
  34. addEdge: true,
  35. editNode: true,
  36. editEdge: true,
  37. deleteNode: true,
  38. deleteEdge: true
  39. },
  40. handlerFunctions: {
  41. addNode: undefined,
  42. addEdge: undefined,
  43. editNode: undefined,
  44. editEdge: undefined,
  45. deleteNode: undefined,
  46. deleteEdge: undefined
  47. },
  48. controlNodeStyle:{
  49. shape:'dot',
  50. size:6,
  51. color: {background: '#ff0000', border: '#3c3c3c', highlight: {background: '#07f968'}},
  52. borderWidth: 2,
  53. borderWidthSelected: 2
  54. }
  55. }
  56. util.extend(this.options, this.defaultOptions);
  57. }
  58. /**
  59. * Set the Options
  60. * @param options
  61. */
  62. setOptions(options) {
  63. if (options !== undefined) {
  64. if (typeof options == 'boolean') {
  65. this.options.enabled = options;
  66. }
  67. else {
  68. this.options.enabled = true;
  69. util.deepExtend(this.options, options);
  70. }
  71. if (this.options.initiallyVisible === true) {
  72. this.editMode = true;
  73. }
  74. this._setup();
  75. }
  76. }
  77. /**
  78. * Enable or disable edit-mode. Draws the DOM required and cleans up after itself.
  79. *
  80. * @private
  81. */
  82. toggleEditMode() {
  83. this.editMode = !this.editMode;
  84. if (this.guiEnabled === true) {
  85. let toolbar = this.manipulationDiv;
  86. let closeDiv = this.closeDiv;
  87. let editModeDiv = this.editModeDiv;
  88. if (this.editMode === true) {
  89. toolbar.style.display = "block";
  90. closeDiv.style.display = "block";
  91. editModeDiv.style.display = "none";
  92. this._bindHammerToDiv(closeDiv, this.toggleEditMode.bind(this));
  93. this.showManipulatorToolbar();
  94. }
  95. else {
  96. toolbar.style.display = "none";
  97. closeDiv.style.display = "none";
  98. editModeDiv.style.display = "block";
  99. this._createEditButton();
  100. }
  101. }
  102. }
  103. /**
  104. * Creates the main toolbar. Removes functions bound to the select event. Binds all the buttons of the toolbar.
  105. *
  106. * @private
  107. */
  108. showManipulatorToolbar() {
  109. // restore the state of any bound functions or events, remove control nodes, restore physics
  110. this._clean();
  111. // reset global letiables
  112. this.manipulationDOM = {};
  113. let selectedNodeCount = this.selectionHandler._getSelectedNodeCount();
  114. let selectedEdgeCount = this.selectionHandler._getSelectedEdgeCount();
  115. let selectedTotalCount = selectedNodeCount + selectedEdgeCount;
  116. let locale = this.options.locales[this.options.locale];
  117. let needSeperator = false;
  118. if (this.options.functionality.addNode === true) {
  119. this._createAddNodeButton(locale);
  120. needSeperator = true;
  121. }
  122. if (this.options.functionality.addEdge === true) {
  123. if (needSeperator === true) {this._createSeperator(1);} else {needSeperator = true;}
  124. this._createAddEdgeButton(locale);
  125. }
  126. if (selectedNodeCount === 1 && typeof this.options.handlerFunctions.editNode === 'function' && this.options.functionality.editNode === true) {
  127. if (needSeperator === true) {this._createSeperator(2);} else {needSeperator = true;}
  128. this._createEditNodeButton(locale);
  129. }
  130. else if (selectedEdgeCount === 1 && selectedNodeCount === 0 && this.options.functionality.editEdge === true) {
  131. if (needSeperator === true) {this._createSeperator(3);} else {needSeperator = true;}
  132. this._createEditEdgeButton(locale);
  133. }
  134. // remove buttons
  135. if (selectedTotalCount !== 0) {
  136. if (selectedNodeCount === 1 && this.options.functionality.deleteNode === true) {
  137. if (needSeperator === true) {this._createSeperator(4);}
  138. this._createDeleteButton(locale);
  139. }
  140. else if (selectedNodeCount === 0 && this.options.functionality.deleteEdge === true) {
  141. if (needSeperator === true) {this._createSeperator(4);}
  142. this._createDeleteButton(locale);
  143. }
  144. }
  145. // bind the close button
  146. this._bindHammerToDiv(this.closeDiv, this.toggleEditMode.bind(this));
  147. // refresh this bar based on what has been selected
  148. this._temporaryBindEvent('select', this.showManipulatorToolbar.bind(this));
  149. // redraw to show any possible changes
  150. this.body.emitter.emit('_redraw');
  151. }
  152. /**
  153. * Create the toolbar for adding Nodes
  154. *
  155. * @private
  156. */
  157. addNodeMode() {
  158. // clear the toolbar
  159. this._clean();
  160. if (this.guiEnabled === true) {
  161. let locale = this.options.locales[this.options.locale];
  162. this.manipulationDOM = {};
  163. this._createBackButton(locale);
  164. this._createSeperator();
  165. this._createDescription(locale['addDescription'])
  166. // bind the close button
  167. this._bindHammerToDiv(this.closeDiv, this.toggleEditMode.bind(this));
  168. }
  169. this._temporaryBindEvent('click', this._performAddNode.bind(this));
  170. }
  171. /**
  172. * call the bound function to handle the editing of the node. The node has to be selected.
  173. *
  174. * @private
  175. */
  176. editNode() {
  177. if (typeof this.options.handlerFunctions.editNode === 'function') {
  178. let node = this.selectionHandler._getSelectedNode();
  179. if (node.isCluster !== true) {
  180. let data = util.deepExtend({}, node.options, true);
  181. data.x = node.x;
  182. data.y = node.y;
  183. if (this.options.handlerFunctions.editNode.length == 2) {
  184. this.options.handlerFunctions.editNode(data, (finalizedData) => {
  185. this.body.data.nodes.update(finalizedData);
  186. this.showManipulatorToolbar();
  187. });
  188. }
  189. else {
  190. throw new Error('The function for edit does not support two arguments (data, callback)');
  191. }
  192. }
  193. else {
  194. alert(this.options.locales[this.options.locale]["editClusterError"]);
  195. }
  196. }
  197. else {
  198. throw new Error('No function has been configured to handle the editing of nodes.');
  199. }
  200. }
  201. /**
  202. * create the toolbar to connect nodes
  203. *
  204. * @private
  205. */
  206. addEdgeMode() {
  207. // _clean the system
  208. this._clean();
  209. if (this.guiEnabled === true) {
  210. let locale = this.options.locales[this.options.locale];
  211. this.manipulationDOM = {};
  212. this._createBackButton(locale);
  213. this._createSeperator();
  214. this._createDescription(locale['edgeDescription']);
  215. // bind the close button
  216. this._bindHammerToDiv(this.closeDiv, this.toggleEditMode.bind(this));
  217. }
  218. // temporarily overload functions
  219. this._temporaryBindUI('onTouch', this._handleConnect.bind(this));
  220. this._temporaryBindUI('onDragEnd', this._finishConnect.bind(this));
  221. this._temporaryBindUI('onHold', () => {});
  222. }
  223. /**
  224. * create the toolbar to edit edges
  225. *
  226. * @private
  227. */
  228. editEdgeMode() {
  229. // clear the system
  230. this._clean();
  231. if (this.guiEnabled === true) {
  232. let locale = this.options.locales[this.options.locale];
  233. this.manipulationDOM = {};
  234. this._createBackButton(locale);
  235. this._createSeperator();
  236. this._createDescription(locale['editEdgeDescription']);
  237. // bind the close button
  238. this._bindHammerToDiv(this.closeDiv, this.toggleEditMode.bind(this));
  239. }
  240. this.edgeBeingEditedId = this.selectionHandler.getSelectedEdges()[0];
  241. let edge = this.body.edges[this.edgeBeingEditedId];
  242. // create control nodes
  243. let controlNodeFrom = this._getNewTargetNode(edge.from.x, edge.from.y);
  244. let controlNodeTo = this._getNewTargetNode(edge.to.x, edge.to.y);
  245. this.temporaryIds.nodes.push(controlNodeFrom.id);
  246. this.temporaryIds.nodes.push(controlNodeTo.id);
  247. this.body.nodes[controlNodeFrom.id] = controlNodeFrom;
  248. this.body.nodeIndices.push(controlNodeFrom.id);
  249. this.body.nodes[controlNodeTo.id] = controlNodeTo;
  250. this.body.nodeIndices.push(controlNodeTo.id);
  251. // temporarily overload UI functions, cleaned up automatically because of _temporaryBindUI
  252. this._temporaryBindUI('onTouch', this._controlNodeTouch.bind(this)); // used to get the position
  253. this._temporaryBindUI('onTap', () => {}); // disabled
  254. this._temporaryBindUI('onHold', () => {}); // disabled
  255. this._temporaryBindUI('onDragStart', this._controlNodeDragStart.bind(this));// used to select control node
  256. this._temporaryBindUI('onDrag', this._controlNodeDrag.bind(this)); // used to drag control node
  257. this._temporaryBindUI('onDragEnd', this._controlNodeDragEnd.bind(this)); // used to connect or revert control nodes
  258. this._temporaryBindUI('onMouseMove', () => {}); // disabled
  259. // create function to position control nodes correctly on movement
  260. // automatically cleaned up because we use the temporary bind
  261. this._temporaryBindEvent('beforeDrawing', (ctx) => {
  262. let positions = edge.edgeType.findBorderPositions(ctx);
  263. if (controlNodeFrom.selected === false) {
  264. controlNodeFrom.x = positions.from.x;
  265. controlNodeFrom.y = positions.from.y;
  266. }
  267. if (controlNodeTo.selected === false) {
  268. controlNodeTo.x = positions.to.x;
  269. controlNodeTo.y = positions.to.y;
  270. }
  271. });
  272. this.body.emitter.emit('_redraw');
  273. }
  274. /**
  275. * delete everything in the selection
  276. *
  277. * @private
  278. */
  279. deleteSelected() {
  280. let selectedNodes = this.selectionHandler.getSelectedNodes();
  281. let selectedEdges = this.selectionHandler.getSelectedEdges();
  282. let deleteFunction = undefined;
  283. if (selectedNodes.length > 0) {
  284. for (let i = 0; i < selectedNodes.length; i++) {
  285. if (this.body.nodes[selectedNodes[i]].isCluster === true) {
  286. alert(this.options.locales[this.options.locale]["deleteClusterError"]);
  287. return;
  288. }
  289. }
  290. if (typeof this.options.handlerFunctions.deleteNode === 'function') {
  291. deleteFunction = this.options.handlerFunctions.deleteNode;
  292. }
  293. }
  294. else if (selectedEdges.length > 0) {
  295. if (typeof this.options.handlerFunctions.deleteEdge === 'function') {
  296. deleteFunction = this.options.handlerFunctions.deleteEdge;
  297. }
  298. }
  299. if (typeof deleteFunction === 'function') {
  300. let data = {nodes: selectedNodes, edges: selectedEdges};
  301. if (deleteFunction.length == 2) {
  302. deleteFunction(data, (finalizedData) => {
  303. this.body.data.edges.remove(finalizedData.edges);
  304. this.body.data.nodes.remove(finalizedData.nodes);
  305. this.body.emitter.emit("startSimulation");
  306. });
  307. }
  308. else {
  309. throw new Error('The function for delete does not support two arguments (data, callback)')
  310. }
  311. }
  312. else {
  313. this.body.data.edges.remove(selectedEdges);
  314. this.body.data.nodes.remove(selectedNodes);
  315. this.body.emitter.emit("startSimulation");
  316. }
  317. }
  318. //********************************************** PRIVATE ***************************************//
  319. /**
  320. * draw or remove the DOM
  321. * @private
  322. */
  323. _setup() {
  324. if (this.options.enabled === true) {
  325. // Enable the GUI
  326. this.guiEnabled = true;
  327. // remove override
  328. this.selectionHandler.forceSelectEdges = true;
  329. this._createWrappers();
  330. if (this.editMode === false) {
  331. this._createEditButton();
  332. }
  333. else {
  334. this.showManipulatorToolbar();
  335. }
  336. }
  337. else {
  338. this._removeManipulationDOM();
  339. // disable the gui
  340. this.guiEnabled = false;
  341. }
  342. }
  343. /**
  344. * create the div overlays that contain the DOM
  345. * @private
  346. */
  347. _createWrappers() {
  348. // load the manipulator HTML elements. All styling done in css.
  349. if (this.manipulationDiv === undefined) {
  350. this.manipulationDiv = document.createElement('div');
  351. this.manipulationDiv.className = 'network-manipulationDiv';
  352. if (this.editMode === true) {
  353. this.manipulationDiv.style.display = "block";
  354. }
  355. else {
  356. this.manipulationDiv.style.display = "none";
  357. }
  358. this.canvas.frame.appendChild(this.manipulationDiv);
  359. }
  360. // container for the edit button.
  361. if (this.editModeDiv === undefined) {
  362. this.editModeDiv = document.createElement('div');
  363. this.editModeDiv.className = 'network-manipulation-editMode';
  364. if (this.editMode === true) {
  365. this.editModeDiv.style.display = "none";
  366. }
  367. else {
  368. this.editModeDiv.style.display = "block";
  369. }
  370. this.canvas.frame.appendChild(this.editModeDiv);
  371. }
  372. // container for the close div button
  373. if (this.closeDiv === undefined) {
  374. this.closeDiv = document.createElement('div');
  375. this.closeDiv.className = 'network-manipulation-closeDiv';
  376. this.closeDiv.style.display = this.manipulationDiv.style.display;
  377. this.canvas.frame.appendChild(this.closeDiv);
  378. }
  379. }
  380. /**
  381. * generate a new target node. Used for creating new edges and editing edges
  382. * @param x
  383. * @param y
  384. * @returns {*}
  385. * @private
  386. */
  387. _getNewTargetNode(x,y) {
  388. let controlNodeStyle = util.deepExtend({}, this.options.controlNodeStyle);
  389. controlNodeStyle.id = 'targetNode' + util.randomUUID();
  390. controlNodeStyle.hidden = false;
  391. controlNodeStyle.physics = false;
  392. controlNodeStyle.x = x;
  393. controlNodeStyle.y = y;
  394. return this.body.functions.createNode(controlNodeStyle);
  395. }
  396. /**
  397. * Create the edit button
  398. */
  399. _createEditButton() {
  400. // restore everything to it's original state (if applicable)
  401. this._clean();
  402. // reset the manipulationDOM
  403. this.manipulationDOM = {};
  404. // empty the editModeDiv
  405. util.recursiveDOMDelete(this.editModeDiv);
  406. // create the contents for the editMode button
  407. let locale = this.options.locales[this.options.locale];
  408. let button = this._createButton('editMode', 'network-manipulationUI edit editmode', locale['edit']);
  409. this.editModeDiv.appendChild(button);
  410. // bind a hammer listener to the button, calling the function toggleEditMode.
  411. this._bindHammerToDiv(button, this.toggleEditMode.bind(this));
  412. }
  413. /**
  414. * this function cleans up after everything this module does. Temporary elements, functions and events are removed, physics restored, hammers removed.
  415. * @private
  416. */
  417. _clean() {
  418. // _clean the divs
  419. if (this.guiEnabled === true) {
  420. util.recursiveDOMDelete(this.editModeDiv);
  421. util.recursiveDOMDelete(this.manipulationDiv);
  422. // removes all the bindings and overloads
  423. this._cleanManipulatorHammers();
  424. }
  425. // remove temporary nodes and edges
  426. this._cleanupTemporaryNodesAndEdges();
  427. // restore overloaded UI functions
  428. this._unbindTemporaryUIs();
  429. // remove the temporaryEventFunctions
  430. this._unbindTemporaryEvents();
  431. // restore the physics if required
  432. this.body.emitter.emit("restorePhysics");
  433. }
  434. /**
  435. * Each dom element has it's own hammer. They are stored in this.manipulationHammers. This cleans them up.
  436. * @private
  437. */
  438. _cleanManipulatorHammers() {
  439. // _clean hammer bindings
  440. if (this.manipulationHammers.length != 0) {
  441. for (let i = 0; i < this.manipulationHammers.length; i++) {
  442. this.manipulationHammers[i].destroy();
  443. }
  444. this.manipulationHammers = [];
  445. }
  446. }
  447. /**
  448. * Remove all DOM elements created by this module.
  449. * @private
  450. */
  451. _removeManipulationDOM() {
  452. // removes all the bindings and overloads
  453. this._clean();
  454. // empty the manipulation divs
  455. util.recursiveDOMDelete(this.manipulationDiv);
  456. util.recursiveDOMDelete(this.editModeDiv);
  457. util.recursiveDOMDelete(this.closeDiv);
  458. // remove the manipulation divs
  459. this.canvas.frame.removeChild(this.manipulationDiv);
  460. this.canvas.frame.removeChild(this.editModeDiv);
  461. this.canvas.frame.removeChild(this.closeDiv);
  462. // set the references to undefined
  463. this.manipulationDiv = undefined;
  464. this.editModeDiv = undefined;
  465. this.closeDiv = undefined;
  466. // remove override
  467. this.selectionHandler.forceSelectEdges = false;
  468. }
  469. /**
  470. * create a seperator line. the index is to differentiate in the manipulation dom
  471. * @param index
  472. * @private
  473. */
  474. _createSeperator(index = 1) {
  475. this.manipulationDOM['seperatorLineDiv' + index] = document.createElement('div');
  476. this.manipulationDOM['seperatorLineDiv' + index].className = 'network-seperatorLine';
  477. this.manipulationDiv.appendChild(this.manipulationDOM['seperatorLineDiv' + index]);
  478. }
  479. // ---------------------- DOM functions for buttons --------------------------//
  480. _createAddNodeButton(locale) {
  481. let button = this._createButton('addNode', 'network-manipulationUI add', locale['addNode']);
  482. this.manipulationDiv.appendChild(button);
  483. this._bindHammerToDiv(button, this.addNodeMode.bind(this));
  484. }
  485. _createAddEdgeButton(locale) {
  486. let button = this._createButton('addEdge', 'network-manipulationUI connect', locale['addEdge']);
  487. this.manipulationDiv.appendChild(button);
  488. this._bindHammerToDiv(button, this.addEdgeMode.bind(this));
  489. }
  490. _createEditNodeButton(locale) {
  491. let button = this._createButton('editNode', 'network-manipulationUI edit', locale['editNode']);
  492. this.manipulationDiv.appendChild(button);
  493. this._bindHammerToDiv(button, this.editNode.bind(this));
  494. }
  495. _createEditEdgeButton(locale) {
  496. let button = this._createButton('editEdge', 'network-manipulationUI edit', locale['editEdge']);
  497. this.manipulationDiv.appendChild(button);
  498. this._bindHammerToDiv(button, this.editEdgeMode.bind(this));
  499. }
  500. _createDeleteButton(locale) {
  501. let button = this._createButton('delete', 'network-manipulationUI delete', locale['del']);
  502. this.manipulationDiv.appendChild(button);
  503. this._bindHammerToDiv(button, this.deleteSelected.bind(this));
  504. }
  505. _createBackButton(locale) {
  506. let button = this._createButton('back', 'network-manipulationUI back', locale['back']);
  507. this.manipulationDiv.appendChild(button);
  508. this._bindHammerToDiv(button, this.showManipulatorToolbar.bind(this));
  509. }
  510. _createButton(id, className, label, labelClassName = 'network-manipulationLabel') {
  511. this.manipulationDOM[id+"Div"] = document.createElement('div');
  512. this.manipulationDOM[id+"Div"].className = className;
  513. this.manipulationDOM[id+"Label"] = document.createElement('div');
  514. this.manipulationDOM[id+"Label"].className = labelClassName;
  515. this.manipulationDOM[id+"Label"].innerHTML = label;
  516. this.manipulationDOM[id+"Div"].appendChild(this.manipulationDOM[id+'Label']);
  517. return this.manipulationDOM[id+"Div"];
  518. }
  519. _createDescription(label) {
  520. this.manipulationDiv.appendChild(
  521. this._createButton('description', 'network-manipulationUI none', label)
  522. );
  523. }
  524. // -------------------------- End of DOM functions for buttons ------------------------------//
  525. /**
  526. * this binds an event until cleanup by the clean functions.
  527. * @param event
  528. * @param newFunction
  529. * @private
  530. */
  531. _temporaryBindEvent(event, newFunction) {
  532. this.temporaryEventFunctions.push({event:event, boundFunction:newFunction});
  533. this.body.emitter.on(event, newFunction);
  534. }
  535. /**
  536. * this overrides an UI function until cleanup by the clean function
  537. * @param UIfunctionName
  538. * @param newFunction
  539. * @private
  540. */
  541. _temporaryBindUI(UIfunctionName, newFunction) {
  542. if (this.body.eventListeners[UIfunctionName] !== undefined) {
  543. this.temporaryUIFunctions[UIfunctionName] = this.body.eventListeners[UIfunctionName];
  544. this.body.eventListeners[UIfunctionName] = newFunction;
  545. }
  546. else {
  547. throw new Error('This UI function does not exist. Typo? You tried: "' + UIfunctionName + '" possible are: ' + JSON.stringify(Object.keys(this.body.eventListeners)));
  548. }
  549. }
  550. /**
  551. * Restore the overridden UI functions to their original state.
  552. *
  553. * @private
  554. */
  555. _unbindTemporaryUIs() {
  556. for (let functionName in this.temporaryUIFunctions) {
  557. if (this.temporaryUIFunctions.hasOwnProperty(functionName)) {
  558. this.body.eventListeners[functionName] = this.temporaryUIFunctions[functionName];
  559. delete this.temporaryUIFunctions[functionName];
  560. }
  561. }
  562. this.temporaryUIFunctions = {};
  563. }
  564. /**
  565. * Unbind the events created by _temporaryBindEvent
  566. * @private
  567. */
  568. _unbindTemporaryEvents() {
  569. for (let i = 0; i < this.temporaryEventFunctions.length; i++) {
  570. let eventName = this.temporaryEventFunctions[i].event;
  571. let boundFunction = this.temporaryEventFunctions[i].boundFunction;
  572. this.body.emitter.off(eventName, boundFunction);
  573. }
  574. this.temporaryEventFunctions = [];
  575. }
  576. /**
  577. * Bind an hammer instance to a DOM element.
  578. * @param domElement
  579. * @param funct
  580. */
  581. _bindHammerToDiv(domElement, boundFunction) {
  582. let hammer = new Hammer(domElement, {});
  583. hammerUtil.onTouch(hammer, boundFunction);
  584. this.manipulationHammers.push(hammer);
  585. }
  586. /**
  587. * Neatly clean up temporary edges and nodes
  588. * @private
  589. */
  590. _cleanupTemporaryNodesAndEdges() {
  591. // _clean temporary edges
  592. for (let i = 0; i < this.temporaryIds.edges.length; i++) {
  593. this.body.edges[this.temporaryIds.edges[i]].disconnect();
  594. delete this.body.edges[this.temporaryIds.edges[i]];
  595. let indexTempEdge = this.body.edgeIndices.indexOf(this.temporaryIds.edges[i]);
  596. if (indexTempEdge !== -1) {this.body.edgeIndices.splice(indexTempEdge,1);}
  597. }
  598. // _clean temporary nodes
  599. for (let i = 0; i < this.temporaryIds.nodes.length; i++) {
  600. delete this.body.nodes[this.temporaryIds.nodes[i]];
  601. let indexTempNode = this.body.nodeIndices.indexOf(this.temporaryIds.nodes[i]);
  602. if (indexTempNode !== -1) {this.body.nodeIndices.splice(indexTempNode,1);}
  603. }
  604. this.temporaryIds = {nodes: [], edges: []};
  605. }
  606. // ------------------------------------------ EDIT EDGE FUNCTIONS -----------------------------------------//
  607. /**
  608. * the touch is used to get the position of the initial click
  609. * @param event
  610. * @private
  611. */
  612. _controlNodeTouch(event) {
  613. this.lastTouch = this.body.functions.getPointer(event.center);
  614. this.lastTouch.translation = util.extend({},this.body.view.translation); // copy the object
  615. }
  616. /**
  617. * the drag start is used to mark one of the control nodes as selected.
  618. * @param event
  619. * @private
  620. */
  621. _controlNodeDragStart(event) {
  622. let pointer = this.lastTouch;
  623. let pointerObj = this.selectionHandler._pointerToPositionObject(pointer);
  624. let from = this.body.nodes[this.temporaryIds.nodes[0]];
  625. let to = this.body.nodes[this.temporaryIds.nodes[1]];
  626. let edge = this.body.edges[this.edgeBeingEditedId];
  627. this.selectedControlNode = undefined;
  628. let fromSelect = from.isOverlappingWith(pointerObj);
  629. let toSelect = to.isOverlappingWith(pointerObj);
  630. if (fromSelect === true) {
  631. this.selectedControlNode = from;
  632. edge.edgeType.from = from;
  633. }
  634. else if (toSelect === true) {
  635. this.selectedControlNode = to;
  636. edge.edgeType.to = to;
  637. }
  638. this.body.emitter.emit("_redraw");
  639. }
  640. /**
  641. * dragging the control nodes or the canvas
  642. * @param event
  643. * @private
  644. */
  645. _controlNodeDrag(event) {
  646. this.body.emitter.emit("disablePhysics");
  647. let pointer = this.body.functions.getPointer(event.center);
  648. let pos = this.canvas.DOMtoCanvas(pointer);
  649. if (this.selectedControlNode !== undefined) {
  650. this.selectedControlNode.x = pos.x;
  651. this.selectedControlNode.y = pos.y;
  652. }
  653. else {
  654. // if the drag was not started properly because the click started outside the network div, start it now.
  655. let diffX = pointer.x - this.lastTouch.x;
  656. let diffY = pointer.y - this.lastTouch.y;
  657. this.body.view.translation = {x:this.lastTouch.translation.x + diffX, y:this.lastTouch.translation.y + diffY};
  658. }
  659. this.body.emitter.emit("_redraw");
  660. }
  661. /**
  662. * connecting or restoring the control nodes.
  663. * @param event
  664. * @private
  665. */
  666. _controlNodeDragEnd(event) {
  667. let pointer = this.body.functions.getPointer(event.center);
  668. let pointerObj = this.selectionHandler._pointerToPositionObject(pointer);
  669. let edge = this.body.edges[this.edgeBeingEditedId];
  670. let overlappingNodeIds = this.selectionHandler._getAllNodesOverlappingWith(pointerObj);
  671. let node = undefined;
  672. for (let i = overlappingNodeIds.length-1; i >= 0; i--) {
  673. if (overlappingNodeIds[i] !== this.selectedControlNode.id) {
  674. node = this.body.nodes[overlappingNodeIds[i]];
  675. break;
  676. }
  677. }
  678. // perform the connection
  679. if (node !== undefined && this.selectedControlNode !== undefined) {
  680. if (node.isCluster === true) {
  681. alert(this.options.locales[this.options.locale]["createEdgeError"])
  682. }
  683. else {
  684. let from = this.body.nodes[this.temporaryIds.nodes[0]];
  685. if (this.selectedControlNode.id == from.id) {
  686. this._performEditEdge(node.id, edge.to.id);
  687. }
  688. else {
  689. this._performEditEdge(edge.from.id, node.id);
  690. }
  691. }
  692. }
  693. else {
  694. edge.updateEdgeType();
  695. this.body.emitter.emit("restorePhysics");
  696. }
  697. this.body.emitter.emit("_redraw");
  698. }
  699. // ------------------------------------ END OF EDIT EDGE FUNCTIONS -----------------------------------------//
  700. // ------------------------------------------- ADD EDGE FUNCTIONS -----------------------------------------//
  701. /**
  702. * the function bound to the selection event. It checks if you want to connect a cluster and changes the description
  703. * to walk the user through the process.
  704. *
  705. * @private
  706. */
  707. _handleConnect(event) {
  708. // check to avoid double fireing of this function.
  709. if (new Date().valueOf() - this.touchTime > 100) {
  710. let pointer = this.body.functions.getPointer(event.center);
  711. let node = this.selectionHandler.getNodeAt(pointer);
  712. if (node !== undefined) {
  713. if (node.isCluster === true) {
  714. alert(this.options.locales[this.options.locale]['createEdgeError'])
  715. }
  716. else {
  717. // create a node the temporary line can look at
  718. let targetNode = this._getNewTargetNode(node.x,node.y);
  719. let targetNodeId = targetNode.id;
  720. this.body.nodes[targetNode.id] = targetNode;
  721. this.body.nodeIndices.push(targetNode.id);
  722. // create a temporary edge
  723. let connectionEdge = this.body.functions.createEdge({
  724. id: "connectionEdge" + util.randomUUID(),
  725. from: node.id,
  726. to: targetNode.id,
  727. physics:false,
  728. smooth: {
  729. enabled: true,
  730. dynamic: false,
  731. type: "continuous",
  732. roundness: 0.5
  733. }
  734. });
  735. this.body.edges[connectionEdge.id] = connectionEdge;
  736. this.body.edgeIndices.push(connectionEdge.id);
  737. this.temporaryIds.nodes.push(targetNode.id);
  738. this.temporaryIds.edges.push(connectionEdge.id);
  739. this.temporaryUIFunctions["onDrag"] = this.body.eventListeners.onDrag;
  740. this.body.eventListeners.onDrag = (event) => {
  741. let pointer = this.body.functions.getPointer(event.center);
  742. let targetNode = this.body.nodes[targetNodeId];
  743. targetNode.x = this.canvas._XconvertDOMtoCanvas(pointer.x);
  744. targetNode.y = this.canvas._YconvertDOMtoCanvas(pointer.y);
  745. this.body.emitter.emit("_redraw");
  746. }
  747. }
  748. }
  749. this.touchTime = new Date().valueOf();
  750. // do the original touch events
  751. this.temporaryUIFunctions["onTouch"](event);
  752. }
  753. }
  754. /**
  755. * Connect the new edge to the target if one exists, otherwise remove temp line
  756. * @param event
  757. * @private
  758. */
  759. _finishConnect(event) {
  760. let pointer = this.body.functions.getPointer(event.center);
  761. let pointerObj = this.selectionHandler._pointerToPositionObject(pointer);
  762. // remember the edge id
  763. let connectFromId = undefined;
  764. if (this.temporaryIds.edges[0] !== undefined) {
  765. connectFromId = this.body.edges[this.temporaryIds.edges[0]].fromId;
  766. }
  767. //restore the drag function
  768. if (this.temporaryUIFunctions["onDrag"] !== undefined) {
  769. this.body.eventListeners.onDrag = this.temporaryUIFunctions["onDrag"];
  770. delete this.temporaryUIFunctions["onDrag"];
  771. }
  772. // get the overlapping node but NOT the temporary node;
  773. let overlappingNodeIds = this.selectionHandler._getAllNodesOverlappingWith(pointerObj);
  774. let node = undefined;
  775. for (let i = overlappingNodeIds.length-1; i >= 0; i--) {
  776. if (this.temporaryIds.nodes.indexOf(overlappingNodeIds[i]) !== -1) {
  777. node = this.body.nodes[overlappingNodeIds[i]];
  778. break;
  779. }
  780. }
  781. // clean temporary nodes and edges.
  782. this._cleanupTemporaryNodesAndEdges();
  783. // perform the connection
  784. if (node !== undefined) {
  785. if (node.isCluster === true) {
  786. alert(this.options.locales[this.options.locale]["createEdgeError"]);
  787. }
  788. else {
  789. if (this.body.nodes[connectFromId] !== undefined && this.body.nodes[node.id] !== undefined) {
  790. this._performCreateEdge(connectFromId, node.id);
  791. }
  792. }
  793. }
  794. this.body.emitter.emit("_redraw");
  795. }
  796. // --------------------------------------- END OF ADD EDGE FUNCTIONS -------------------------------------//
  797. // ------------------------------ Performing all the actual data manipulation ------------------------//
  798. /**
  799. * Adds a node on the specified location
  800. */
  801. _performAddNode(clickData) {
  802. let defaultData = {
  803. id: util.randomUUID(),
  804. x: clickData.pointer.canvas.x,
  805. y: clickData.pointer.canvas.y,
  806. label: "new"
  807. };
  808. if (typeof this.options.handlerFunctions.addNode === 'function') {
  809. if (this.options.handlerFunctions.addNode.length == 2) {
  810. this.options.handlerFunctions.addNode(defaultData, (finalizedData) => {
  811. this.body.data.nodes.add(finalizedData);
  812. this.showManipulatorToolbar();
  813. });
  814. }
  815. else {
  816. throw new Error('The function for add does not support two arguments (data,callback)');
  817. this.showManipulatorToolbar();
  818. }
  819. }
  820. else {
  821. this.body.data.nodes.add(defaultData);
  822. this.showManipulatorToolbar();
  823. }
  824. }
  825. /**
  826. * connect two nodes with a new edge.
  827. *
  828. * @private
  829. */
  830. _performCreateEdge(sourceNodeId, targetNodeId) {
  831. let defaultData = {from: sourceNodeId, to: targetNodeId};
  832. if (this.options.handlerFunctions.addEdge) {
  833. if (this.options.handlerFunctions.addEdge.length == 2) {
  834. this.options.handlerFunctions.addEdge(defaultData, (finalizedData) => {
  835. this.body.data.edges.add(finalizedData);
  836. this.selectionHandler.unselectAll();
  837. this.showManipulatorToolbar();
  838. });
  839. }
  840. else {
  841. throw new Error('The function for connect does not support two arguments (data,callback)');
  842. }
  843. }
  844. else {
  845. this.body.data.edges.add(defaultData);
  846. this.selectionHandler.unselectAll();
  847. this.showManipulatorToolbar();
  848. }
  849. }
  850. /**
  851. * connect two nodes with a new edge.
  852. *
  853. * @private
  854. */
  855. _performEditEdge(sourceNodeId, targetNodeId) {
  856. let defaultData = {id: this.edgeBeingEditedId, from: sourceNodeId, to: targetNodeId};
  857. if (this.options.handlerFunctions.editEdge) {
  858. if (this.options.handlerFunctions.editEdge.length == 2) {
  859. this.options.handlerFunctions.editEdge(defaultData, (finalizedData) => {
  860. this.body.data.edges.update(finalizedData);
  861. this.selectionHandler.unselectAll();
  862. this.showManipulatorToolbar();
  863. });
  864. }
  865. else {
  866. throw new Error('The function for edit does not support two arguments (data, callback)');
  867. }
  868. }
  869. else {
  870. this.body.data.edges.update(defaultData);
  871. this.selectionHandler.unselectAll();
  872. this.showManipulatorToolbar();
  873. }
  874. }
  875. }
  876. export default ManipulationSystem;