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.

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