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.

1125 lines
36 KiB

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