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.

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