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.

702 lines
22 KiB

9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
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 &&
  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. *
  144. * @param pointer
  145. * @param add
  146. */
  147. checkSelectionChanges(pointer, event, add = false) {
  148. let previouslySelectedEdgeCount = this.selectionHandler._getSelectedEdgeCount();
  149. let previouslySelectedNodeCount = this.selectionHandler._getSelectedNodeCount();
  150. let previousSelection = this.selectionHandler.getSelection();
  151. let selected;
  152. if (add === true) {
  153. selected = this.selectionHandler.selectAdditionalOnPoint(pointer);
  154. }
  155. else {
  156. selected = this.selectionHandler.selectOnPoint(pointer);
  157. }
  158. let selectedEdgesCount = this.selectionHandler._getSelectedEdgeCount();
  159. let selectedNodesCount = this.selectionHandler._getSelectedNodeCount();
  160. let currentSelection = this.selectionHandler.getSelection();
  161. let {nodesChanges, edgesChanges} = this._determineIfDifferent(previousSelection, currentSelection);
  162. if (selectedNodesCount - previouslySelectedNodeCount > 0) { // node was selected
  163. this.selectionHandler._generateClickEvent('selectNode', event, pointer);
  164. selected = true;
  165. }
  166. else if (selectedNodesCount - previouslySelectedNodeCount < 0) { // node was deselected
  167. this.selectionHandler._generateClickEvent('deselectNode', event, pointer, previousSelection);
  168. selected = true;
  169. }
  170. else if (selectedNodesCount === previouslySelectedNodeCount && nodesChanges === true) {
  171. this.selectionHandler._generateClickEvent('deselectNode', event, pointer, previousSelection);
  172. this.selectionHandler._generateClickEvent('selectNode', event, pointer);
  173. selected = true;
  174. }
  175. if (selectedEdgesCount - previouslySelectedEdgeCount > 0) { // edge was selected
  176. this.selectionHandler._generateClickEvent('selectEdge', event, pointer);
  177. selected = true;
  178. }
  179. else if (selectedEdgesCount - previouslySelectedEdgeCount < 0) { // edge was deselected
  180. this.selectionHandler._generateClickEvent('deselectEdge', event, pointer, previousSelection);
  181. selected = true;
  182. }
  183. else if (selectedEdgesCount === previouslySelectedEdgeCount && edgesChanges === true) {
  184. this.selectionHandler._generateClickEvent('deselectEdge', event, pointer, previousSelection);
  185. this.selectionHandler._generateClickEvent('selectEdge', event, pointer);
  186. selected = true;
  187. }
  188. if (selected === true) { // select or unselect
  189. this.selectionHandler._generateClickEvent('select', event, pointer);
  190. }
  191. }
  192. /**
  193. * This function checks if the nodes and edges previously selected have changed.
  194. * @param previousSelection
  195. * @param currentSelection
  196. * @returns {{nodesChanges: boolean, edgesChanges: boolean}}
  197. * @private
  198. */
  199. _determineIfDifferent(previousSelection,currentSelection) {
  200. let nodesChanges = false;
  201. let edgesChanges = false;
  202. for (let i = 0; i < previousSelection.nodes.length; i++) {
  203. if (currentSelection.nodes.indexOf(previousSelection.nodes[i]) === -1) {
  204. nodesChanges = true;
  205. }
  206. }
  207. for (let i = 0; i < currentSelection.nodes.length; i++) {
  208. if (previousSelection.nodes.indexOf(previousSelection.nodes[i]) === -1) {
  209. nodesChanges = true;
  210. }
  211. }
  212. for (let i = 0; i < previousSelection.edges.length; i++) {
  213. if (currentSelection.edges.indexOf(previousSelection.edges[i]) === -1) {
  214. edgesChanges = true;
  215. }
  216. }
  217. for (let i = 0; i < currentSelection.edges.length; i++) {
  218. if (previousSelection.edges.indexOf(previousSelection.edges[i]) === -1) {
  219. edgesChanges = true;
  220. }
  221. }
  222. return {nodesChanges, edgesChanges};
  223. }
  224. /**
  225. * This function is called by onDragStart.
  226. * It is separated out because we can then overload it for the datamanipulation system.
  227. *
  228. * @private
  229. */
  230. onDragStart(event) {
  231. //in case the touch event was triggered on an external div, do the initial touch now.
  232. if (this.drag.pointer === undefined) {
  233. this.onTouch(event);
  234. }
  235. // note: drag.pointer is set in onTouch to get the initial touch location
  236. let node = this.selectionHandler.getNodeAt(this.drag.pointer);
  237. this.drag.dragging = true;
  238. this.drag.selection = [];
  239. this.drag.translation = util.extend({},this.body.view.translation); // copy the object
  240. this.drag.nodeId = undefined;
  241. this.selectionHandler._generateClickEvent('dragStart', event, this.drag.pointer);
  242. if (node !== undefined && this.options.dragNodes === true) {
  243. this.drag.nodeId = node.id;
  244. // select the clicked node if not yet selected
  245. if (node.isSelected() === false) {
  246. this.selectionHandler.unselectAll();
  247. this.selectionHandler.selectObject(node);
  248. }
  249. let selection = this.selectionHandler.selectionObj.nodes;
  250. // create an array with the selected nodes and their original location and status
  251. for (let nodeId in selection) {
  252. if (selection.hasOwnProperty(nodeId)) {
  253. let object = selection[nodeId];
  254. let s = {
  255. id: object.id,
  256. node: object,
  257. // store original x, y, xFixed and yFixed, make the node temporarily Fixed
  258. x: object.x,
  259. y: object.y,
  260. xFixed: object.options.fixed.x,
  261. yFixed: object.options.fixed.y
  262. };
  263. object.options.fixed.x = true;
  264. object.options.fixed.y = true;
  265. this.drag.selection.push(s);
  266. }
  267. }
  268. }
  269. }
  270. /**
  271. * handle drag event
  272. * @private
  273. */
  274. onDrag(event) {
  275. if (this.drag.pinched === true) {
  276. return;
  277. }
  278. // remove the focus on node if it is focussed on by the focusOnNode
  279. this.body.emitter.emit('unlockNode');
  280. let pointer = this.getPointer(event.center);
  281. this.selectionHandler._generateClickEvent('dragging', event, pointer);
  282. let selection = this.drag.selection;
  283. if (selection && selection.length && this.options.dragNodes === true) {
  284. // calculate delta's and new location
  285. let deltaX = pointer.x - this.drag.pointer.x;
  286. let deltaY = pointer.y - this.drag.pointer.y;
  287. // update position of all selected nodes
  288. selection.forEach((selection) => {
  289. let node = selection.node;
  290. // only move the node if it was not fixed initially
  291. if (selection.xFixed === false) {
  292. node.x = this.canvas._XconvertDOMtoCanvas(this.canvas._XconvertCanvasToDOM(selection.x) + deltaX);
  293. }
  294. // only move the node if it was not fixed initially
  295. if (selection.yFixed === false) {
  296. node.y = this.canvas._YconvertDOMtoCanvas(this.canvas._YconvertCanvasToDOM(selection.y) + deltaY);
  297. }
  298. });
  299. // start the simulation of the physics
  300. this.body.emitter.emit('startSimulation');
  301. }
  302. else {
  303. // move the network
  304. if (this.options.dragView === true) {
  305. // if the drag was not started properly because the click started outside the network div, start it now.
  306. if (this.drag.pointer === undefined) {
  307. this._handleDragStart(event);
  308. return;
  309. }
  310. let diffX = pointer.x - this.drag.pointer.x;
  311. let diffY = pointer.y - this.drag.pointer.y;
  312. this.body.view.translation = {x:this.drag.translation.x + diffX, y:this.drag.translation.y + diffY};
  313. this.body.emitter.emit('_redraw');
  314. }
  315. }
  316. }
  317. /**
  318. * handle drag start event
  319. * @private
  320. */
  321. onDragEnd(event) {
  322. this.drag.dragging = false;
  323. let selection = this.drag.selection;
  324. if (selection && selection.length) {
  325. selection.forEach(function (s) {
  326. // restore original xFixed and yFixed
  327. s.node.options.fixed.x = s.xFixed;
  328. s.node.options.fixed.y = s.yFixed;
  329. });
  330. this.body.emitter.emit('startSimulation');
  331. }
  332. else {
  333. this.body.emitter.emit('_requestRedraw');
  334. }
  335. this.selectionHandler._generateClickEvent('dragEnd', event, this.getPointer(event.center));
  336. }
  337. /**
  338. * Handle pinch event
  339. * @param event
  340. * @private
  341. */
  342. onPinch(event) {
  343. let pointer = this.getPointer(event.center);
  344. this.drag.pinched = true;
  345. if (this.pinch['scale'] === undefined) {
  346. this.pinch.scale = 1;
  347. }
  348. // TODO: enabled moving while pinching?
  349. let scale = this.pinch.scale * event.scale;
  350. this.zoom(scale, pointer)
  351. }
  352. /**
  353. * Zoom the network in or out
  354. * @param {Number} scale a number around 1, and between 0.01 and 10
  355. * @param {{x: Number, y: Number}} pointer Position on screen
  356. * @return {Number} appliedScale scale is limited within the boundaries
  357. * @private
  358. */
  359. zoom(scale, pointer) {
  360. if (this.options.zoomView === true) {
  361. let scaleOld = this.body.view.scale;
  362. if (scale < 0.00001) {
  363. scale = 0.00001;
  364. }
  365. if (scale > 10) {
  366. scale = 10;
  367. }
  368. let preScaleDragPointer = undefined;
  369. if (this.drag !== undefined) {
  370. if (this.drag.dragging === true) {
  371. preScaleDragPointer = this.canvas.DOMtoCanvas(this.drag.pointer);
  372. }
  373. }
  374. // + this.canvas.frame.canvas.clientHeight / 2
  375. let translation = this.body.view.translation;
  376. let scaleFrac = scale / scaleOld;
  377. let tx = (1 - scaleFrac) * pointer.x + translation.x * scaleFrac;
  378. let ty = (1 - scaleFrac) * pointer.y + translation.y * scaleFrac;
  379. this.body.view.scale = scale;
  380. this.body.view.translation = {x:tx, y:ty};
  381. if (preScaleDragPointer != undefined) {
  382. let postScaleDragPointer = this.canvas.canvasToDOM(preScaleDragPointer);
  383. this.drag.pointer.x = postScaleDragPointer.x;
  384. this.drag.pointer.y = postScaleDragPointer.y;
  385. }
  386. this.body.emitter.emit('_requestRedraw');
  387. if (scaleOld < scale) {
  388. this.body.emitter.emit('zoom', {direction: '+', scale: this.body.view.scale});
  389. }
  390. else {
  391. this.body.emitter.emit('zoom', {direction: '-', scale: this.body.view.scale});
  392. }
  393. }
  394. }
  395. /**
  396. * Event handler for mouse wheel event, used to zoom the timeline
  397. * See http://adomas.org/javascript-mouse-wheel/
  398. * https://github.com/EightMedia/hammer.js/issues/256
  399. * @param {MouseEvent} event
  400. * @private
  401. */
  402. onMouseWheel(event) {
  403. // retrieve delta
  404. let delta = 0;
  405. if (event.wheelDelta) { /* IE/Opera. */
  406. delta = event.wheelDelta / 120;
  407. } else if (event.detail) { /* Mozilla case. */
  408. // In Mozilla, sign of delta is different than in IE.
  409. // Also, delta is multiple of 3.
  410. delta = -event.detail / 3;
  411. }
  412. // If delta is nonzero, handle it.
  413. // Basically, delta is now positive if wheel was scrolled up,
  414. // and negative, if wheel was scrolled down.
  415. if (delta !== 0) {
  416. // calculate the new scale
  417. let scale = this.body.view.scale;
  418. let zoom = delta / 10;
  419. if (delta < 0) {
  420. zoom = zoom / (1 - zoom);
  421. }
  422. scale *= (1 + zoom);
  423. // calculate the pointer location
  424. let pointer = this.getPointer({x:event.clientX, y:event.clientY});
  425. // apply the new scale
  426. this.zoom(scale, pointer);
  427. }
  428. // Prevent default actions caused by mouse wheel.
  429. event.preventDefault();
  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.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;