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.

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