useMobileTouchMove.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.default = useMobileTouchMove;
  6. var _vue = require("vue");
  7. const SMOOTH_PTG = 14 / 15;
  8. function useMobileTouchMove(inVirtual, listRef, callback) {
  9. let touched = false;
  10. let touchY = 0;
  11. let element = null;
  12. // Smooth scroll
  13. let interval = null;
  14. const cleanUpEvents = () => {
  15. if (element) {
  16. element.removeEventListener('touchmove', onTouchMove);
  17. element.removeEventListener('touchend', onTouchEnd);
  18. }
  19. };
  20. const onTouchMove = e => {
  21. if (touched) {
  22. const currentY = Math.ceil(e.touches[0].pageY);
  23. let offsetY = touchY - currentY;
  24. touchY = currentY;
  25. if (callback(offsetY)) {
  26. e.preventDefault();
  27. }
  28. // Smooth interval
  29. clearInterval(interval);
  30. interval = setInterval(() => {
  31. offsetY *= SMOOTH_PTG;
  32. if (!callback(offsetY, true) || Math.abs(offsetY) <= 0.1) {
  33. clearInterval(interval);
  34. }
  35. }, 16);
  36. }
  37. };
  38. const onTouchEnd = () => {
  39. touched = false;
  40. cleanUpEvents();
  41. };
  42. const onTouchStart = e => {
  43. cleanUpEvents();
  44. if (e.touches.length === 1 && !touched) {
  45. touched = true;
  46. touchY = Math.ceil(e.touches[0].pageY);
  47. element = e.target;
  48. element.addEventListener('touchmove', onTouchMove, {
  49. passive: false
  50. });
  51. element.addEventListener('touchend', onTouchEnd);
  52. }
  53. };
  54. const noop = () => {};
  55. (0, _vue.onMounted)(() => {
  56. document.addEventListener('touchmove', noop, {
  57. passive: false
  58. });
  59. (0, _vue.watch)(inVirtual, val => {
  60. listRef.value.removeEventListener('touchstart', onTouchStart);
  61. cleanUpEvents();
  62. clearInterval(interval);
  63. if (val) {
  64. listRef.value.addEventListener('touchstart', onTouchStart, {
  65. passive: false
  66. });
  67. }
  68. }, {
  69. immediate: true
  70. });
  71. });
  72. (0, _vue.onBeforeUnmount)(() => {
  73. document.removeEventListener('touchmove', noop);
  74. });
  75. }