'use strict';

var _rollupPluginBabelHelpers = require('./_rollupPluginBabelHelpers-ea66c137.js');
var React = require('react');
var MediaQueryContext = require('./MediaQueryContext-1dd78ce3.js');

const DEFAULT_DURATION = 300;
function preventDefault(e) {
  if (!isTouchEvent(e)) {
    return;
  }
  if (e.touches.length < 2 && e.preventDefault) {
    e.preventDefault();
  }
}
function isTouchEvent(e) {
  return e && 'touches' in e;
}
function useLongPress(_ref) {
  let {
    onLongPress,
    onClick
  } = _ref;
  let {
    delay = DEFAULT_DURATION,
    shouldPreventDefault = true,
    shouldStopPropagation = false
  } = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  const {
    isMobile
  } = MediaQueryContext.useMediaQueryContext();
  const [longPressTriggered, setLongPressTriggered] = React.useState(false);
  const [dragTriggered, setDragTriggered] = React.useState(false);
  // https://www.typescriptlang.org/docs/handbook/utility-types.html#returntypetype
  const timeout = React.useRef();
  const target = React.useRef();
  const start = React.useCallback(e => {
    e.persist();
    const clonedEvent = _rollupPluginBabelHelpers._objectSpread2({}, e);
    setDragTriggered(false);
    if (shouldStopPropagation) {
      e.stopPropagation();
    }
    if (shouldPreventDefault && e.target) {
      e.target.addEventListener('touchend', preventDefault, {
        passive: false
      });
      target.current = e.target;
    }
    timeout.current = setTimeout(() => {
      onLongPress(clonedEvent);
      setLongPressTriggered(true);
    }, delay);
  }, [onLongPress, delay, shouldPreventDefault, shouldStopPropagation, isMobile]);
  const clear = React.useCallback(function (e) {
    let shouldTriggerClick = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
    let onDrag = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
    if (onDrag) {
      setDragTriggered(true);
    } else {
      setDragTriggered(false);
    }
    if (timeout !== null && timeout !== void 0 && timeout.current) {
      clearTimeout(timeout.current);
    }
    if (shouldTriggerClick && !longPressTriggered && !dragTriggered) {
      onClick === null || onClick === void 0 ? void 0 : onClick(e);
    }
    setLongPressTriggered(false);
    if (shouldPreventDefault && target.current) {
      target.current.removeEventListener('touchend', preventDefault);
    }
  }, [shouldPreventDefault, onClick, longPressTriggered, dragTriggered]);
  return {
    onMouseDown: e => start(e),
    onMouseUp: e => clear(e),
    onMouseLeave: e => clear(e, false),
    onTouchStart: e => start(e),
    // setDragTriggered as true on touchmove, so that next onTouchEnd is ignored
    // if we dont do it, onClick?.(e) will be triggred, see inside clear()
    onTouchMove: e => clear(e, false, true),
    onTouchEnd: e => clear(e)
  };
}

exports.useLongPress = useLongPress;
//# sourceMappingURL=useLongPress-928530d4.js.map
