function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
function _extends() { _extends = Object.assign ? Object.assign.bind() : 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); }
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
import { animated, useSpring } from '@react-spring/web';
import { useDrag } from '@use-gesture/react/dist/use-gesture-react.cjs';
import React, { forwardRef, useEffect, useImperativeHandle, useRef, useState } from 'react';

// 本地实现的工具函数和类型

// withNativeProps 工具函数
function withNativeProps(props, element) {
  var p = _objectSpread({}, element.props);
  if (props.className) {
    p.className = props.className + (element.props.className ? " ".concat(element.props.className) : '');
  }
  if (props.style) {
    p.style = _objectSpread(_objectSpread({}, props.style), element.props.style);
  }
  return /*#__PURE__*/React.cloneElement(element, p);
}

// nearest 工具函数
function nearest(arr, target) {
  return arr.reduce(function (prev, curr) {
    return Math.abs(curr - target) < Math.abs(prev - target) ? curr : prev;
  });
}

// mergeProps 工具函数
function mergeProps(a, b) {
  return _objectSpread(_objectSpread({}, a), b);
}

// withStopPropagation 工具函数
function withStopPropagation(events, element) {
  if (!events.includes('click')) {
    return element;
  }
  var onClick = function onClick(e) {
    var _element$props$onClic, _element$props;
    e.stopPropagation();
    (_element$props$onClic = (_element$props = element.props).onClick) === null || _element$props$onClic === void 0 || _element$props$onClic.call(_element$props, e);
  };
  return /*#__PURE__*/React.cloneElement(element, _objectSpread(_objectSpread({}, element.props), {}, {
    onClick: onClick
  }));
}

// Button 组件实现

var Button = function Button(_ref) {
  var children = _ref.children,
    className = _ref.className,
    style = _ref.style,
    onClick = _ref.onClick;
  return /*#__PURE__*/React.createElement("button", {
    className: className,
    style: _objectSpread({
      border: 'none',
      background: (style === null || style === void 0 ? void 0 : style['--background-color']) || 'transparent'
    }, style),
    onClick: onClick
  }, children);
};
import "./index.less";
var classPrefix = "pisell-custom-swipe-action";
var defaultProps = {
  rightActions: [],
  leftActions: [],
  closeOnTouchOutside: true,
  closeOnAction: true,
  stopPropagation: []
};
export var SwipeAction = /*#__PURE__*/forwardRef(function (p, ref) {
  var props = mergeProps(defaultProps, p);
  var rootRef = useRef(null);
  var leftRef = useRef(null);
  var rightRef = useRef(null);

  // 添加容器高度状态
  var _useState = useState(0),
    _useState2 = _slicedToArray(_useState, 2),
    containerHeight = _useState2[0],
    setContainerHeight = _useState2[1];
  function getWidth(ref) {
    var element = ref.current;
    if (!element) return 0;
    return element.offsetWidth;
  }

  // 添加获取高度的函数
  function getHeight(ref) {
    var element = ref.current;
    if (!element) return 0;
    return element.offsetHeight;
  }
  function getLeftWidth() {
    return getWidth(leftRef);
  }
  function getRightWidth() {
    return getWidth(rightRef);
  }

  // 添加获取根容器高度的函数
  function getRootHeight() {
    return getHeight(rootRef);
  }
  var _useSpring = useSpring(function () {
      return {
        x: 0,
        config: {
          tension: 200,
          friction: 30
        }
      };
    }, []),
    _useSpring2 = _slicedToArray(_useSpring, 2),
    x = _useSpring2[0].x,
    api = _useSpring2[1];
  var draggingRef = useRef(false);
  var dragCancelRef = useRef(null);
  function forceCancelDrag() {
    var _dragCancelRef$curren;
    (_dragCancelRef$curren = dragCancelRef.current) === null || _dragCancelRef$curren === void 0 || _dragCancelRef$curren.call(dragCancelRef);
    draggingRef.current = false;
  }
  var bind = useDrag(function (state) {
    dragCancelRef.current = state.cancel;
    if (!state.intentional) return;
    if (state.down) {
      draggingRef.current = true;
    }
    if (!draggingRef.current) return;
    var _state$offset = _slicedToArray(state.offset, 1),
      offsetX = _state$offset[0];
    if (state.last) {
      var leftWidth = getLeftWidth();
      var rightWidth = getRightWidth();
      var position = offsetX + state.velocity[0] * state.direction[0] * 50;
      if (offsetX > 0) {
        position = Math.max(0, position);
      } else if (offsetX < 0) {
        position = Math.min(0, position);
      } else {
        position = 0;
      }
      var targetX = nearest([-rightWidth, 0, leftWidth], position);
      api.start({
        x: targetX
      });
      if (targetX !== 0) {
        var _p$onActionsReveal;
        (_p$onActionsReveal = p.onActionsReveal) === null || _p$onActionsReveal === void 0 || _p$onActionsReveal.call(p, targetX > 0 ? 'left' : 'right');
      }
      window.setTimeout(function () {
        draggingRef.current = false;
      });
    } else {
      api.start({
        x: offsetX,
        immediate: true
      });
    }
  }, {
    from: function from() {
      return [x.get(), 0];
    },
    bounds: function bounds() {
      var leftWidth = getLeftWidth();
      var rightWidth = getRightWidth();
      return {
        left: -rightWidth,
        right: leftWidth
      };
    },
    axis: 'x',
    preventScroll: true,
    pointer: {
      touch: true
    },
    triggerAllEvents: true
  });
  var close = function close() {
    var _props$onClose;
    api.start({
      x: 0
    });
    forceCancelDrag();
    (_props$onClose = props.onClose) === null || _props$onClose === void 0 || _props$onClose.call(props);
  };
  useImperativeHandle(ref, function () {
    return {
      show: function show() {
        var _p$onActionsReveal2;
        var side = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'right';
        if (side === 'right') {
          api.start({
            x: -getRightWidth()
          });
        } else if (side === 'left') {
          api.start({
            x: getLeftWidth()
          });
        }
        (_p$onActionsReveal2 = p.onActionsReveal) === null || _p$onActionsReveal2 === void 0 || _p$onActionsReveal2.call(p, side);
      },
      close: close
    };
  });

  // 添加高度检测的 useEffect
  useEffect(function () {
    var updateHeight = function updateHeight() {
      var height = getRootHeight();
      setContainerHeight(height);
    };

    // 组件挂载后检测高度
    updateHeight();

    // 监听窗口大小变化
    var resizeObserver = new ResizeObserver(updateHeight);
    if (rootRef.current) {
      resizeObserver.observe(rootRef.current);
    }
    return function () {
      resizeObserver.disconnect();
    };
  }, []);
  useEffect(function () {
    if (!props.closeOnTouchOutside) return;
    function handle(e) {
      // 检查点击的元素或其祖先元素是否有特定 class
      if (e.target && props.escapeDom) {
        var container = document.querySelector(props.escapeDom);
        if (container !== null && container !== void 0 && container.contains(e.target)) return;
      }
      if (x.get() === 0) {
        return;
      }
      var root = rootRef.current;
      if (root && !root.contains(e.target)) {
        close();
      }
    }
    if ('ontouchstart' in window) {
      document.addEventListener('touchstart', handle);
    } else {
      document.addEventListener('mousedown', handle);
    }
    return function () {
      document.removeEventListener('touchstart', handle);
      document.removeEventListener('mousedown', handle);
    };
  }, [props.closeOnTouchOutside, props.escapeDom]);

  // 根据容器高度获取右侧容器的 class 名称
  var getRightContainerClass = function getRightContainerClass() {
    var baseClass = "".concat(classPrefix, "-actions ").concat(classPrefix, "-actions-right");
    if (containerHeight > 180) {
      return "".concat(baseClass, " ").concat(classPrefix, "-height-large");
    } else if (containerHeight > 120) {
      return "".concat(baseClass, " ").concat(classPrefix, "-height-medium");
    }
    return "".concat(baseClass, " ").concat(classPrefix, "-height-small");
  };

  // 根据容器高度获取右侧按钮的 class 名称
  var getRightActionButtonClass = function getRightActionButtonClass() {
    if (containerHeight > 180) {
      return "".concat(classPrefix, "-action-height-large");
    } else if (containerHeight > 120) {
      return "".concat(classPrefix, "-action-height-medium");
    }
    return "".concat(classPrefix, "-action-height-small");
  };
  function renderAction(action) {
    var _action$color, _colorRecord$color;
    var isRightAction = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
    var color = (_action$color = action.color) !== null && _action$color !== void 0 ? _action$color : 'light';
    var _style = action.style || {};

    // 为右侧按钮添加基于高度的 class
    var buttonClass = isRightAction ? "".concat(classPrefix, "-action-button ").concat(getRightActionButtonClass()) : "".concat(classPrefix, "-action-button");
    return /*#__PURE__*/React.createElement(Button, {
      key: action.key,
      className: buttonClass,
      style: _objectSpread({
        '--background-color': (_colorRecord$color = colorRecord[color]) !== null && _colorRecord$color !== void 0 ? _colorRecord$color : color
      }, _style),
      onClick: function onClick(e) {
        var _action$onClick, _props$onAction;
        if (props.closeOnAction) {
          close();
        }
        (_action$onClick = action.onClick) === null || _action$onClick === void 0 || _action$onClick.call(action, e);
        (_props$onAction = props.onAction) === null || _props$onAction === void 0 || _props$onAction.call(props, action, e);
      }
    }, action.text);
  }
  return withNativeProps(props, /*#__PURE__*/React.createElement("div", _extends({
    className: classPrefix
  }, bind(), {
    ref: rootRef,
    onClickCapture: function onClickCapture(e) {
      if (draggingRef.current) {
        e.stopPropagation();
        e.preventDefault();
      }
    }
  }), /*#__PURE__*/React.createElement(animated.div, {
    className: "".concat(classPrefix, "-track"),
    style: {
      x: x
    }
  }, withStopPropagation(props.stopPropagation, /*#__PURE__*/React.createElement("div", {
    className: "".concat(classPrefix, "-actions ").concat(classPrefix, "-actions-left"),
    ref: leftRef
  }, props.leftActions.map(function (action) {
    return renderAction(action, false);
  }))), /*#__PURE__*/React.createElement("div", {
    className: "".concat(classPrefix, "-content"),
    onClickCapture: function onClickCapture(e) {
      if (x.goal !== 0) {
        e.preventDefault();
        e.stopPropagation();
        close();
      }
    }
  }, /*#__PURE__*/React.createElement(animated.div, {
    style: {
      pointerEvents: x.to(function (v) {
        return v !== 0 && x.goal !== 0 ? 'none' : 'auto';
      })
    }
  }, props.children)), withStopPropagation(props.stopPropagation, /*#__PURE__*/React.createElement("div", {
    className: getRightContainerClass(),
    ref: rightRef
  }, props.rightActions.map(function (action) {
    return renderAction(action, true);
  }))))));
});
var colorRecord = {
  light: '#ccc',
  weak: '#999',
  primary: '#1677ff',
  success: '#00b578',
  warning: '#ff8f1f',
  danger: '#ff3141'
};