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.

651 lines
20 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.pageX, y:event.pageY});
  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 selectedEdges = this.selectionHandler._getSelectedEdgeCount();
  158. let selectedNodes = this.selectionHandler._getSelectedNodeCount();
  159. if (selectedNodes - previouslySelectedNodeCount > 0) { // node was selected
  160. this.selectionHandler._generateClickEvent('selectNode', event, pointer);
  161. selected = true;
  162. }
  163. else if (selectedNodes - previouslySelectedNodeCount < 0) { // node was deselected
  164. this.selectionHandler._generateClickEvent('deselectNode', event, pointer, previousSelection);
  165. selected = true;
  166. }
  167. if (selectedEdges - previouslySelectedEdgeCount > 0) { // node was selected
  168. this.selectionHandler._generateClickEvent('selectEdge', event, pointer);
  169. selected = true;
  170. }
  171. else if (selectedEdges - previouslySelectedEdgeCount < 0) { // node was deselected
  172. this.selectionHandler._generateClickEvent('deselectEdge', event, pointer, previousSelection);
  173. selected = true;
  174. }
  175. if (selected === true) { // select or unselect
  176. this.selectionHandler._generateClickEvent('select', event, pointer);
  177. }
  178. }
  179. /**
  180. * This function is called by onDragStart.
  181. * It is separated out because we can then overload it for the datamanipulation system.
  182. *
  183. * @private
  184. */
  185. onDragStart(event) {
  186. //in case the touch event was triggered on an external div, do the initial touch now.
  187. if (this.drag.pointer === undefined) {
  188. this.onTouch(event);
  189. }
  190. // note: drag.pointer is set in onTouch to get the initial touch location
  191. let node = this.selectionHandler.getNodeAt(this.drag.pointer);
  192. this.drag.dragging = true;
  193. this.drag.selection = [];
  194. this.drag.translation = util.extend({},this.body.view.translation); // copy the object
  195. this.drag.nodeId = undefined;
  196. this.selectionHandler._generateClickEvent('dragStart', event, this.drag.pointer);
  197. if (node !== undefined && this.options.dragNodes === true) {
  198. this.drag.nodeId = node.id;
  199. // select the clicked node if not yet selected
  200. if (node.isSelected() === false) {
  201. this.selectionHandler.unselectAll();
  202. this.selectionHandler.selectObject(node);
  203. }
  204. let selection = this.selectionHandler.selectionObj.nodes;
  205. // create an array with the selected nodes and their original location and status
  206. for (let nodeId in selection) {
  207. if (selection.hasOwnProperty(nodeId)) {
  208. let object = selection[nodeId];
  209. let s = {
  210. id: object.id,
  211. node: object,
  212. // store original x, y, xFixed and yFixed, make the node temporarily Fixed
  213. x: object.x,
  214. y: object.y,
  215. xFixed: object.options.fixed.x,
  216. yFixed: object.options.fixed.y
  217. };
  218. object.options.fixed.x = true;
  219. object.options.fixed.y = true;
  220. this.drag.selection.push(s);
  221. }
  222. }
  223. }
  224. }
  225. /**
  226. * handle drag event
  227. * @private
  228. */
  229. onDrag(event) {
  230. if (this.drag.pinched === true) {
  231. return;
  232. }
  233. // remove the focus on node if it is focussed on by the focusOnNode
  234. this.body.emitter.emit('unlockNode');
  235. let pointer = this.getPointer(event.center);
  236. this.selectionHandler._generateClickEvent('dragging', event, pointer);
  237. let selection = this.drag.selection;
  238. if (selection && selection.length && this.options.dragNodes === true) {
  239. // calculate delta's and new location
  240. let deltaX = pointer.x - this.drag.pointer.x;
  241. let deltaY = pointer.y - this.drag.pointer.y;
  242. // update position of all selected nodes
  243. selection.forEach((selection) => {
  244. let node = selection.node;
  245. // only move the node if it was not fixed initially
  246. if (selection.xFixed === false) {
  247. node.x = this.canvas._XconvertDOMtoCanvas(this.canvas._XconvertCanvasToDOM(selection.x) + deltaX);
  248. }
  249. // only move the node if it was not fixed initially
  250. if (selection.yFixed === false) {
  251. node.y = this.canvas._YconvertDOMtoCanvas(this.canvas._YconvertCanvasToDOM(selection.y) + deltaY);
  252. }
  253. });
  254. // start the simulation of the physics
  255. this.body.emitter.emit('startSimulation');
  256. }
  257. else {
  258. // move the network
  259. if (this.options.dragView === true) {
  260. // if the drag was not started properly because the click started outside the network div, start it now.
  261. if (this.drag.pointer === undefined) {
  262. this._handleDragStart(event);
  263. return;
  264. }
  265. let diffX = pointer.x - this.drag.pointer.x;
  266. let diffY = pointer.y - this.drag.pointer.y;
  267. this.body.view.translation = {x:this.drag.translation.x + diffX, y:this.drag.translation.y + diffY};
  268. this.body.emitter.emit('_redraw');
  269. }
  270. }
  271. }
  272. /**
  273. * handle drag start event
  274. * @private
  275. */
  276. onDragEnd(event) {
  277. this.drag.dragging = false;
  278. let selection = this.drag.selection;
  279. if (selection && selection.length) {
  280. selection.forEach(function (s) {
  281. // restore original xFixed and yFixed
  282. s.node.options.fixed.x = s.xFixed;
  283. s.node.options.fixed.y = s.yFixed;
  284. });
  285. this.body.emitter.emit('startSimulation');
  286. }
  287. else {
  288. this.body.emitter.emit('_requestRedraw');
  289. }
  290. this.selectionHandler._generateClickEvent('dragEnd', event, this.getPointer(event.center));
  291. }
  292. /**
  293. * Handle pinch event
  294. * @param event
  295. * @private
  296. */
  297. onPinch(event) {
  298. let pointer = this.getPointer(event.center);
  299. this.drag.pinched = true;
  300. if (this.pinch['scale'] === undefined) {
  301. this.pinch.scale = 1;
  302. }
  303. // TODO: enabled moving while pinching?
  304. let scale = this.pinch.scale * event.scale;
  305. this.zoom(scale, pointer)
  306. }
  307. /**
  308. * Zoom the network in or out
  309. * @param {Number} scale a number around 1, and between 0.01 and 10
  310. * @param {{x: Number, y: Number}} pointer Position on screen
  311. * @return {Number} appliedScale scale is limited within the boundaries
  312. * @private
  313. */
  314. zoom(scale, pointer) {
  315. if (this.options.zoomView === true) {
  316. let scaleOld = this.body.view.scale;
  317. if (scale < 0.00001) {
  318. scale = 0.00001;
  319. }
  320. if (scale > 10) {
  321. scale = 10;
  322. }
  323. let preScaleDragPointer = undefined;
  324. if (this.drag !== undefined) {
  325. if (this.drag.dragging === true) {
  326. preScaleDragPointer = this.canvas.DOMtoCanvas(this.drag.pointer);
  327. }
  328. }
  329. // + this.canvas.frame.canvas.clientHeight / 2
  330. let translation = this.body.view.translation;
  331. let scaleFrac = scale / scaleOld;
  332. let tx = (1 - scaleFrac) * pointer.x + translation.x * scaleFrac;
  333. let ty = (1 - scaleFrac) * pointer.y + translation.y * scaleFrac;
  334. this.body.view.scale = scale;
  335. this.body.view.translation = {x:tx, y:ty};
  336. if (preScaleDragPointer != undefined) {
  337. let postScaleDragPointer = this.canvas.canvasToDOM(preScaleDragPointer);
  338. this.drag.pointer.x = postScaleDragPointer.x;
  339. this.drag.pointer.y = postScaleDragPointer.y;
  340. }
  341. this.body.emitter.emit('_requestRedraw');
  342. if (scaleOld < scale) {
  343. this.body.emitter.emit('zoom', {direction: '+', scale: this.body.view.scale});
  344. }
  345. else {
  346. this.body.emitter.emit('zoom', {direction: '-', scale: this.body.view.scale});
  347. }
  348. }
  349. }
  350. /**
  351. * Event handler for mouse wheel event, used to zoom the timeline
  352. * See http://adomas.org/javascript-mouse-wheel/
  353. * https://github.com/EightMedia/hammer.js/issues/256
  354. * @param {MouseEvent} event
  355. * @private
  356. */
  357. onMouseWheel(event) {
  358. // retrieve delta
  359. let delta = 0;
  360. if (event.wheelDelta) { /* IE/Opera. */
  361. delta = event.wheelDelta / 120;
  362. } else if (event.detail) { /* Mozilla case. */
  363. // In Mozilla, sign of delta is different than in IE.
  364. // Also, delta is multiple of 3.
  365. delta = -event.detail / 3;
  366. }
  367. // If delta is nonzero, handle it.
  368. // Basically, delta is now positive if wheel was scrolled up,
  369. // and negative, if wheel was scrolled down.
  370. if (delta !== 0) {
  371. // calculate the new scale
  372. let scale = this.body.view.scale;
  373. let zoom = delta / 10;
  374. if (delta < 0) {
  375. zoom = zoom / (1 - zoom);
  376. }
  377. scale *= (1 + zoom);
  378. // calculate the pointer location
  379. let pointer = this.getPointer({x:event.pageX, y:event.pageY});
  380. // apply the new scale
  381. this.zoom(scale, pointer);
  382. }
  383. // Prevent default actions caused by mouse wheel.
  384. event.preventDefault();
  385. }
  386. /**
  387. * Mouse move handler for checking whether the title moves over a node with a title.
  388. * @param {Event} event
  389. * @private
  390. */
  391. onMouseMove(event) {
  392. let pointer = this.getPointer({x:event.pageX, y:event.pageY});
  393. let popupVisible = false;
  394. // check if the previously selected node is still selected
  395. if (this.popup !== undefined) {
  396. if (this.popup.hidden === false) {
  397. this._checkHidePopup(pointer);
  398. }
  399. // if the popup was not hidden above
  400. if (this.popup.hidden === false) {
  401. popupVisible = true;
  402. this.popup.setPosition(pointer.x + 3, pointer.y - 5);
  403. this.popup.show();
  404. }
  405. }
  406. // if we bind the keyboard to the div, we have to highlight it to use it. This highlights it on mouse over.
  407. if (this.options.keyboard.bindToWindow === false && this.options.keyboard.enabled === true) {
  408. this.canvas.frame.focus();
  409. }
  410. // start a timeout that will check if the mouse is positioned above an element
  411. if (popupVisible === false) {
  412. if (this.popupTimer !== undefined) {
  413. clearInterval(this.popupTimer); // stop any running calculationTimer
  414. this.popupTimer = undefined;
  415. }
  416. if (!this.drag.dragging) {
  417. this.popupTimer = setTimeout(() => this._checkShowPopup(pointer), this.options.tooltipDelay);
  418. }
  419. }
  420. /**
  421. * Adding hover highlights
  422. */
  423. if (this.options.hover === true) {
  424. // adding hover highlights
  425. let obj = this.selectionHandler.getNodeAt(pointer);
  426. if (obj === undefined) {
  427. obj = this.selectionHandler.getEdgeAt(pointer);
  428. }
  429. this.selectionHandler.hoverObject(obj);
  430. }
  431. }
  432. /**
  433. * Check if there is an element on the given position in the network
  434. * (a node or edge). If so, and if this element has a title,
  435. * show a popup window with its title.
  436. *
  437. * @param {{x:Number, y:Number}} pointer
  438. * @private
  439. */
  440. _checkShowPopup(pointer) {
  441. let x = this.canvas._XconvertDOMtoCanvas(pointer.x);
  442. let y = this.canvas._YconvertDOMtoCanvas(pointer.y);
  443. let pointerObj = {
  444. left: x,
  445. top: y,
  446. right: x,
  447. bottom: y
  448. };
  449. let previousPopupObjId = this.popupObj === undefined ? undefined : this.popupObj.id;
  450. let nodeUnderCursor = false;
  451. let popupType = 'node';
  452. // check if a node is under the cursor.
  453. if (this.popupObj === undefined) {
  454. // search the nodes for overlap, select the top one in case of multiple nodes
  455. let nodeIndices = this.body.nodeIndices;
  456. let nodes = this.body.nodes;
  457. let node;
  458. let overlappingNodes = [];
  459. for (let i = 0; i < nodeIndices.length; i++) {
  460. node = nodes[nodeIndices[i]];
  461. if (node.isOverlappingWith(pointerObj) === true) {
  462. if (node.getTitle() !== undefined) {
  463. overlappingNodes.push(nodeIndices[i]);
  464. }
  465. }
  466. }
  467. if (overlappingNodes.length > 0) {
  468. // if there are overlapping nodes, select the last one, this is the one which is drawn on top of the others
  469. this.popupObj = nodes[overlappingNodes[overlappingNodes.length - 1]];
  470. // if you hover over a node, the title of the edge is not supposed to be shown.
  471. nodeUnderCursor = true;
  472. }
  473. }
  474. if (this.popupObj === undefined && nodeUnderCursor === false) {
  475. // search the edges for overlap
  476. let edgeIndices = this.body.edgeIndices;
  477. let edges = this.body.edges;
  478. let edge;
  479. let overlappingEdges = [];
  480. for (let i = 0; i < edgeIndices.length; i++) {
  481. edge = edges[edgeIndices[i]];
  482. if (edge.isOverlappingWith(pointerObj) === true) {
  483. if (edge.connected === true && edge.getTitle() !== undefined) {
  484. overlappingEdges.push(edgeIndices[i]);
  485. }
  486. }
  487. }
  488. if (overlappingEdges.length > 0) {
  489. this.popupObj = edges[overlappingEdges[overlappingEdges.length - 1]];
  490. popupType = 'edge';
  491. }
  492. }
  493. if (this.popupObj !== undefined) {
  494. // show popup message window
  495. if (this.popupObj.id !== previousPopupObjId) {
  496. if (this.popup === undefined) {
  497. this.popup = new Popup(this.canvas.frame);
  498. }
  499. this.popup.popupTargetType = popupType;
  500. this.popup.popupTargetId = this.popupObj.id;
  501. // adjust a small offset such that the mouse cursor is located in the
  502. // bottom left location of the popup, and you can easily move over the
  503. // popup area
  504. this.popup.setPosition(pointer.x + 3, pointer.y - 5);
  505. this.popup.setText(this.popupObj.getTitle());
  506. this.popup.show();
  507. this.body.emitter.emit('showPopup',this.popupObj.id);
  508. }
  509. }
  510. else {
  511. if (this.popup !== undefined) {
  512. this.popup.hide();
  513. this.body.emitter.emit('hidePopup');
  514. }
  515. }
  516. }
  517. /**
  518. * Check if the popup must be hidden, which is the case when the mouse is no
  519. * longer hovering on the object
  520. * @param {{x:Number, y:Number}} pointer
  521. * @private
  522. */
  523. _checkHidePopup(pointer) {
  524. let pointerObj = this.selectionHandler._pointerToPositionObject(pointer);
  525. let stillOnObj = false;
  526. if (this.popup.popupTargetType === 'node') {
  527. if (this.body.nodes[this.popup.popupTargetId] !== undefined) {
  528. stillOnObj = this.body.nodes[this.popup.popupTargetId].isOverlappingWith(pointerObj);
  529. // 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.
  530. // we initially only check stillOnObj because this is much faster.
  531. if (stillOnObj === true) {
  532. let overNode = this.selectionHandler.getNodeAt(pointer);
  533. stillOnObj = overNode.id === this.popup.popupTargetId;
  534. }
  535. }
  536. }
  537. else {
  538. if (this.selectionHandler.getNodeAt(pointer) === undefined) {
  539. if (this.body.edges[this.popup.popupTargetId] !== undefined) {
  540. stillOnObj = this.body.edges[this.popup.popupTargetId].isOverlappingWith(pointerObj);
  541. }
  542. }
  543. }
  544. if (stillOnObj === false) {
  545. this.popupObj = undefined;
  546. this.popup.hide();
  547. this.body.emitter.emit('hidePopup');
  548. }
  549. }
  550. }
  551. export default InteractionHandler;