import { _ as _async_to_generator } from "@swc/helpers/_/_async_to_generator";
import { _ as _define_property } from "@swc/helpers/_/_define_property";
import { _ as _object_spread } from "@swc/helpers/_/_object_spread";
import { _ as _object_spread_props } from "@swc/helpers/_/_object_spread_props";
import { _ as _sliced_to_array } from "@swc/helpers/_/_sliced_to_array";
import { _ as _ts_generator } from "@swc/helpers/_/_ts_generator";
import React, { forwardRef, useCallback, useEffect, useImperativeHandle, useRef, useState } from "react";
import classNames from "classnames";
import { View } from "@tarojs/components";
import { createSelectorQuery, nextTick, useReady } from "@tarojs/taro";
import { useTouch } from "../../hooks/use-touch";
import { ComponentDefaults } from "../../utils/typings";
import { harmony } from "../../utils/taro/platform";
import { useRefState } from "../../hooks/use-ref-state";
import { useUuid } from "../../hooks/use-uuid";
function preventDefault(event, isStopPropagation) {
    if (event.preventDefault && (typeof event.cancelable !== 'boolean' || event.cancelable)) {
        event.preventDefault();
    }
    if (isStopPropagation && event.stopPropagation) {
        event.stopPropagation();
    }
}
var defaultProps = _object_spread_props(_object_spread({}, ComponentDefaults), {
    name: ''
});
export var Swipe = /*#__PURE__*/ forwardRef(function(props, instanceRef) {
    var classPrefix = 'nut-swipe';
    var touch = useTouch();
    var uid = useUuid();
    var leftId = "swipe-left-".concat(uid);
    var rightId = "swipe-right-".concat(uid);
    var _$_object_spread = _object_spread({}, defaultProps, props), children = _$_object_spread.children, className = _$_object_spread.className, style = _$_object_spread.style;
    var root = useRef();
    var opened = useRef(false);
    var lockClick = useRef(false);
    var startOffset = useRef(0);
    var leftWrapper = useRef(null);
    var rightWrapper = useRef(null);
    var _useState = _sliced_to_array(useState({
        offset: 0,
        dragging: false
    }), 2), state = _useState[0], setState = _useState[1];
    var _useRefState = _sliced_to_array(useRefState({
        left: 0,
        right: 0
    }), 2), actionWidth = _useRefState[0], updateState = _useRefState[1];
    var setActionWidth = useCallback(function(side, width) {
        if (actionWidth.current[side] === width) return;
        updateState(_object_spread_props(_object_spread({}, actionWidth.current), _define_property({}, side, width)));
    }, [
        actionWidth,
        updateState
    ]);
    var getActionRect = function(element, id) {
        return new Promise(function(resolve) {
            if (!element) {
                resolve(null);
                return;
            }
            var query = createSelectorQuery();
            var scope = element === null || element === void 0 ? void 0 : element._scope;
            var scopedQuery = scope ? query.in(scope) : query;
            scopedQuery.select("#".concat(id)).boundingClientRect().exec(function() {
                var rect = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : [];
                resolve(rect[0] || null);
            });
        });
    };
    var getWidth = useCallback(function() {
        return _async_to_generator(function() {
            var leftRect, rightRect;
            return _ts_generator(this, function(_state) {
                switch(_state.label){
                    case 0:
                        if (!props.leftAction) return [
                            3,
                            2
                        ];
                        return [
                            4,
                            getActionRect(leftWrapper.current, leftId)
                        ];
                    case 1:
                        leftRect = _state.sent();
                        leftRect && setActionWidth('left', leftRect.width);
                        _state.label = 2;
                    case 2:
                        if (!props.rightAction) return [
                            3,
                            4
                        ];
                        return [
                            4,
                            getActionRect(rightWrapper.current, rightId)
                        ];
                    case 3:
                        rightRect = _state.sent();
                        rightRect && setActionWidth('right', rightRect.width);
                        _state.label = 4;
                    case 4:
                        return [
                            2
                        ];
                }
            });
        })();
    }, [
        leftId,
        props.leftAction,
        props.rightAction,
        rightId,
        setActionWidth
    ]);
    var getWidthRef = useRef(getWidth);
    useEffect(function() {
        getWidthRef.current = getWidth;
    }, [
        getWidth
    ]);
    // 页面 ready 后测量操作区域宽度，宽度未变化时不触发更新。
    useReady(function() {
        nextTick(function() {
            getWidthRef.current();
        });
    });
    var wrapperStyle = {
        transform: "translate(".concat(state.offset).concat(!harmony() ? 'px' : '', ", 0)"),
        transitionDuration: state.dragging ? '0s' : '.6s'
    };
    var onTouchStart = function(event) {
        return _async_to_generator(function() {
            var _props_onTouchStart;
            return _ts_generator(this, function(_state) {
                if (!props.disabled) {
                    ;
                    getWidth();
                    startOffset.current = state.offset;
                    touch.start(event);
                    (_props_onTouchStart = props.onTouchStart) === null || _props_onTouchStart === void 0 ? void 0 : _props_onTouchStart.call(props, event);
                }
                return [
                    2
                ];
            });
        })();
    };
    var onTouchMove = function(event) {
        var _props_onTouchMove;
        if (props.disabled) {
            return;
        }
        touch.move(event);
        (_props_onTouchMove = props.onTouchMove) === null || _props_onTouchMove === void 0 ? void 0 : _props_onTouchMove.call(props, event);
        if (touch.isHorizontal()) {
            lockClick.current = true;
            var newState = _object_spread_props(_object_spread({}, state), {
                dragging: true
            });
            var isEdge = !opened.current || touch.deltaX.current * startOffset.current < 0;
            if (isEdge) {
                preventDefault(event, true);
            }
            newState.offset = rangeCalculation(touch.deltaX.current + startOffset.current, -actionWidth.current.right || 0, actionWidth.current.left || 0);
            setState(newState);
        }
    };
    var onTouchEnd = function(event) {
        if (state.dragging) {
            var _props_onTouchEnd;
            setState(function(v) {
                return _object_spread_props(_object_spread({}, v), {
                    dragging: false
                });
            });
            toggle(state.offset > 0 ? 'left' : 'right');
            setTimeout(function() {
                lockClick.current = false;
            }, 0);
            (_props_onTouchEnd = props.onTouchEnd) === null || _props_onTouchEnd === void 0 ? void 0 : _props_onTouchEnd.call(props, event);
        }
    };
    var toggle = function(side) {
        var offset = Math.abs(state.offset);
        var base = 0.3;
        var baseNum = opened.current ? 1 - base : base;
        var width = side === 'left' ? actionWidth.current.left : actionWidth.current.right;
        if (width && offset > Number(width) * baseNum) {
            open(side);
        } else {
            close(side);
        }
    };
    var open = function(side) {
        var _props_onOpen;
        opened.current = true;
        var offset = side === 'left' ? actionWidth.current.left : -actionWidth.current.right;
        var name = props.name;
        (_props_onOpen = props.onOpen) === null || _props_onOpen === void 0 ? void 0 : _props_onOpen.call(props, {
            name: name,
            position: side
        });
        setState(function(v) {
            return _object_spread_props(_object_spread({}, v), {
                offset: Number(offset) || 0
            });
        });
    };
    var close = function(position) {
        if (opened.current) {
            var _props_onClose;
            opened.current = false;
            (_props_onClose = props.onClose) === null || _props_onClose === void 0 ? void 0 : _props_onClose.call(props, {
                name: props.name,
                position: position || 'left'
            });
        }
        setState(function(v) {
            return _object_spread_props(_object_spread({}, v), {
                offset: 0
            });
        });
    };
    var rangeCalculation = function(num, min, max) {
        return Math.min(Math.max(Number(num), Number(min)), Number(max));
    };
    var renderActionContent = function(side) {
        if (props["".concat(side, "Action")]) {
            return /*#__PURE__*/ React.createElement(View, {
                ref: side === 'left' ? leftWrapper : rightWrapper,
                className: "".concat(classPrefix, "-").concat(side),
                id: side === 'left' ? leftId : rightId,
                onClick: function(e) {
                    return handleOperate(e, side);
                }
            }, props["".concat(side, "Action")]);
        }
        return null;
    };
    var handleOperate = function(event, position) {
        event.stopPropagation();
        if (props.beforeClose) {
            props.beforeClose(position);
        } else {
            var _props_onActionClick;
            (_props_onActionClick = props.onActionClick) === null || _props_onActionClick === void 0 ? void 0 : _props_onActionClick.call(props, event, position);
        }
    };
    useImperativeHandle(instanceRef, function() {
        return {
            open: open,
            close: function() {
                return close();
            }
        };
    });
    useEffect(function() {
        if (harmony()) return;
        var handler = function(event) {
            var targets = [
                root
            ];
            if (targets.some(function(targetItem) {
                var targetElement = targetItem.current || targetItem;
                return !targetElement || (targetElement === null || targetElement === void 0 ? void 0 : targetElement.contains(event.target));
            })) {
                return;
            }
            close();
        };
        document.addEventListener('touchstart', handler);
        return function() {
            document.removeEventListener('touchstart', handler);
        };
    }, []);
    return /*#__PURE__*/ React.createElement(View, {
        ref: root,
        className: classNames(classPrefix, className),
        onTouchStart: function(e) {
            return onTouchStart(e);
        },
        onTouchMove: function(e) {
            return onTouchMove(e);
        },
        onTouchEnd: function(e) {
            return onTouchEnd(e);
        },
        style: style
    }, /*#__PURE__*/ React.createElement(View, {
        className: "".concat(classPrefix, "-wrapper"),
        style: wrapperStyle
    }, renderActionContent('left'), children, renderActionContent('right')));
});
Swipe.displayName = 'NutSwipe';
