"use strict";

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

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

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

var _react = require("react");

var _events = _interopRequireDefault(require("../utils/events"));

var _hooks = require("../utils/hooks");

var isTouchEvent = function isTouchEvent(ev) {
  return 'touches' in ev;
};

var preventDefault = function preventDefault(ev) {
  if (!isTouchEvent(ev)) return;

  if (ev.touches.length < 2 && ev.preventDefault) {
    ev.preventDefault();
  }
};

var useLongPress = function useLongPress(_ref) {
  var _ref$isPreventDefault = _ref.isPreventDefault,
      isPreventDefault = _ref$isPreventDefault === void 0 ? true : _ref$isPreventDefault,
      _ref$delay = _ref.delay,
      delay = _ref$delay === void 0 ? 300 : _ref$delay,
      restProps = (0, _objectWithoutProperties2.default)(_ref, ["isPreventDefault", "delay"]);
  var onLongPress = restProps.onLongPress,
      onPress = restProps.onPress,
      onClear = restProps.onClear;
  var timeout = (0, _react.useRef)(0);
  var target = (0, _react.useRef)();
  var onLongPressRef = (0, _hooks.useLatest)(onLongPress);
  var onPressRef = (0, _hooks.useLatest)(onPress);
  var onClearRef = (0, _hooks.useLatest)(onClear);
  var startedRef = (0, _react.useRef)(false);
  var start = (0, _react.useCallback)(function (event) {
    // prevent ghost click on mobile devices
    if (isPreventDefault && event.target instanceof Element) {
      _events.default.on(event.target, 'touchend', preventDefault, {
        passive: false
      });

      target.current = event.target;
    }

    if (typeof onPressRef.current === 'function') {
      onPressRef.current(event);
    }

    if (typeof onLongPressRef.current === 'function') {
      timeout.current = window.setTimeout(function () {
        onLongPressRef.current(event);
      }, delay);
    }

    startedRef.current = true;
  }, [delay, isPreventDefault]);
  var clear = (0, _react.useCallback)(function (event) {
    if (!startedRef.current) {
      return;
    } // clearTimeout and removeEventListener


    if (timeout.current) {
      window.clearTimeout(timeout.current);
    }

    if (typeof onClearRef.current === 'function') {
      onClearRef.current(event);
    }

    if (isPreventDefault && target.current instanceof Element) {
      _events.default.off(target.current, 'touchend', preventDefault);
    }
  }, [isPreventDefault]);
  return {
    onTouchStart: start,
    onTouchEnd: clear,
    onMouseDown: start,
    onMouseUp: clear,
    onMouseLeave: clear
  };
};

var _default = useLongPress;
exports.default = _default;