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.

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