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); }

import React, { forwardRef, useCallback, useContext, useImperativeHandle, useMemo, useRef, useState } from 'react';
import cls from 'clsx';
import { isDef, preventDefault, range } from '../utils';
import useTouch from '../hooks/use-touch';
import { getRect } from '../hooks/use-rect';
import { callInterceptor } from '../utils/interceptor';
import useClickAway from '../hooks/use-click-away';
import useEventListener from '../hooks/use-event-listener';
import ConfigProviderContext from '../config-provider/ConfigProviderContext';
var SwipeCell = /*#__PURE__*/forwardRef(function (props, instanceRef) {
  var _useContext = useContext(ConfigProviderContext),
      prefixCls = _useContext.prefixCls,
      createNamespace = _useContext.createNamespace;

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

  var opened = useRef(false);
  var lockClick = useRef(false);
  var startOffset = useRef(0);

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

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

  var root = useRef();

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

  var leftRef = useCallback(function (node) {
    if (node !== null) {
      setActionWidth(function (v) {
        return _extends({}, v, {
          left: getWidthByNode(node)
        });
      });
    }
  }, []);
  var rightRef = useCallback(function (node) {
    if (node !== null) {
      setActionWidth(function (v) {
        return _extends({}, v, {
          right: getWidthByNode(node)
        });
      });
    }
  }, []);
  var touch = useTouch();
  var leftWidth = useMemo(function () {
    return isDef(props.leftWidth) ? +props.leftWidth : actionWidth.left;
  }, [props.leftWidth, actionWidth.left]);
  var rightWidth = useMemo(function () {
    return 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) {
        preventDefault(event, props.stopPropagation);
      }

      newState.offset = 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) {
      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.createElement("div", {
        ref: measuredRef,
        className: cls(bem(side)),
        onClick: getClickHandler(side, true)
      }, props[side + "Action"]);
    }

    return null;
  };

  useClickAway(root, function () {
    return onClick('outside');
  }, 'touchstart');
  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'
  };
  useEventListener('touchmove', onTouchMove, {
    target: root.current,
    depends: [touch.deltaX]
  });
  return /*#__PURE__*/React.createElement("div", {
    ref: root,
    className: cls(bem()),
    onClick: getClickHandler('cell'),
    onTouchStart: onTouchStart,
    onTouchEnd: onTouchEnd,
    onTouchCancel: onTouchEnd
  }, /*#__PURE__*/React.createElement("div", {
    className: cls(bem('wrapper')),
    style: wrapperStyle
  }, renderSideContent('left', leftRef), props.children, renderSideContent('right', rightRef)));
});
SwipeCell.defaultProps = {
  name: ''
};
export default SwipeCell;