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.

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