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.

673 lines
21 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, event);
  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. this.checkSelectionChanges(pointer, event, true);
  120. this.selectionHandler._generateClickEvent('click', event, pointer);
  121. this.selectionHandler._generateClickEvent('hold', event, 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', event, 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('oncontext', event, pointer);
  139. }
  140. /**
  141. *
  142. * @param pointer
  143. * @param add
  144. */
  145. checkSelectionChanges(pointer, event, 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', event, pointer);
  160. selected = true;
  161. }
  162. else if (selectedNodes - previouslySelectedNodeCount < 0) { // node was deselected
  163. this.selectionHandler._generateClickEvent('deselectNode', event, pointer, previousSelection);
  164. selected = true;
  165. }
  166. if (selectedEdges - previouslySelectedEdgeCount > 0) { // node was selected
  167. this.selectionHandler._generateClickEvent('selectEdge', event, pointer);
  168. selected = true;
  169. }
  170. else if (selectedEdges - previouslySelectedEdgeCount < 0) { // node was deselected
  171. this.selectionHandler._generateClickEvent('deselectEdge', event, pointer, previousSelection);
  172. selected = true;
  173. }
  174. if (selected === true) { // select or unselect
  175. this.selectionHandler._generateClickEvent('select', event, 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', event, 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 = {};
  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: '+'});
  344. }
  345. else {
  346. this.body.emitter.emit('zoom', {direction: '-'});
  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.hoverEnabled === true) {
  424. // removing all hover highlights
  425. for (let edgeId in this.hoverObj.edges) {
  426. if (this.hoverObj.edges.hasOwnProperty(edgeId)) {
  427. this.hoverObj.edges[edgeId].hover = false;
  428. delete this.hoverObj.edges[edgeId];
  429. }
  430. }
  431. // adding hover highlights
  432. let obj = this.selectionHandler.getNodeAt(pointer);
  433. if (obj === undefined) {
  434. obj = this.selectionHandler.getEdgeAt(pointer);
  435. }
  436. if (obj != undefined) {
  437. this.selectionHandler.hoverObject(obj);
  438. }
  439. // removing all node hover highlights except for the selected one.
  440. for (let nodeId in this.hoverObj.nodes) {
  441. if (this.hoverObj.nodes.hasOwnProperty(nodeId)) {
  442. if (obj instanceof Node && obj.id != nodeId || obj instanceof Edge || obj === undefined) {
  443. this.selectionHandler.blurObject(this.hoverObj.nodes[nodeId]);
  444. delete this.hoverObj.nodes[nodeId];
  445. }
  446. }
  447. }
  448. this.body.emitter.emit('_requestRedraw');
  449. }
  450. }
  451. /**
  452. * Check if there is an element on the given position in the network
  453. * (a node or edge). If so, and if this element has a title,
  454. * show a popup window with its title.
  455. *
  456. * @param {{x:Number, y:Number}} pointer
  457. * @private
  458. */
  459. _checkShowPopup(pointer) {
  460. let x = this.canvas._XconvertDOMtoCanvas(pointer.x);
  461. let y = this.canvas._YconvertDOMtoCanvas(pointer.y);
  462. let pointerObj = {
  463. left: x,
  464. top: y,
  465. right: x,
  466. bottom: y
  467. };
  468. let previousPopupObjId = this.popupObj === undefined ? undefined : this.popupObj.id;
  469. let nodeUnderCursor = false;
  470. let popupType = 'node';
  471. // check if a node is under the cursor.
  472. if (this.popupObj === undefined) {
  473. // search the nodes for overlap, select the top one in case of multiple nodes
  474. let nodeIndices = this.body.nodeIndices;
  475. let nodes = this.body.nodes;
  476. let node;
  477. let overlappingNodes = [];
  478. for (let i = 0; i < nodeIndices.length; i++) {
  479. node = nodes[nodeIndices[i]];
  480. if (node.isOverlappingWith(pointerObj) === true) {
  481. if (node.getTitle() !== undefined) {
  482. overlappingNodes.push(nodeIndices[i]);
  483. }
  484. }
  485. }
  486. if (overlappingNodes.length > 0) {
  487. // if there are overlapping nodes, select the last one, this is the one which is drawn on top of the others
  488. this.popupObj = nodes[overlappingNodes[overlappingNodes.length - 1]];
  489. // if you hover over a node, the title of the edge is not supposed to be shown.
  490. nodeUnderCursor = true;
  491. }
  492. }
  493. if (this.popupObj === undefined && nodeUnderCursor === false) {
  494. // search the edges for overlap
  495. let edgeIndices = this.body.edgeIndices;
  496. let edges = this.body.edges;
  497. let edge;
  498. let overlappingEdges = [];
  499. for (let i = 0; i < edgeIndices.length; i++) {
  500. edge = edges[edgeIndices[i]];
  501. if (edge.isOverlappingWith(pointerObj) === true) {
  502. if (edge.connected === true && edge.getTitle() !== undefined) {
  503. overlappingEdges.push(edgeIndices[i]);
  504. }
  505. }
  506. }
  507. if (overlappingEdges.length > 0) {
  508. this.popupObj = edges[overlappingEdges[overlappingEdges.length - 1]];
  509. popupType = 'edge';
  510. }
  511. }
  512. if (this.popupObj !== undefined) {
  513. // show popup message window
  514. if (this.popupObj.id !== previousPopupObjId) {
  515. if (this.popup === undefined) {
  516. this.popup = new Popup(this.canvas.frame);
  517. }
  518. this.popup.popupTargetType = popupType;
  519. this.popup.popupTargetId = this.popupObj.id;
  520. // adjust a small offset such that the mouse cursor is located in the
  521. // bottom left location of the popup, and you can easily move over the
  522. // popup area
  523. this.popup.setPosition(pointer.x + 3, pointer.y - 5);
  524. this.popup.setText(this.popupObj.getTitle());
  525. this.popup.show();
  526. this.body.emitter.emit('showPopup',this.popupObj.id);
  527. }
  528. }
  529. else {
  530. if (this.popup !== undefined) {
  531. this.popup.hide();
  532. this.body.emitter.emit('hidePopup');
  533. }
  534. }
  535. }
  536. /**
  537. * Check if the popup must be hidden, which is the case when the mouse is no
  538. * longer hovering on the object
  539. * @param {{x:Number, y:Number}} pointer
  540. * @private
  541. */
  542. _checkHidePopup(pointer) {
  543. let pointerObj = this.selectionHandler._pointerToPositionObject(pointer);
  544. let stillOnObj = false;
  545. if (this.popup.popupTargetType === 'node') {
  546. if (this.body.nodes[this.popup.popupTargetId] !== undefined) {
  547. stillOnObj = this.body.nodes[this.popup.popupTargetId].isOverlappingWith(pointerObj);
  548. // 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.
  549. // we initially only check stillOnObj because this is much faster.
  550. if (stillOnObj === true) {
  551. let overNode = this.selectionHandler.getNodeAt(pointer);
  552. stillOnObj = overNode.id === this.popup.popupTargetId;
  553. }
  554. }
  555. }
  556. else {
  557. if (this.selectionHandler.getNodeAt(pointer) === undefined) {
  558. if (this.body.edges[this.popup.popupTargetId] !== undefined) {
  559. stillOnObj = this.body.edges[this.popup.popupTargetId].isOverlappingWith(pointerObj);
  560. }
  561. }
  562. }
  563. if (stillOnObj === false) {
  564. this.popupObj = undefined;
  565. this.popup.hide();
  566. this.body.emitter.emit('hidePopup');
  567. }
  568. }
  569. }
  570. export default InteractionHandler;