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.

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