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.

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