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.

705 lines
22 KiB

9 years ago
9 years ago
  1. let util = require('../../util');
  2. var NavigationHandler = require('./components/NavigationHandler').default;
  3. var Popup = require('./../../shared/Popup').default;
  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 &&
  102. (event.changedPointers[0].ctrlKey || event.changedPointers[0].metaKey);
  103. this.checkSelectionChanges(pointer, event, multiselect);
  104. this.selectionHandler._generateClickEvent('click', event, pointer);
  105. }
  106. /**
  107. * handle doubletap event
  108. * @private
  109. */
  110. onDoubleTap(event) {
  111. let pointer = this.getPointer(event.center);
  112. this.selectionHandler._generateClickEvent('doubleClick', event, pointer);
  113. }
  114. /**
  115. * handle long tap event: multi select nodes
  116. * @private
  117. */
  118. onHold(event) {
  119. let pointer = this.getPointer(event.center);
  120. let multiselect = this.selectionHandler.options.multiselect;
  121. this.checkSelectionChanges(pointer, event, multiselect);
  122. this.selectionHandler._generateClickEvent('click', event, pointer);
  123. this.selectionHandler._generateClickEvent('hold', event, pointer);
  124. }
  125. /**
  126. * handle the release of the screen
  127. *
  128. * @private
  129. */
  130. onRelease(event) {
  131. if (new Date().valueOf() - this.touchTime > 10) {
  132. let pointer = this.getPointer(event.center);
  133. this.selectionHandler._generateClickEvent('release', event, pointer);
  134. // to avoid double fireing of this event because we have two hammer instances. (on canvas and on frame)
  135. this.touchTime = new Date().valueOf();
  136. }
  137. }
  138. onContext(event) {
  139. let pointer = this.getPointer({x:event.clientX, y:event.clientY});
  140. this.selectionHandler._generateClickEvent('oncontext', event, pointer);
  141. }
  142. /**
  143. * Select and deselect nodes depending current selection change.
  144. *
  145. * For changing nodes, select/deselect events are fired.
  146. *
  147. * NOTE: For a given edge, if one connecting node is deselected and with the same
  148. * click the other node is selected, no events for the edge will fire.
  149. * It was selected and it will remain selected.
  150. *
  151. * TODO: This is all SelectionHandler calls; the method should be moved to there.
  152. *
  153. * @param pointer
  154. * @param add
  155. */
  156. checkSelectionChanges(pointer, event, add = false) {
  157. let previousSelection = this.selectionHandler.getSelection();
  158. let selected = false;
  159. if (add === true) {
  160. selected = this.selectionHandler.selectAdditionalOnPoint(pointer);
  161. }
  162. else {
  163. selected = this.selectionHandler.selectOnPoint(pointer);
  164. }
  165. let currentSelection = this.selectionHandler.getSelection();
  166. // See NOTE in method comment for the reason to do it like this
  167. let deselectedItems = this._determineDifference(previousSelection, currentSelection);
  168. let selectedItems = this._determineDifference(currentSelection , previousSelection);
  169. if (deselectedItems.edges.length > 0) {
  170. this.selectionHandler._generateClickEvent('deselectEdge', event, pointer, previousSelection);
  171. selected = true;
  172. }
  173. if (deselectedItems.nodes.length > 0) {
  174. this.selectionHandler._generateClickEvent('deselectNode', event, pointer, previousSelection);
  175. selected = true;
  176. }
  177. if (selectedItems.nodes.length > 0) {
  178. this.selectionHandler._generateClickEvent('selectNode', event, pointer);
  179. selected = true;
  180. }
  181. if (selectedItems.edges.length > 0) {
  182. this.selectionHandler._generateClickEvent('selectEdge', event, pointer);
  183. selected = true;
  184. }
  185. // fire the select event if anything has been selected or deselected
  186. if (selected === true) { // select or unselect
  187. this.selectionHandler._generateClickEvent('select', event, pointer);
  188. }
  189. }
  190. /**
  191. * Remove all node and edge id's from the first set that are present in the second one.
  192. *
  193. * @param firstSet
  194. * @param secondSet
  195. * @returns {{nodes: array, edges: array}}
  196. * @private
  197. */
  198. _determineDifference(firstSet, secondSet) {
  199. let arrayDiff = function(firstArr, secondArr) {
  200. let result = [];
  201. for (let i = 0; i < firstArr.length; i++) {
  202. let value = firstArr[i];
  203. if (secondArr.indexOf(value) === -1) {
  204. result.push(value);
  205. }
  206. }
  207. return result;
  208. };
  209. return {
  210. nodes: arrayDiff(firstSet.nodes, secondSet.nodes),
  211. edges: arrayDiff(firstSet.edges, secondSet.edges)
  212. };
  213. }
  214. /**
  215. * This function is called by onDragStart.
  216. * It is separated out because we can then overload it for the datamanipulation system.
  217. *
  218. * @private
  219. */
  220. onDragStart(event) {
  221. //in case the touch event was triggered on an external div, do the initial touch now.
  222. if (this.drag.pointer === undefined) {
  223. this.onTouch(event);
  224. }
  225. // note: drag.pointer is set in onTouch to get the initial touch location
  226. let node = this.selectionHandler.getNodeAt(this.drag.pointer);
  227. this.drag.dragging = true;
  228. this.drag.selection = [];
  229. this.drag.translation = util.extend({},this.body.view.translation); // copy the object
  230. this.drag.nodeId = undefined;
  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. // after select to contain the node
  239. this.selectionHandler._generateClickEvent('dragStart', event, this.drag.pointer);
  240. let selection = this.selectionHandler.selectionObj.nodes;
  241. // create an array with the selected nodes and their original location and status
  242. for (let nodeId in selection) {
  243. if (selection.hasOwnProperty(nodeId)) {
  244. let object = selection[nodeId];
  245. let s = {
  246. id: object.id,
  247. node: object,
  248. // store original x, y, xFixed and yFixed, make the node temporarily Fixed
  249. x: object.x,
  250. y: object.y,
  251. xFixed: object.options.fixed.x,
  252. yFixed: object.options.fixed.y
  253. };
  254. object.options.fixed.x = true;
  255. object.options.fixed.y = true;
  256. this.drag.selection.push(s);
  257. }
  258. }
  259. }
  260. else {
  261. // fallback if no node is selected and thus the view is dragged.
  262. this.selectionHandler._generateClickEvent('dragStart', event, this.drag.pointer, undefined, true);
  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. let selection = this.drag.selection;
  277. if (selection && selection.length && this.options.dragNodes === true) {
  278. this.selectionHandler._generateClickEvent('dragging', event, pointer);
  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. this.selectionHandler._generateClickEvent('dragging', event, pointer, undefined, true);
  301. // if the drag was not started properly because the click started outside the network div, start it now.
  302. if (this.drag.pointer === undefined) {
  303. this.onDragStart(event);
  304. return;
  305. }
  306. let diffX = pointer.x - this.drag.pointer.x;
  307. let diffY = pointer.y - this.drag.pointer.y;
  308. this.body.view.translation = {x:this.drag.translation.x + diffX, y:this.drag.translation.y + diffY};
  309. this.body.emitter.emit('_redraw');
  310. }
  311. }
  312. }
  313. /**
  314. * handle drag start event
  315. * @private
  316. */
  317. onDragEnd(event) {
  318. this.drag.dragging = false;
  319. let selection = this.drag.selection;
  320. if (selection && selection.length) {
  321. selection.forEach(function (s) {
  322. // restore original xFixed and yFixed
  323. s.node.options.fixed.x = s.xFixed;
  324. s.node.options.fixed.y = s.yFixed;
  325. });
  326. this.selectionHandler._generateClickEvent('dragEnd', event, this.getPointer(event.center));
  327. this.body.emitter.emit('startSimulation');
  328. }
  329. else {
  330. this.selectionHandler._generateClickEvent('dragEnd', event, this.getPointer(event.center), undefined, true);
  331. this.body.emitter.emit('_requestRedraw');
  332. }
  333. }
  334. /**
  335. * Handle pinch event
  336. * @param event
  337. * @private
  338. */
  339. onPinch(event) {
  340. let pointer = this.getPointer(event.center);
  341. this.drag.pinched = true;
  342. if (this.pinch['scale'] === undefined) {
  343. this.pinch.scale = 1;
  344. }
  345. // TODO: enabled moving while pinching?
  346. let scale = this.pinch.scale * event.scale;
  347. this.zoom(scale, pointer)
  348. }
  349. /**
  350. * Zoom the network in or out
  351. * @param {Number} scale a number around 1, and between 0.01 and 10
  352. * @param {{x: Number, y: Number}} pointer Position on screen
  353. * @return {Number} appliedScale scale is limited within the boundaries
  354. * @private
  355. */
  356. zoom(scale, pointer) {
  357. if (this.options.zoomView === true) {
  358. let scaleOld = this.body.view.scale;
  359. if (scale < 0.00001) {
  360. scale = 0.00001;
  361. }
  362. if (scale > 10) {
  363. scale = 10;
  364. }
  365. let preScaleDragPointer = undefined;
  366. if (this.drag !== undefined) {
  367. if (this.drag.dragging === true) {
  368. preScaleDragPointer = this.canvas.DOMtoCanvas(this.drag.pointer);
  369. }
  370. }
  371. // + this.canvas.frame.canvas.clientHeight / 2
  372. let translation = this.body.view.translation;
  373. let scaleFrac = scale / scaleOld;
  374. let tx = (1 - scaleFrac) * pointer.x + translation.x * scaleFrac;
  375. let ty = (1 - scaleFrac) * pointer.y + translation.y * scaleFrac;
  376. this.body.view.scale = scale;
  377. this.body.view.translation = {x:tx, y:ty};
  378. if (preScaleDragPointer != undefined) {
  379. let postScaleDragPointer = this.canvas.canvasToDOM(preScaleDragPointer);
  380. this.drag.pointer.x = postScaleDragPointer.x;
  381. this.drag.pointer.y = postScaleDragPointer.y;
  382. }
  383. this.body.emitter.emit('_requestRedraw');
  384. if (scaleOld < scale) {
  385. this.body.emitter.emit('zoom', {direction: '+', scale: this.body.view.scale, pointer: pointer});
  386. }
  387. else {
  388. this.body.emitter.emit('zoom', {direction: '-', scale: this.body.view.scale, pointer: pointer});
  389. }
  390. }
  391. }
  392. /**
  393. * Event handler for mouse wheel event, used to zoom the timeline
  394. * See http://adomas.org/javascript-mouse-wheel/
  395. * https://github.com/EightMedia/hammer.js/issues/256
  396. * @param {MouseEvent} event
  397. * @private
  398. */
  399. onMouseWheel(event) {
  400. if (this.options.zoomView === true) {
  401. // retrieve delta
  402. let delta = 0;
  403. if (event.wheelDelta) { /* IE/Opera. */
  404. delta = event.wheelDelta / 120;
  405. }
  406. else if (event.detail) { /* Mozilla case. */
  407. // In Mozilla, sign of delta is different than in IE.
  408. // Also, delta is multiple of 3.
  409. delta = -event.detail / 3;
  410. }
  411. // If delta is nonzero, handle it.
  412. // Basically, delta is now positive if wheel was scrolled up,
  413. // and negative, if wheel was scrolled down.
  414. if (delta !== 0) {
  415. // calculate the new scale
  416. let scale = this.body.view.scale;
  417. let zoom = delta / 10;
  418. if (delta < 0) {
  419. zoom = zoom / (1 - zoom);
  420. }
  421. scale *= (1 + zoom);
  422. // calculate the pointer location
  423. let pointer = this.getPointer({x: event.clientX, y: event.clientY});
  424. // apply the new scale
  425. this.zoom(scale, pointer);
  426. }
  427. // Prevent default actions caused by mouse wheel.
  428. event.preventDefault();
  429. }
  430. }
  431. /**
  432. * Mouse move handler for checking whether the title moves over a node with a title.
  433. * @param {Event} event
  434. * @private
  435. */
  436. onMouseMove(event) {
  437. let pointer = this.getPointer({x:event.clientX, y:event.clientY});
  438. let popupVisible = false;
  439. // check if the previously selected node is still selected
  440. if (this.popup !== undefined) {
  441. if (this.popup.hidden === false) {
  442. this._checkHidePopup(pointer);
  443. }
  444. // if the popup was not hidden above
  445. if (this.popup.hidden === false) {
  446. popupVisible = true;
  447. this.popup.setPosition(pointer.x + 3, pointer.y - 5);
  448. this.popup.show();
  449. }
  450. }
  451. // if we bind the keyboard to the div, we have to highlight it to use it. This highlights it on mouse over.
  452. if (this.options.keyboard.bindToWindow === false && this.options.keyboard.enabled === true) {
  453. this.canvas.frame.focus();
  454. }
  455. // start a timeout that will check if the mouse is positioned above an element
  456. if (popupVisible === false) {
  457. if (this.popupTimer !== undefined) {
  458. clearInterval(this.popupTimer); // stop any running calculationTimer
  459. this.popupTimer = undefined;
  460. }
  461. if (!this.drag.dragging) {
  462. this.popupTimer = setTimeout(() => this._checkShowPopup(pointer), this.options.tooltipDelay);
  463. }
  464. }
  465. /**
  466. * Adding hover highlights
  467. */
  468. if (this.options.hover === true) {
  469. // adding hover highlights
  470. let obj = this.selectionHandler.getNodeAt(pointer);
  471. if (obj === undefined) {
  472. obj = this.selectionHandler.getEdgeAt(pointer);
  473. }
  474. this.selectionHandler.hoverObject(obj);
  475. }
  476. }
  477. /**
  478. * Check if there is an element on the given position in the network
  479. * (a node or edge). If so, and if this element has a title,
  480. * show a popup window with its title.
  481. *
  482. * @param {{x:Number, y:Number}} pointer
  483. * @private
  484. */
  485. _checkShowPopup(pointer) {
  486. let x = this.canvas._XconvertDOMtoCanvas(pointer.x);
  487. let y = this.canvas._YconvertDOMtoCanvas(pointer.y);
  488. let pointerObj = {
  489. left: x,
  490. top: y,
  491. right: x,
  492. bottom: y
  493. };
  494. let previousPopupObjId = this.popupObj === undefined ? undefined : this.popupObj.id;
  495. let nodeUnderCursor = false;
  496. let popupType = 'node';
  497. // check if a node is under the cursor.
  498. if (this.popupObj === undefined) {
  499. // search the nodes for overlap, select the top one in case of multiple nodes
  500. let nodeIndices = this.body.nodeIndices;
  501. let nodes = this.body.nodes;
  502. let node;
  503. let overlappingNodes = [];
  504. for (let i = 0; i < nodeIndices.length; i++) {
  505. node = nodes[nodeIndices[i]];
  506. if (node.isOverlappingWith(pointerObj) === true) {
  507. if (node.getTitle() !== undefined) {
  508. overlappingNodes.push(nodeIndices[i]);
  509. }
  510. }
  511. }
  512. if (overlappingNodes.length > 0) {
  513. // if there are overlapping nodes, select the last one, this is the one which is drawn on top of the others
  514. this.popupObj = nodes[overlappingNodes[overlappingNodes.length - 1]];
  515. // if you hover over a node, the title of the edge is not supposed to be shown.
  516. nodeUnderCursor = true;
  517. }
  518. }
  519. if (this.popupObj === undefined && nodeUnderCursor === false) {
  520. // search the edges for overlap
  521. let edgeIndices = this.body.edgeIndices;
  522. let edges = this.body.edges;
  523. let edge;
  524. let overlappingEdges = [];
  525. for (let i = 0; i < edgeIndices.length; i++) {
  526. edge = edges[edgeIndices[i]];
  527. if (edge.isOverlappingWith(pointerObj) === true) {
  528. if (edge.connected === true && edge.getTitle() !== undefined) {
  529. overlappingEdges.push(edgeIndices[i]);
  530. }
  531. }
  532. }
  533. if (overlappingEdges.length > 0) {
  534. this.popupObj = edges[overlappingEdges[overlappingEdges.length - 1]];
  535. popupType = 'edge';
  536. }
  537. }
  538. if (this.popupObj !== undefined) {
  539. // show popup message window
  540. if (this.popupObj.id !== previousPopupObjId) {
  541. if (this.popup === undefined) {
  542. this.popup = new Popup(this.canvas.frame);
  543. }
  544. this.popup.popupTargetType = popupType;
  545. this.popup.popupTargetId = this.popupObj.id;
  546. // adjust a small offset such that the mouse cursor is located in the
  547. // bottom left location of the popup, and you can easily move over the
  548. // popup area
  549. this.popup.setPosition(pointer.x + 3, pointer.y - 5);
  550. this.popup.setText(this.popupObj.getTitle());
  551. this.popup.show();
  552. this.body.emitter.emit('showPopup',this.popupObj.id);
  553. }
  554. }
  555. else {
  556. if (this.popup !== undefined) {
  557. this.popup.hide();
  558. this.body.emitter.emit('hidePopup');
  559. }
  560. }
  561. }
  562. /**
  563. * Check if the popup must be hidden, which is the case when the mouse is no
  564. * longer hovering on the object
  565. * @param {{x:Number, y:Number}} pointer
  566. * @private
  567. */
  568. _checkHidePopup(pointer) {
  569. let pointerObj = this.selectionHandler._pointerToPositionObject(pointer);
  570. let stillOnObj = false;
  571. if (this.popup.popupTargetType === 'node') {
  572. if (this.body.nodes[this.popup.popupTargetId] !== undefined) {
  573. stillOnObj = this.body.nodes[this.popup.popupTargetId].isOverlappingWith(pointerObj);
  574. // 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.
  575. // we initially only check stillOnObj because this is much faster.
  576. if (stillOnObj === true) {
  577. let overNode = this.selectionHandler.getNodeAt(pointer);
  578. stillOnObj = overNode === undefined ? false : overNode.id === this.popup.popupTargetId;
  579. }
  580. }
  581. }
  582. else {
  583. if (this.selectionHandler.getNodeAt(pointer) === undefined) {
  584. if (this.body.edges[this.popup.popupTargetId] !== undefined) {
  585. stillOnObj = this.body.edges[this.popup.popupTargetId].isOverlappingWith(pointerObj);
  586. }
  587. }
  588. }
  589. if (stillOnObj === false) {
  590. this.popupObj = undefined;
  591. this.popup.hide();
  592. this.body.emitter.emit('hidePopup');
  593. }
  594. }
  595. }
  596. export default InteractionHandler;