"use strict";

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

function _react() {
  const data = _interopRequireWildcard(require("react"));

  _react = function () {
    return data;
  };

  return data;
}

function _jsxRuntime() {
  const data = require("react/jsx-runtime");

  _jsxRuntime = function () {
    return data;
  };

  return data;
}

function _clsx() {
  const data = _interopRequireDefault(require("clsx"));

  _clsx = function () {
    return data;
  };

  return data;
}

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

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

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

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

const SwipeCell = (0, _react().forwardRef)((props, instanceRef) => {
  const {
    prefixCls,
    createNamespace
  } = (0, _react().useContext)(_ConfigProviderContext.default);
  const [bem] = createNamespace('swipe-cell', prefixCls);
  const opened = (0, _react().useRef)(false);
  const lockClick = (0, _react().useRef)(false);
  const startOffset = (0, _react().useRef)(0);
  const [state, setState] = (0, _react().useState)({
    offset: 0,
    dragging: false
  });
  const [actionWidth, setActionWidth] = (0, _react().useState)({
    left: 0,
    right: 0
  });
  const root = (0, _react().useRef)();

  const getWidthByNode = node => node ? (0, _useRect.getRect)(node).width : 0;

  const leftRef = (0, _react().useCallback)(node => {
    if (node !== null) {
      setActionWidth(v => Object.assign(Object.assign({}, v), {
        left: getWidthByNode(node)
      }));
    }
  }, []);
  const rightRef = (0, _react().useCallback)(node => {
    if (node !== null) {
      setActionWidth(v => Object.assign(Object.assign({}, v), {
        right: getWidthByNode(node)
      }));
    }
  }, []);
  const touch = (0, _hooks.useTouch)();
  const leftWidth = (0, _react().useMemo)(() => (0, _utils.isDef)(props.leftWidth) ? +props.leftWidth : actionWidth.left, [props.leftWidth, actionWidth.left]);
  const rightWidth = (0, _react().useMemo)(() => (0, _utils.isDef)(props.rightWidth) ? +props.rightWidth : actionWidth.right, [props.rightWidth, actionWidth.right]);

  const open = side => {
    var _a;

    opened.current = true;
    const offset = side === 'left' ? leftWidth : -rightWidth;
    (_a = props.onOpen) === null || _a === void 0 ? void 0 : _a.call(props, {
      name: props.name,
      position: side
    });
    setState(v => Object.assign(Object.assign({}, v), {
      offset
    }));
  };

  const close = position => {
    var _a;

    if (opened.current) {
      opened.current = false;
      (_a = props.onClose) === null || _a === void 0 ? void 0 : _a.call(props, {
        name: props.name,
        position
      });
    }

    setState(v => Object.assign(Object.assign({}, v), {
      offset: 0
    }));
  };

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

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

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

  const onTouchMove = event => {
    if (props.disabled) {
      return;
    }

    touch.move(event);

    if (touch.isHorizontal()) {
      lockClick.current = true;
      const newState = Object.assign(Object.assign({}, state), {
        dragging: true
      });
      const isEdge = !opened || touch.deltaX.current * startOffset.current < 0;

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

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

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

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

  const onClick = (position = 'outside') => {
    var _a;

    (_a = props.onClick) === null || _a === void 0 ? void 0 : _a.call(props, position);

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

  const getClickHandler = (position, stop) => event => {
    if (stop) {
      event.stopPropagation();
    }

    onClick(position);
  };

  const renderSideContent = (side, measuredRef) => {
    if (props[`${side}Action`]) {
      return (0, _jsxRuntime().jsx)("div", Object.assign({
        ref: measuredRef,
        className: (0, _clsx().default)(bem(side)),
        onClick: getClickHandler(side, true)
      }, {
        children: props[`${side}Action`]
      }));
    }

    return null;
  };

  (0, _useClickAway.default)(root, () => onClick('outside'), 'touchstart');
  (0, _react().useImperativeHandle)(instanceRef, () => ({
    open,
    close: () => close('outside')
  }));
  const 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 (0, _jsxRuntime().jsx)("div", Object.assign({
    ref: root,
    className: (0, _clsx().default)(bem()),
    onClick: getClickHandler('cell'),
    onTouchStart: onTouchStart,
    onTouchEnd: onTouchEnd,
    onTouchCancel: onTouchEnd
  }, {
    children: (0, _jsxRuntime().jsxs)("div", Object.assign({
      className: (0, _clsx().default)(bem('wrapper')),
      style: wrapperStyle
    }, {
      children: [renderSideContent('left', leftRef), props.children, renderSideContent('right', rightRef)]
    }))
  }));
});
SwipeCell.defaultProps = {
  name: ''
};
var _default = SwipeCell;
exports.default = _default;