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.

690 lines
22 KiB

9 years ago
  1. let util = require('../../util');
  2. import NavigationHandler from './components/NavigationHandler'
  3. import Popup from './components/Popup'
  4. class InteractionHandler {
  5. constructor(body, canvas, selectionHandler) {
  6. this.body = body;
  7. this.canvas = canvas;
  8. this.selectionHandler = selectionHandler;
  9. this.navigationHandler = new NavigationHandler(body,canvas);
  10. // bind the events from hammer to functions in this object
  11. this.body.eventListeners.onTap = this.onTap.bind(this);
  12. this.body.eventListeners.onTouch = this.onTouch.bind(this);
  13. this.body.eventListeners.onDoubleTap = this.onDoubleTap.bind(this);
  14. this.body.eventListeners.onHold = this.onHold.bind(this);
  15. this.body.eventListeners.onDragStart = this.onDragStart.bind(this);
  16. this.body.eventListeners.onDrag = this.onDrag.bind(this);
  17. this.body.eventListeners.onDragEnd = this.onDragEnd.bind(this);
  18. this.body.eventListeners.onMouseWheel = this.onMouseWheel.bind(this);
  19. this.body.eventListeners.onPinch = this.onPinch.bind(this);
  20. this.body.eventListeners.onMouseMove = this.onMouseMove.bind(this);
  21. this.body.eventListeners.onRelease = this.onRelease.bind(this);
  22. this.body.eventListeners.onContext = this.onContext.bind(this);
  23. this.touchTime = 0;
  24. this.drag = {};
  25. this.pinch = {};
  26. this.popup = undefined;
  27. this.popupObj = undefined;
  28. this.popupTimer = undefined;
  29. this.body.functions.getPointer = this.getPointer.bind(this);
  30. this.options = {};
  31. this.defaultOptions = {
  32. dragNodes:true,
  33. dragView: true,
  34. hover: false,
  35. keyboard: {
  36. enabled: false,
  37. speed: {x: 10, y: 10, zoom: 0.02},
  38. bindToWindow: true
  39. },
  40. navigationButtons: false,
  41. tooltipDelay: 300,
  42. zoomView: true
  43. };
  44. util.extend(this.options,this.defaultOptions);
  45. this.bindEventListeners()
  46. }
  47. bindEventListeners() {
  48. this.body.emitter.on('destroy', () => {
  49. clearTimeout(this.popupTimer);
  50. delete this.body.functions.getPointer;
  51. })
  52. }
  53. setOptions(options) {
  54. if (options !== undefined) {
  55. // extend all but the values in fields
  56. let fields = ['hideEdgesOnDrag','hideNodesOnDrag','keyboard','multiselect','selectable','selectConnectedEdges'];
  57. util.selectiveNotDeepExtend(fields, this.options, options);
  58. // merge the keyboard options in.
  59. util.mergeOptions(this.options, options, 'keyboard');
  60. if (options.tooltip) {
  61. util.extend(this.options.tooltip, options.tooltip);
  62. if (options.tooltip.color) {
  63. this.options.tooltip.color = util.parseColor(options.tooltip.color);
  64. }
  65. }
  66. }
  67. this.navigationHandler.setOptions(this.options);
  68. }
  69. /**
  70. * Get the pointer location from a touch location
  71. * @param {{x: Number, y: Number}} touch
  72. * @return {{x: Number, y: Number}} pointer
  73. * @private
  74. */
  75. getPointer(touch) {
  76. return {
  77. x: touch.x - util.getAbsoluteLeft(this.canvas.frame.canvas),
  78. y: touch.y - util.getAbsoluteTop(this.canvas.frame.canvas)
  79. };
  80. }
  81. /**
  82. * On start of a touch gesture, store the pointer
  83. * @param event
  84. * @private
  85. */
  86. onTouch(event) {
  87. if (new Date().valueOf() - this.touchTime > 50) {
  88. this.drag.pointer = this.getPointer(event.center);
  89. this.drag.pinched = false;
  90. this.pinch.scale = this.body.view.scale;
  91. // to avoid double fireing of this event because we have two hammer instances. (on canvas and on frame)
  92. this.touchTime = new Date().valueOf();
  93. }
  94. }
  95. /**
  96. * handle tap/click event: select/unselect a node
  97. * @private
  98. */
  99. onTap(event) {
  100. let pointer = this.getPointer(event.center);
  101. let multiselect = this.selectionHandler.options.multiselect && event.changedPointers[0].ctrlKey;
  102. this.checkSelectionChanges(pointer, event, multiselect);
  103. this.selectionHandler._generateClickEvent('click', event, pointer);
  104. }
  105. /**
  106. * handle doubletap event
  107. * @private
  108. */
  109. onDoubleTap(event) {
  110. let pointer = this.getPointer(event.center);
  111. this.selectionHandler._generateClickEvent('doubleClick', event, pointer);
  112. }
  113. /**
  114. * handle long tap event: multi select nodes
  115. * @private
  116. */
  117. onHold(event) {
  118. let pointer = this.getPointer(event.center);
  119. let multiselect = this.selectionHandler.options.multiselect;
  120. this.checkSelectionChanges(pointer, event, multiselect);
  121. this.selectionHandler._generateClickEvent('click', event, pointer);
  122. this.selectionHandler._generateClickEvent('hold', event, pointer);
  123. }
  124. /**
  125. * handle the release of the screen
  126. *
  127. * @private
  128. */
  129. onRelease(event) {
  130. if (new Date().valueOf() - this.touchTime > 10) {
  131. let pointer = this.getPointer(event.center);
  132. this.selectionHandler._generateClickEvent('release', event, pointer);
  133. // to avoid double fireing of this event because we have two hammer instances. (on canvas and on frame)
  134. this.touchTime = new Date().valueOf();
  135. }
  136. }
  137. onContext(event) {
  138. let pointer = this.getPointer({x:event.clientX, y:event.clientY});
  139. this.selectionHandler._generateClickEvent('oncontext', event, pointer);
  140. }
  141. /**
  142. *
  143. * @param pointer
  144. * @param add
  145. */
  146. checkSelectionChanges(pointer, event, add = false) {
  147. let previouslySelectedEdgeCount = this.selectionHandler._getSelectedEdgeCount();
  148. let previouslySelectedNodeCount = this.selectionHandler._getSelectedNodeCount();
  149. let previousSelection = this.selectionHandler.getSelection();
  150. let selected;
  151. if (add === true) {
  152. selected = this.selectionHandler.selectAdditionalOnPoint(pointer);
  153. }
  154. else {
  155. selected = this.selectionHandler.selectOnPoint(pointer);
  156. }
  157. let selectedEdgesCount = this.selectionHandler._getSelectedEdgeCount();
  158. let selectedNodesCount = this.selectionHandler._getSelectedNodeCount();
  159. let currentSelection = this.selectionHandler.getSelection();
  160. let {nodesChanges, edgesChanges} = this._determineIfDifferent(previousSelection, currentSelection);
  161. if (selectedNodesCount - previouslySelectedNodeCount > 0 || (selectedNodesCount === previouslySelectedNodeCount && nodesChanges === true)) { // node was selected
  162. this.selectionHandler._generateClickEvent('selectNode', event, pointer);
  163. selected = true;
  164. }
  165. else if (selectedNodesCount - previouslySelectedNodeCount < 0) { // node was deselected
  166. this.selectionHandler._generateClickEvent('deselectNode', event, pointer, previousSelection);
  167. selected = true;
  168. }
  169. if (selectedEdgesCount - previouslySelectedEdgeCount > 0|| (selectedEdgesCount === previouslySelectedEdgeCount && edgesChanges === true)) { // node was selected
  170. this.selectionHandler._generateClickEvent('selectEdge', event, pointer);
  171. selected = true;
  172. }
  173. else if (selectedEdgesCount - previouslySelectedEdgeCount < 0) { // node was deselected
  174. this.selectionHandler._generateClickEvent('deselectEdge', event, pointer, previousSelection);
  175. selected = true;
  176. }
  177. if (selected === true) { // select or unselect
  178. this.selectionHandler._generateClickEvent('select', event, pointer);
  179. }
  180. }
  181. /**
  182. * This function checks if the nodes and edges previously selected have changed.
  183. * @param previousSelection
  184. * @param currentSelection
  185. * @returns {{nodesChanges: boolean, edgesChanges: boolean}}
  186. * @private
  187. */
  188. _determineIfDifferent(previousSelection,currentSelection) {
  189. let nodesChanges = false;
  190. let edgesChanges = false;
  191. for (let i = 0; i < previousSelection.nodes.length; i++) {
  192. if (currentSelection.nodes.indexOf(previousSelection.nodes[i]) === -1) {
  193. nodesChanges = true;
  194. }
  195. }
  196. for (let i = 0; i < currentSelection.nodes.length; i++) {
  197. if (previousSelection.nodes.indexOf(previousSelection.nodes[i]) === -1) {
  198. nodesChanges = true;
  199. }
  200. }
  201. for (let i = 0; i < previousSelection.edges.length; i++) {
  202. if (currentSelection.edges.indexOf(previousSelection.edges[i]) === -1) {
  203. edgesChanges = true;
  204. }
  205. }
  206. for (let i = 0; i < currentSelection.edges.length; i++) {
  207. if (previousSelection.edges.indexOf(previousSelection.edges[i]) === -1) {
  208. edgesChanges = true;
  209. }
  210. }
  211. return {nodesChanges, edgesChanges};
  212. }
  213. /**
  214. * This function is called by onDragStart.
  215. * It is separated out because we can then overload it for the datamanipulation system.
  216. *
  217. * @private
  218. */
  219. onDragStart(event) {
  220. //in case the touch event was triggered on an external div, do the initial touch now.
  221. if (this.drag.pointer === undefined) {
  222. this.onTouch(event);
  223. }
  224. // note: drag.pointer is set in onTouch to get the initial touch location
  225. let node = this.selectionHandler.getNodeAt(this.drag.pointer);
  226. this.drag.dragging = true;
  227. this.drag.selection = [];
  228. this.drag.translation = util.extend({},this.body.view.translation); // copy the object
  229. this.drag.nodeId = undefined;
  230. this.selectionHandler._generateClickEvent('dragStart', event, this.drag.pointer);
  231. if (node !== undefined && this.options.dragNodes === true) {
  232. this.drag.nodeId = node.id;
  233. // select the clicked node if not yet selected
  234. if (node.isSelected() === false) {
  235. this.selectionHandler.unselectAll();
  236. this.selectionHandler.selectObject(node);
  237. }
  238. let selection = this.selectionHandler.selectionObj.nodes;
  239. // create an array with the selected nodes and their original location and status
  240. for (let nodeId in selection) {
  241. if (selection.hasOwnProperty(nodeId)) {
  242. let object = selection[nodeId];
  243. let s = {
  244. id: object.id,
  245. node: object,
  246. // store original x, y, xFixed and yFixed, make the node temporarily Fixed
  247. x: object.x,
  248. y: object.y,
  249. xFixed: object.options.fixed.x,
  250. yFixed: object.options.fixed.y
  251. };
  252. object.options.fixed.x = true;
  253. object.options.fixed.y = true;
  254. this.drag.selection.push(s);
  255. }
  256. }
  257. }
  258. }
  259. /**
  260. * handle drag event
  261. * @private
  262. */
  263. onDrag(event) {
  264. if (this.drag.pinched === true) {
  265. return;
  266. }
  267. // remove the focus on node if it is focussed on by the focusOnNode
  268. this.body.emitter.emit('unlockNode');
  269. let pointer = this.getPointer(event.center);
  270. this.selectionHandler._generateClickEvent('dragging', event, pointer);
  271. let selection = this.drag.selection;
  272. if (selection && selection.length && this.options.dragNodes === true) {
  273. // calculate delta's and new location
  274. let deltaX = pointer.x - this.drag.pointer.x;
  275. let deltaY = pointer.y - this.drag.pointer.y;
  276. // update position of all selected nodes
  277. selection.forEach((selection) => {
  278. let node = selection.node;
  279. // only move the node if it was not fixed initially
  280. if (selection.xFixed === false) {
  281. node.x = this.canvas._XconvertDOMtoCanvas(this.canvas._XconvertCanvasToDOM(selection.x) + deltaX);
  282. }
  283. // only move the node if it was not fixed initially
  284. if (selection.yFixed === false) {
  285. node.y = this.canvas._YconvertDOMtoCanvas(this.canvas._YconvertCanvasToDOM(selection.y) + deltaY);
  286. }
  287. });
  288. // start the simulation of the physics
  289. this.body.emitter.emit('startSimulation');
  290. }
  291. else {
  292. // move the network
  293. if (this.options.dragView === true) {
  294. // if the drag was not started properly because the click started outside the network div, start it now.
  295. if (this.drag.pointer === undefined) {
  296. this._handleDragStart(event);
  297. return;
  298. }
  299. let diffX = pointer.x - this.drag.pointer.x;
  300. let diffY = pointer.y - this.drag.pointer.y;
  301. this.body.view.translation = {x:this.drag.translation.x + diffX, y:this.drag.translation.y + diffY};
  302. this.body.emitter.emit('_redraw');
  303. }
  304. }
  305. }
  306. /**
  307. * handle drag start event
  308. * @private
  309. */
  310. onDragEnd(event) {
  311. this.drag.dragging = false;
  312. let selection = this.drag.selection;
  313. if (selection && selection.length) {
  314. selection.forEach(function (s) {
  315. // restore original xFixed and yFixed
  316. s.node.options.fixed.x = s.xFixed;
  317. s.node.options.fixed.y = s.yFixed;
  318. });
  319. this.body.emitter.emit('startSimulation');
  320. }
  321. else {
  322. this.body.emitter.emit('_requestRedraw');
  323. }
  324. this.selectionHandler._generateClickEvent('dragEnd', event, this.getPointer(event.center));
  325. }
  326. /**
  327. * Handle pinch event
  328. * @param event
  329. * @private
  330. */
  331. onPinch(event) {
  332. let pointer = this.getPointer(event.center);
  333. this.drag.pinched = true;
  334. if (this.pinch['scale'] === undefined) {
  335. this.pinch.scale = 1;
  336. }
  337. // TODO: enabled moving while pinching?
  338. let scale = this.pinch.scale * event.scale;
  339. this.zoom(scale, pointer)
  340. }
  341. /**
  342. * Zoom the network in or out
  343. * @param {Number} scale a number around 1, and between 0.01 and 10
  344. * @param {{x: Number, y: Number}} pointer Position on screen
  345. * @return {Number} appliedScale scale is limited within the boundaries
  346. * @private
  347. */
  348. zoom(scale, pointer) {
  349. if (this.options.zoomView === true) {
  350. let scaleOld = this.body.view.scale;
  351. if (scale < 0.00001) {
  352. scale = 0.00001;
  353. }
  354. if (scale > 10) {
  355. scale = 10;
  356. }
  357. let preScaleDragPointer = undefined;
  358. if (this.drag !== undefined) {
  359. if (this.drag.dragging === true) {
  360. preScaleDragPointer = this.canvas.DOMtoCanvas(this.drag.pointer);
  361. }
  362. }
  363. // + this.canvas.frame.canvas.clientHeight / 2
  364. let translation = this.body.view.translation;
  365. let scaleFrac = scale / scaleOld;
  366. let tx = (1 - scaleFrac) * pointer.x + translation.x * scaleFrac;
  367. let ty = (1 - scaleFrac) * pointer.y + translation.y * scaleFrac;
  368. this.body.view.scale = scale;
  369. this.body.view.translation = {x:tx, y:ty};
  370. if (preScaleDragPointer != undefined) {
  371. let postScaleDragPointer = this.canvas.canvasToDOM(preScaleDragPointer);
  372. this.drag.pointer.x = postScaleDragPointer.x;
  373. this.drag.pointer.y = postScaleDragPointer.y;
  374. }
  375. this.body.emitter.emit('_requestRedraw');
  376. if (scaleOld < scale) {
  377. this.body.emitter.emit('zoom', {direction: '+', scale: this.body.view.scale});
  378. }
  379. else {
  380. this.body.emitter.emit('zoom', {direction: '-', scale: this.body.view.scale});
  381. }
  382. }
  383. }
  384. /**
  385. * Event handler for mouse wheel event, used to zoom the timeline
  386. * See http://adomas.org/javascript-mouse-wheel/
  387. * https://github.com/EightMedia/hammer.js/issues/256
  388. * @param {MouseEvent} event
  389. * @private
  390. */
  391. onMouseWheel(event) {
  392. // retrieve delta
  393. let delta = 0;
  394. if (event.wheelDelta) { /* IE/Opera. */
  395. delta = event.wheelDelta / 120;
  396. } else if (event.detail) { /* Mozilla case. */
  397. // In Mozilla, sign of delta is different than in IE.
  398. // Also, delta is multiple of 3.
  399. delta = -event.detail / 3;
  400. }
  401. // If delta is nonzero, handle it.
  402. // Basically, delta is now positive if wheel was scrolled up,
  403. // and negative, if wheel was scrolled down.
  404. if (delta !== 0) {
  405. // calculate the new scale
  406. let scale = this.body.view.scale;
  407. let zoom = delta / 10;
  408. if (delta < 0) {
  409. zoom = zoom / (1 - zoom);
  410. }
  411. scale *= (1 + zoom);
  412. // calculate the pointer location
  413. let pointer = this.getPointer({x:event.clientX, y:event.clientY});
  414. // apply the new scale
  415. this.zoom(scale, pointer);
  416. }
  417. // Prevent default actions caused by mouse wheel.
  418. event.preventDefault();
  419. }
  420. /**
  421. * Mouse move handler for checking whether the title moves over a node with a title.
  422. * @param {Event} event
  423. * @private
  424. */
  425. onMouseMove(event) {
  426. let pointer = this.getPointer({x:event.clientX, y:event.clientY});
  427. let popupVisible = false;
  428. // check if the previously selected node is still selected
  429. if (this.popup !== undefined) {
  430. if (this.popup.hidden === false) {
  431. this._checkHidePopup(pointer);
  432. }
  433. // if the popup was not hidden above
  434. if (this.popup.hidden === false) {
  435. popupVisible = true;
  436. this.popup.setPosition(pointer.x + 3, pointer.y - 5);
  437. this.popup.show();
  438. }
  439. }
  440. // if we bind the keyboard to the div, we have to highlight it to use it. This highlights it on mouse over.
  441. if (this.options.keyboard.bindToWindow === false && this.options.keyboard.enabled === true) {
  442. this.canvas.frame.focus();
  443. }
  444. // start a timeout that will check if the mouse is positioned above an element
  445. if (popupVisible === false) {
  446. if (this.popupTimer !== undefined) {
  447. clearInterval(this.popupTimer); // stop any running calculationTimer
  448. this.popupTimer = undefined;
  449. }
  450. if (!this.drag.dragging) {
  451. this.popupTimer = setTimeout(() => this._checkShowPopup(pointer), this.options.tooltipDelay);
  452. }
  453. }
  454. /**
  455. * Adding hover highlights
  456. */
  457. if (this.options.hover === true) {
  458. // adding hover highlights
  459. let obj = this.selectionHandler.getNodeAt(pointer);
  460. if (obj === undefined) {
  461. obj = this.selectionHandler.getEdgeAt(pointer);
  462. }
  463. this.selectionHandler.hoverObject(obj);
  464. }
  465. }
  466. /**
  467. * Check if there is an element on the given position in the network
  468. * (a node or edge). If so, and if this element has a title,
  469. * show a popup window with its title.
  470. *
  471. * @param {{x:Number, y:Number}} pointer
  472. * @private
  473. */
  474. _checkShowPopup(pointer) {
  475. let x = this.canvas._XconvertDOMtoCanvas(pointer.x);
  476. let y = this.canvas._YconvertDOMtoCanvas(pointer.y);
  477. let pointerObj = {
  478. left: x,
  479. top: y,
  480. right: x,
  481. bottom: y
  482. };
  483. let previousPopupObjId = this.popupObj === undefined ? undefined : this.popupObj.id;
  484. let nodeUnderCursor = false;
  485. let popupType = 'node';
  486. // check if a node is under the cursor.
  487. if (this.popupObj === undefined) {
  488. // search the nodes for overlap, select the top one in case of multiple nodes
  489. let nodeIndices = this.body.nodeIndices;
  490. let nodes = this.body.nodes;
  491. let node;
  492. let overlappingNodes = [];
  493. for (let i = 0; i < nodeIndices.length; i++) {
  494. node = nodes[nodeIndices[i]];
  495. if (node.isOverlappingWith(pointerObj) === true) {
  496. if (node.getTitle() !== undefined) {
  497. overlappingNodes.push(nodeIndices[i]);
  498. }
  499. }
  500. }
  501. if (overlappingNodes.length > 0) {
  502. // if there are overlapping nodes, select the last one, this is the one which is drawn on top of the others
  503. this.popupObj = nodes[overlappingNodes[overlappingNodes.length - 1]];
  504. // if you hover over a node, the title of the edge is not supposed to be shown.
  505. nodeUnderCursor = true;
  506. }
  507. }
  508. if (this.popupObj === undefined && nodeUnderCursor === false) {
  509. // search the edges for overlap
  510. let edgeIndices = this.body.edgeIndices;
  511. let edges = this.body.edges;
  512. let edge;
  513. let overlappingEdges = [];
  514. for (let i = 0; i < edgeIndices.length; i++) {
  515. edge = edges[edgeIndices[i]];
  516. if (edge.isOverlappingWith(pointerObj) === true) {
  517. if (edge.connected === true && edge.getTitle() !== undefined) {
  518. overlappingEdges.push(edgeIndices[i]);
  519. }
  520. }
  521. }
  522. if (overlappingEdges.length > 0) {
  523. this.popupObj = edges[overlappingEdges[overlappingEdges.length - 1]];
  524. popupType = 'edge';
  525. }
  526. }
  527. if (this.popupObj !== undefined) {
  528. // show popup message window
  529. if (this.popupObj.id !== previousPopupObjId) {
  530. if (this.popup === undefined) {
  531. this.popup = new Popup(this.canvas.frame);
  532. }
  533. this.popup.popupTargetType = popupType;
  534. this.popup.popupTargetId = this.popupObj.id;
  535. // adjust a small offset such that the mouse cursor is located in the
  536. // bottom left location of the popup, and you can easily move over the
  537. // popup area
  538. this.popup.setPosition(pointer.x + 3, pointer.y - 5);
  539. this.popup.setText(this.popupObj.getTitle());
  540. this.popup.show();
  541. this.body.emitter.emit('showPopup',this.popupObj.id);
  542. }
  543. }
  544. else {
  545. if (this.popup !== undefined) {
  546. this.popup.hide();
  547. this.body.emitter.emit('hidePopup');
  548. }
  549. }
  550. }
  551. /**
  552. * Check if the popup must be hidden, which is the case when the mouse is no
  553. * longer hovering on the object
  554. * @param {{x:Number, y:Number}} pointer
  555. * @private
  556. */
  557. _checkHidePopup(pointer) {
  558. let pointerObj = this.selectionHandler._pointerToPositionObject(pointer);
  559. let stillOnObj = false;
  560. if (this.popup.popupTargetType === 'node') {
  561. if (this.body.nodes[this.popup.popupTargetId] !== undefined) {
  562. stillOnObj = this.body.nodes[this.popup.popupTargetId].isOverlappingWith(pointerObj);
  563. // if the mouse is still one the node, we have to check if it is not also on one that is drawn on top of it.
  564. // we initially only check stillOnObj because this is much faster.
  565. if (stillOnObj === true) {
  566. let overNode = this.selectionHandler.getNodeAt(pointer);
  567. stillOnObj = overNode.id === this.popup.popupTargetId;
  568. }
  569. }
  570. }
  571. else {
  572. if (this.selectionHandler.getNodeAt(pointer) === undefined) {
  573. if (this.body.edges[this.popup.popupTargetId] !== undefined) {
  574. stillOnObj = this.body.edges[this.popup.popupTargetId].isOverlappingWith(pointerObj);
  575. }
  576. }
  577. }
  578. if (stillOnObj === false) {
  579. this.popupObj = undefined;
  580. this.popup.hide();
  581. this.body.emitter.emit('hidePopup');
  582. }
  583. }
  584. }
  585. export default InteractionHandler;