"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = useMobileTouchMove;

var _supportsPassive = _interopRequireDefault(require("../../_util/supportsPassive"));

var _vue = require("vue");

var SMOOTH_PTG = 14 / 15;

function useMobileTouchMove(inVirtual, listRef, callback) {
  var touched = false;
  var touchY = 0;
  var element = null; // Smooth scroll

  var interval = null;

  var cleanUpEvents = function cleanUpEvents() {
    if (element) {
      element.removeEventListener('touchmove', onTouchMove, _supportsPassive.default ? {
        passive: false
      } : false);
      element.removeEventListener('touchend', onTouchEnd);
    }
  };

  var onTouchMove = function onTouchMove(e) {
    if (touched) {
      var currentY = Math.ceil(e.touches[0].pageY);

      var _offsetY = touchY - currentY;

      touchY = currentY;

      if (callback(_offsetY)) {
        e.preventDefault();
      } // Smooth interval


      clearInterval(interval);
      interval = setInterval(function () {
        _offsetY *= SMOOTH_PTG;

        if (!callback(_offsetY, true) || Math.abs(_offsetY) <= 0.1) {
          clearInterval(interval);
        }
      }, 16);
    }
  };

  var onTouchEnd = function onTouchEnd() {
    touched = false;
    cleanUpEvents();
  };

  var onTouchStart = function onTouchStart(e) {
    cleanUpEvents();

    if (e.touches.length === 1 && !touched) {
      touched = true;
      touchY = Math.ceil(e.touches[0].pageY);
      element = e.target;
      element.addEventListener('touchmove', onTouchMove, _supportsPassive.default ? {
        passive: false
      } : false);
      element.addEventListener('touchend', onTouchEnd);
    }
  };

  (0, _vue.onMounted)(function () {
    (0, _vue.watch)(inVirtual, function (val) {
      listRef.value.removeEventListener('touchstart', onTouchStart, _supportsPassive.default ? {
        passive: false
      } : false);
      cleanUpEvents();
      clearInterval(interval);

      if (val) {
        listRef.value.addEventListener('touchstart', onTouchStart, _supportsPassive.default ? {
          passive: false
        } : false);
      }
    }, {
      immediate: true
    });
  });
}