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.

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