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.

1014 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. this._createWrappers();
  328. if (this.editMode === false) {
  329. this._createEditButton();
  330. }
  331. else {
  332. this.showManipulatorToolbar();
  333. }
  334. }
  335. else {
  336. this._removeManipulationDOM();
  337. // disable the gui
  338. this.guiEnabled = false;
  339. }
  340. }
  341. /**
  342. * create the div overlays that contain the DOM
  343. * @private
  344. */
  345. _createWrappers() {
  346. // load the manipulator HTML elements. All styling done in css.
  347. if (this.manipulationDiv === undefined) {
  348. this.manipulationDiv = document.createElement('div');
  349. this.manipulationDiv.className = 'vis-manipulation';
  350. if (this.editMode === true) {
  351. this.manipulationDiv.style.display = "block";
  352. }
  353. else {
  354. this.manipulationDiv.style.display = "none";
  355. }
  356. this.canvas.frame.appendChild(this.manipulationDiv);
  357. }
  358. // container for the edit button.
  359. if (this.editModeDiv === undefined) {
  360. this.editModeDiv = document.createElement('div');
  361. this.editModeDiv.className = 'vis-edit-mode';
  362. if (this.editMode === true) {
  363. this.editModeDiv.style.display = "none";
  364. }
  365. else {
  366. this.editModeDiv.style.display = "block";
  367. }
  368. this.canvas.frame.appendChild(this.editModeDiv);
  369. }
  370. // container for the close div button
  371. if (this.closeDiv === undefined) {
  372. this.closeDiv = document.createElement('div');
  373. this.closeDiv.className = 'vis-close';
  374. this.closeDiv.style.display = this.manipulationDiv.style.display;
  375. this.canvas.frame.appendChild(this.closeDiv);
  376. }
  377. }
  378. /**
  379. * generate a new target node. Used for creating new edges and editing edges
  380. * @param x
  381. * @param y
  382. * @returns {*}
  383. * @private
  384. */
  385. _getNewTargetNode(x,y) {
  386. let controlNodeStyle = util.deepExtend({}, this.options.controlNodeStyle);
  387. controlNodeStyle.id = 'targetNode' + util.randomUUID();
  388. controlNodeStyle.hidden = false;
  389. controlNodeStyle.physics = false;
  390. controlNodeStyle.x = x;
  391. controlNodeStyle.y = y;
  392. return this.body.functions.createNode(controlNodeStyle);
  393. }
  394. /**
  395. * Create the edit button
  396. */
  397. _createEditButton() {
  398. // restore everything to it's original state (if applicable)
  399. this._clean();
  400. // reset the manipulationDOM
  401. this.manipulationDOM = {};
  402. // empty the editModeDiv
  403. util.recursiveDOMDelete(this.editModeDiv);
  404. // create the contents for the editMode button
  405. let locale = this.options.locales[this.options.locale];
  406. let button = this._createButton('editMode', 'vis-button vis-edit vis-edit-mode', locale['edit']);
  407. this.editModeDiv.appendChild(button);
  408. // bind a hammer listener to the button, calling the function toggleEditMode.
  409. this._bindHammerToDiv(button, this.toggleEditMode.bind(this));
  410. }
  411. /**
  412. * this function cleans up after everything this module does. Temporary elements, functions and events are removed, physics restored, hammers removed.
  413. * @private
  414. */
  415. _clean() {
  416. // _clean the divs
  417. if (this.guiEnabled === true) {
  418. util.recursiveDOMDelete(this.editModeDiv);
  419. util.recursiveDOMDelete(this.manipulationDiv);
  420. // removes all the bindings and overloads
  421. this._cleanManipulatorHammers();
  422. }
  423. // remove temporary nodes and edges
  424. this._cleanupTemporaryNodesAndEdges();
  425. // restore overloaded UI functions
  426. this._unbindTemporaryUIs();
  427. // remove the temporaryEventFunctions
  428. this._unbindTemporaryEvents();
  429. // restore the physics if required
  430. this.body.emitter.emit("restorePhysics");
  431. }
  432. /**
  433. * Each dom element has it's own hammer. They are stored in this.manipulationHammers. This cleans them up.
  434. * @private
  435. */
  436. _cleanManipulatorHammers() {
  437. // _clean hammer bindings
  438. if (this.manipulationHammers.length != 0) {
  439. for (let i = 0; i < this.manipulationHammers.length; i++) {
  440. this.manipulationHammers[i].destroy();
  441. }
  442. this.manipulationHammers = [];
  443. }
  444. }
  445. /**
  446. * Remove all DOM elements created by this module.
  447. * @private
  448. */
  449. _removeManipulationDOM() {
  450. // removes all the bindings and overloads
  451. this._clean();
  452. // empty the manipulation divs
  453. util.recursiveDOMDelete(this.manipulationDiv);
  454. util.recursiveDOMDelete(this.editModeDiv);
  455. util.recursiveDOMDelete(this.closeDiv);
  456. // remove the manipulation divs
  457. this.canvas.frame.removeChild(this.manipulationDiv);
  458. this.canvas.frame.removeChild(this.editModeDiv);
  459. this.canvas.frame.removeChild(this.closeDiv);
  460. // set the references to undefined
  461. this.manipulationDiv = undefined;
  462. this.editModeDiv = undefined;
  463. this.closeDiv = undefined;
  464. }
  465. /**
  466. * create a seperator line. the index is to differentiate in the manipulation dom
  467. * @param index
  468. * @private
  469. */
  470. _createSeperator(index = 1) {
  471. this.manipulationDOM['seperatorLineDiv' + index] = document.createElement('div');
  472. this.manipulationDOM['seperatorLineDiv' + index].className = 'vis-separator-line';
  473. this.manipulationDiv.appendChild(this.manipulationDOM['seperatorLineDiv' + index]);
  474. }
  475. // ---------------------- DOM functions for buttons --------------------------//
  476. _createAddNodeButton(locale) {
  477. let button = this._createButton('addNode', 'vis-button vis-add', locale['addNode']);
  478. this.manipulationDiv.appendChild(button);
  479. this._bindHammerToDiv(button, this.addNodeMode.bind(this));
  480. }
  481. _createAddEdgeButton(locale) {
  482. let button = this._createButton('addEdge', 'vis-button vis-connect', locale['addEdge']);
  483. this.manipulationDiv.appendChild(button);
  484. this._bindHammerToDiv(button, this.addEdgeMode.bind(this));
  485. }
  486. _createEditNodeButton(locale) {
  487. let button = this._createButton('editNode', 'vis-button vis-edit', locale['editNode']);
  488. this.manipulationDiv.appendChild(button);
  489. this._bindHammerToDiv(button, this.editNode.bind(this));
  490. }
  491. _createEditEdgeButton(locale) {
  492. let button = this._createButton('editEdge', 'vis-button vis-edit', locale['editEdge']);
  493. this.manipulationDiv.appendChild(button);
  494. this._bindHammerToDiv(button, this.editEdgeMode.bind(this));
  495. }
  496. _createDeleteButton(locale) {
  497. let button = this._createButton('delete', 'vis-button vis-delete', locale['del']);
  498. this.manipulationDiv.appendChild(button);
  499. this._bindHammerToDiv(button, this.deleteSelected.bind(this));
  500. }
  501. _createBackButton(locale) {
  502. let button = this._createButton('back', 'vis-button vis-back', locale['back']);
  503. this.manipulationDiv.appendChild(button);
  504. this._bindHammerToDiv(button, this.showManipulatorToolbar.bind(this));
  505. }
  506. _createButton(id, className, label, labelClassName = 'vis-label') {
  507. this.manipulationDOM[id+"Div"] = document.createElement('div');
  508. this.manipulationDOM[id+"Div"].className = className;
  509. this.manipulationDOM[id+"Label"] = document.createElement('div');
  510. this.manipulationDOM[id+"Label"].className = labelClassName;
  511. this.manipulationDOM[id+"Label"].innerHTML = label;
  512. this.manipulationDOM[id+"Div"].appendChild(this.manipulationDOM[id+'Label']);
  513. return this.manipulationDOM[id+"Div"];
  514. }
  515. _createDescription(label) {
  516. this.manipulationDiv.appendChild(
  517. this._createButton('description', 'vis-button vis-none', label)
  518. );
  519. }
  520. // -------------------------- End of DOM functions for buttons ------------------------------//
  521. /**
  522. * this binds an event until cleanup by the clean functions.
  523. * @param event
  524. * @param newFunction
  525. * @private
  526. */
  527. _temporaryBindEvent(event, newFunction) {
  528. this.temporaryEventFunctions.push({event:event, boundFunction:newFunction});
  529. this.body.emitter.on(event, newFunction);
  530. }
  531. /**
  532. * this overrides an UI function until cleanup by the clean function
  533. * @param UIfunctionName
  534. * @param newFunction
  535. * @private
  536. */
  537. _temporaryBindUI(UIfunctionName, newFunction) {
  538. if (this.body.eventListeners[UIfunctionName] !== undefined) {
  539. this.temporaryUIFunctions[UIfunctionName] = this.body.eventListeners[UIfunctionName];
  540. this.body.eventListeners[UIfunctionName] = newFunction;
  541. }
  542. else {
  543. throw new Error('This UI function does not exist. Typo? You tried: "' + UIfunctionName + '" possible are: ' + JSON.stringify(Object.keys(this.body.eventListeners)));
  544. }
  545. }
  546. /**
  547. * Restore the overridden UI functions to their original state.
  548. *
  549. * @private
  550. */
  551. _unbindTemporaryUIs() {
  552. for (let functionName in this.temporaryUIFunctions) {
  553. if (this.temporaryUIFunctions.hasOwnProperty(functionName)) {
  554. this.body.eventListeners[functionName] = this.temporaryUIFunctions[functionName];
  555. delete this.temporaryUIFunctions[functionName];
  556. }
  557. }
  558. this.temporaryUIFunctions = {};
  559. }
  560. /**
  561. * Unbind the events created by _temporaryBindEvent
  562. * @private
  563. */
  564. _unbindTemporaryEvents() {
  565. for (let i = 0; i < this.temporaryEventFunctions.length; i++) {
  566. let eventName = this.temporaryEventFunctions[i].event;
  567. let boundFunction = this.temporaryEventFunctions[i].boundFunction;
  568. this.body.emitter.off(eventName, boundFunction);
  569. }
  570. this.temporaryEventFunctions = [];
  571. }
  572. /**
  573. * Bind an hammer instance to a DOM element.
  574. * @param domElement
  575. * @param funct
  576. */
  577. _bindHammerToDiv(domElement, boundFunction) {
  578. let hammer = new Hammer(domElement, {});
  579. hammerUtil.onTouch(hammer, boundFunction);
  580. this.manipulationHammers.push(hammer);
  581. }
  582. /**
  583. * Neatly clean up temporary edges and nodes
  584. * @private
  585. */
  586. _cleanupTemporaryNodesAndEdges() {
  587. // _clean temporary edges
  588. for (let i = 0; i < this.temporaryIds.edges.length; i++) {
  589. this.body.edges[this.temporaryIds.edges[i]].disconnect();
  590. delete this.body.edges[this.temporaryIds.edges[i]];
  591. let indexTempEdge = this.body.edgeIndices.indexOf(this.temporaryIds.edges[i]);
  592. if (indexTempEdge !== -1) {this.body.edgeIndices.splice(indexTempEdge,1);}
  593. }
  594. // _clean temporary nodes
  595. for (let i = 0; i < this.temporaryIds.nodes.length; i++) {
  596. delete this.body.nodes[this.temporaryIds.nodes[i]];
  597. let indexTempNode = this.body.nodeIndices.indexOf(this.temporaryIds.nodes[i]);
  598. if (indexTempNode !== -1) {this.body.nodeIndices.splice(indexTempNode,1);}
  599. }
  600. this.temporaryIds = {nodes: [], edges: []};
  601. }
  602. // ------------------------------------------ EDIT EDGE FUNCTIONS -----------------------------------------//
  603. /**
  604. * the touch is used to get the position of the initial click
  605. * @param event
  606. * @private
  607. */
  608. _controlNodeTouch(event) {
  609. this.lastTouch = this.body.functions.getPointer(event.center);
  610. this.lastTouch.translation = util.extend({},this.body.view.translation); // copy the object
  611. }
  612. /**
  613. * the drag start is used to mark one of the control nodes as selected.
  614. * @param event
  615. * @private
  616. */
  617. _controlNodeDragStart(event) {
  618. let pointer = this.lastTouch;
  619. let pointerObj = this.selectionHandler._pointerToPositionObject(pointer);
  620. let from = this.body.nodes[this.temporaryIds.nodes[0]];
  621. let to = this.body.nodes[this.temporaryIds.nodes[1]];
  622. let edge = this.body.edges[this.edgeBeingEditedId];
  623. this.selectedControlNode = undefined;
  624. let fromSelect = from.isOverlappingWith(pointerObj);
  625. let toSelect = to.isOverlappingWith(pointerObj);
  626. if (fromSelect === true) {
  627. this.selectedControlNode = from;
  628. edge.edgeType.from = from;
  629. }
  630. else if (toSelect === true) {
  631. this.selectedControlNode = to;
  632. edge.edgeType.to = to;
  633. }
  634. this.body.emitter.emit("_redraw");
  635. }
  636. /**
  637. * dragging the control nodes or the canvas
  638. * @param event
  639. * @private
  640. */
  641. _controlNodeDrag(event) {
  642. this.body.emitter.emit("disablePhysics");
  643. let pointer = this.body.functions.getPointer(event.center);
  644. let pos = this.canvas.DOMtoCanvas(pointer);
  645. if (this.selectedControlNode !== undefined) {
  646. this.selectedControlNode.x = pos.x;
  647. this.selectedControlNode.y = pos.y;
  648. }
  649. else {
  650. // if the drag was not started properly because the click started outside the network div, start it now.
  651. let diffX = pointer.x - this.lastTouch.x;
  652. let diffY = pointer.y - this.lastTouch.y;
  653. this.body.view.translation = {x:this.lastTouch.translation.x + diffX, y:this.lastTouch.translation.y + diffY};
  654. }
  655. this.body.emitter.emit("_redraw");
  656. }
  657. /**
  658. * connecting or restoring the control nodes.
  659. * @param event
  660. * @private
  661. */
  662. _controlNodeDragEnd(event) {
  663. let pointer = this.body.functions.getPointer(event.center);
  664. let pointerObj = this.selectionHandler._pointerToPositionObject(pointer);
  665. let edge = this.body.edges[this.edgeBeingEditedId];
  666. let overlappingNodeIds = this.selectionHandler._getAllNodesOverlappingWith(pointerObj);
  667. let node = undefined;
  668. for (let i = overlappingNodeIds.length-1; i >= 0; i--) {
  669. if (overlappingNodeIds[i] !== this.selectedControlNode.id) {
  670. node = this.body.nodes[overlappingNodeIds[i]];
  671. break;
  672. }
  673. }
  674. // perform the connection
  675. if (node !== undefined && this.selectedControlNode !== undefined) {
  676. if (node.isCluster === true) {
  677. alert(this.options.locales[this.options.locale]["createEdgeError"])
  678. }
  679. else {
  680. let from = this.body.nodes[this.temporaryIds.nodes[0]];
  681. if (this.selectedControlNode.id === from.id) {
  682. this._performEditEdge(node.id, edge.to.id);
  683. }
  684. else {
  685. this._performEditEdge(edge.from.id, node.id);
  686. }
  687. }
  688. }
  689. else {
  690. edge.updateEdgeType();
  691. this.body.emitter.emit("restorePhysics");
  692. }
  693. this.body.emitter.emit("_redraw");
  694. }
  695. // ------------------------------------ END OF EDIT EDGE FUNCTIONS -----------------------------------------//
  696. // ------------------------------------------- ADD EDGE FUNCTIONS -----------------------------------------//
  697. /**
  698. * the function bound to the selection event. It checks if you want to connect a cluster and changes the description
  699. * to walk the user through the process.
  700. *
  701. * @private
  702. */
  703. _handleConnect(event) {
  704. // check to avoid double fireing of this function.
  705. if (new Date().valueOf() - this.touchTime > 100) {
  706. let pointer = this.body.functions.getPointer(event.center);
  707. let node = this.selectionHandler.getNodeAt(pointer);
  708. if (node !== undefined) {
  709. if (node.isCluster === true) {
  710. alert(this.options.locales[this.options.locale]['createEdgeError'])
  711. }
  712. else {
  713. // create a node the temporary line can look at
  714. let targetNode = this._getNewTargetNode(node.x,node.y);
  715. let targetNodeId = targetNode.id;
  716. this.body.nodes[targetNode.id] = targetNode;
  717. this.body.nodeIndices.push(targetNode.id);
  718. // create a temporary edge
  719. let connectionEdge = this.body.functions.createEdge({
  720. id: "connectionEdge" + util.randomUUID(),
  721. from: node.id,
  722. to: targetNode.id,
  723. physics:false,
  724. smooth: {
  725. enabled: true,
  726. dynamic: false,
  727. type: "continuous",
  728. roundness: 0.5
  729. }
  730. });
  731. this.body.edges[connectionEdge.id] = connectionEdge;
  732. this.body.edgeIndices.push(connectionEdge.id);
  733. this.temporaryIds.nodes.push(targetNode.id);
  734. this.temporaryIds.edges.push(connectionEdge.id);
  735. this.temporaryUIFunctions["onDrag"] = this.body.eventListeners.onDrag;
  736. this.body.eventListeners.onDrag = (event) => {
  737. let pointer = this.body.functions.getPointer(event.center);
  738. let targetNode = this.body.nodes[targetNodeId];
  739. targetNode.x = this.canvas._XconvertDOMtoCanvas(pointer.x);
  740. targetNode.y = this.canvas._YconvertDOMtoCanvas(pointer.y);
  741. this.body.emitter.emit("_redraw");
  742. }
  743. }
  744. }
  745. this.touchTime = new Date().valueOf();
  746. // do the original touch events
  747. this.temporaryUIFunctions["onTouch"](event);
  748. }
  749. }
  750. /**
  751. * Connect the new edge to the target if one exists, otherwise remove temp line
  752. * @param event
  753. * @private
  754. */
  755. _finishConnect(event) {
  756. let pointer = this.body.functions.getPointer(event.center);
  757. let pointerObj = this.selectionHandler._pointerToPositionObject(pointer);
  758. // remember the edge id
  759. let connectFromId = undefined;
  760. if (this.temporaryIds.edges[0] !== undefined) {
  761. connectFromId = this.body.edges[this.temporaryIds.edges[0]].fromId;
  762. }
  763. //restore the drag function
  764. if (this.temporaryUIFunctions["onDrag"] !== undefined) {
  765. this.body.eventListeners.onDrag = this.temporaryUIFunctions["onDrag"];
  766. delete this.temporaryUIFunctions["onDrag"];
  767. }
  768. // get the overlapping node but NOT the temporary node;
  769. let overlappingNodeIds = this.selectionHandler._getAllNodesOverlappingWith(pointerObj);
  770. let node = undefined;
  771. for (let i = overlappingNodeIds.length-1; i >= 0; i--) {
  772. if (this.temporaryIds.nodes.indexOf(overlappingNodeIds[i]) !== -1) {
  773. node = this.body.nodes[overlappingNodeIds[i]];
  774. break;
  775. }
  776. }
  777. // clean temporary nodes and edges.
  778. this._cleanupTemporaryNodesAndEdges();
  779. // perform the connection
  780. if (node !== undefined) {
  781. if (node.isCluster === true) {
  782. alert(this.options.locales[this.options.locale]["createEdgeError"]);
  783. }
  784. else {
  785. if (this.body.nodes[connectFromId] !== undefined && this.body.nodes[node.id] !== undefined) {
  786. this._performCreateEdge(connectFromId, node.id);
  787. }
  788. }
  789. }
  790. this.body.emitter.emit("_redraw");
  791. }
  792. // --------------------------------------- END OF ADD EDGE FUNCTIONS -------------------------------------//
  793. // ------------------------------ Performing all the actual data manipulation ------------------------//
  794. /**
  795. * Adds a node on the specified location
  796. */
  797. _performAddNode(clickData) {
  798. let defaultData = {
  799. id: util.randomUUID(),
  800. x: clickData.pointer.canvas.x,
  801. y: clickData.pointer.canvas.y,
  802. label: "new"
  803. };
  804. if (typeof this.options.handlerFunctions.addNode === 'function') {
  805. if (this.options.handlerFunctions.addNode.length === 2) {
  806. this.options.handlerFunctions.addNode(defaultData, (finalizedData) => {
  807. this.body.data.nodes.add(finalizedData);
  808. this.showManipulatorToolbar();
  809. });
  810. }
  811. else {
  812. throw new Error('The function for add does not support two arguments (data,callback)');
  813. this.showManipulatorToolbar();
  814. }
  815. }
  816. else {
  817. this.body.data.nodes.add(defaultData);
  818. this.showManipulatorToolbar();
  819. }
  820. }
  821. /**
  822. * connect two nodes with a new edge.
  823. *
  824. * @private
  825. */
  826. _performCreateEdge(sourceNodeId, targetNodeId) {
  827. let defaultData = {from: sourceNodeId, to: targetNodeId};
  828. if (this.options.handlerFunctions.addEdge) {
  829. if (this.options.handlerFunctions.addEdge.length === 2) {
  830. this.options.handlerFunctions.addEdge(defaultData, (finalizedData) => {
  831. this.body.data.edges.add(finalizedData);
  832. this.selectionHandler.unselectAll();
  833. this.showManipulatorToolbar();
  834. });
  835. }
  836. else {
  837. throw new Error('The function for connect does not support two arguments (data,callback)');
  838. }
  839. }
  840. else {
  841. this.body.data.edges.add(defaultData);
  842. this.selectionHandler.unselectAll();
  843. this.showManipulatorToolbar();
  844. }
  845. }
  846. /**
  847. * connect two nodes with a new edge.
  848. *
  849. * @private
  850. */
  851. _performEditEdge(sourceNodeId, targetNodeId) {
  852. let defaultData = {id: this.edgeBeingEditedId, from: sourceNodeId, to: targetNodeId};
  853. if (this.options.handlerFunctions.editEdge) {
  854. if (this.options.handlerFunctions.editEdge.length === 2) {
  855. this.options.handlerFunctions.editEdge(defaultData, (finalizedData) => {
  856. this.body.data.edges.update(finalizedData);
  857. this.selectionHandler.unselectAll();
  858. this.showManipulatorToolbar();
  859. });
  860. }
  861. else {
  862. throw new Error('The function for edit does not support two arguments (data, callback)');
  863. }
  864. }
  865. else {
  866. this.body.data.edges.update(defaultData);
  867. this.selectionHandler.unselectAll();
  868. this.showManipulatorToolbar();
  869. }
  870. }
  871. }
  872. export default ManipulationSystem;