"use strict";

exports.__esModule = true;
exports.default = void 0;

var _react = _interopRequireWildcard(require("react"));

var _clsx = _interopRequireDefault(require("clsx"));

var _utils = require("../utils");

var _useTouch = _interopRequireDefault(require("../hooks/use-touch"));

var _useRect = require("../hooks/use-rect");

var _interceptor = require("../utils/interceptor");

var _useClickAway = _interopRequireDefault(require("../hooks/use-click-away"));

var _useEventListener = _interopRequireDefault(require("../hooks/use-event-listener"));

var _ConfigProviderContext = _interopRequireDefault(require("../config-provider/ConfigProviderContext"));

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }

function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }

var SwipeCell = /*#__PURE__*/(0, _react.forwardRef)(function (props, instanceRef) {
  var _useContext = (0, _react.useContext)(_ConfigProviderContext.default),
      prefixCls = _useContext.prefixCls,
      createNamespace = _useContext.createNamespace;

  var _createNamespace = createNamespace('swipe-cell', prefixCls),
      bem = _createNamespace[0];

  var opened = (0, _react.useRef)(false);
  var lockClick = (0, _react.useRef)(false);
  var startOffset = (0, _react.useRef)(0);

  var _useState = (0, _react.useState)({
    offset: 0,
    dragging: false
  }),
      state = _useState[0],
      setState = _useState[1];

  var _useState2 = (0, _react.useState)({
    left: 0,
    right: 0
  }),
      actionWidth = _useState2[0],
      setActionWidth = _useState2[1];

  var root = (0, _react.useRef)();

  var getWidthByNode = function getWidthByNode(node) {
    return node ? (0, _useRect.getRect)(node).width : 0;
  };

  var leftRef = (0, _react.useCallback)(function (node) {
    if (node !== null) {
      setActionWidth(function (v) {
        return _extends({}, v, {
          left: getWidthByNode(node)
        });
      });
    }
  }, []);
  var rightRef = (0, _react.useCallback)(function (node) {
    if (node !== null) {
      setActionWidth(function (v) {
        return _extends({}, v, {
          right: getWidthByNode(node)
        });
      });
    }
  }, []);
  var touch = (0, _useTouch.default)();
  var leftWidth = (0, _react.useMemo)(function () {
    return (0, _utils.isDef)(props.leftWidth) ? +props.leftWidth : actionWidth.left;
  }, [props.leftWidth, actionWidth.left]);
  var rightWidth = (0, _react.useMemo)(function () {
    return (0, _utils.isDef)(props.rightWidth) ? +props.rightWidth : actionWidth.right;
  }, [props.rightWidth, actionWidth.right]);

  var open = function open(side) {
    opened.current = true;
    var offset = side === 'left' ? leftWidth : -rightWidth;
    props.onOpen == null ? void 0 : props.onOpen({
      name: props.name,
      position: side
    });
    setState(function (v) {
      return _extends({}, v, {
        offset: offset
      });
    });
  };

  var _close = function close(position) {
    if (opened.current) {
      opened.current = false;
      props.onClose == null ? void 0 : props.onClose({
        name: props.name,
        position: position
      });
    }

    setState(function (v) {
      return _extends({}, v, {
        offset: 0
      });
    });
  };

  var toggle = function toggle(side) {
    var offset = Math.abs(state.offset);
    var THRESHOLD = 0.15;
    var threshold = opened ? 1 - THRESHOLD : THRESHOLD;
    var width = side === 'left' ? leftWidth : rightWidth;

    if (width && offset > width * threshold) {
      open(side);
    } else {
      _close(side);
    }
  };

  var onTouchStart = function onTouchStart(event) {
    if (!props.disabled) {
      startOffset.current = state.offset;
      touch.start(event);
    }
  };

  var onTouchMove = function onTouchMove(event) {
    if (props.disabled) {
      return;
    }

    var deltaX = touch.deltaX;
    touch.move(event);

    if (touch.isHorizontal()) {
      lockClick.current = true;

      var newState = _extends({}, state, {
        dragging: true
      });

      var isEdge = !opened || deltaX * startOffset.current < 0;

      if (isEdge) {
        (0, _utils.preventDefault)(event, props.stopPropagation);
      }

      newState.offset = (0, _utils.range)(deltaX + startOffset.current, -rightWidth, leftWidth);
      setState(newState);
    }
  };

  var onTouchEnd = function onTouchEnd() {
    if (state.dragging) {
      setState(function (v) {
        return _extends({}, v, {
          dragging: false
        });
      });
      toggle(state.offset > 0 ? 'left' : 'right'); // compatible with desktop scenario

      setTimeout(function () {
        lockClick.current = false;
      }, 0);
    }
  };

  var onClick = function onClick(position) {
    if (position === void 0) {
      position = 'outside';
    }

    props.onClick == null ? void 0 : props.onClick(position);

    if (opened.current && !lockClick.current) {
      (0, _interceptor.callInterceptor)({
        interceptor: props.beforeClose,
        args: [{
          name: props.name,
          position: position
        }],
        done: function done() {
          return _close(position);
        }
      });
    }
  };

  var getClickHandler = function getClickHandler(position, stop) {
    return function (event) {
      if (stop) {
        event.stopPropagation();
      }

      onClick(position);
    };
  };

  var renderSideContent = function renderSideContent(side, measuredRef) {
    if (props[side + "Action"]) {
      return /*#__PURE__*/_react.default.createElement("div", {
        ref: measuredRef,
        className: (0, _clsx.default)(bem(side)),
        onClick: getClickHandler(side, true)
      }, props[side + "Action"]);
    }

    return null;
  };

  (0, _useClickAway.default)(root, function () {
    return onClick('outside');
  }, 'touchstart');
  (0, _react.useImperativeHandle)(instanceRef, function () {
    return {
      open: open,
      close: function close() {
        return _close('outside');
      }
    };
  });
  var wrapperStyle = {
    transform: "translate3d(" + state.offset + "px, 0, 0)",
    transitionDuration: state.dragging ? '0s' : '.6s'
  };
  (0, _useEventListener.default)('touchmove', onTouchMove, {
    target: root.current,
    depends: [touch.deltaX]
  });
  return /*#__PURE__*/_react.default.createElement("div", {
    ref: root,
    className: (0, _clsx.default)(bem()),
    onClick: getClickHandler('cell'),
    onTouchStart: onTouchStart,
    onTouchEnd: onTouchEnd,
    onTouchCancel: onTouchEnd
  }, /*#__PURE__*/_react.default.createElement("div", {
    className: (0, _clsx.default)(bem('wrapper')),
    style: wrapperStyle
  }, renderSideContent('left', leftRef), props.children, renderSideContent('right', rightRef)));
});
SwipeCell.defaultProps = {
  name: ''
};
var _default = SwipeCell;
exports.default = _default;