"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
Object.defineProperty(exports, "Tabs", {
    enumerable: true,
    get: function() {
        return Tabs;
    }
});
var _interop_require_default = require("@swc/helpers/_/_interop_require_default");
var _interop_require_wildcard = require("@swc/helpers/_/_interop_require_wildcard");
var _define_property = require("@swc/helpers/_/_define_property");
var _object_spread = require("@swc/helpers/_/_object_spread");
var _object_spread_props = require("@swc/helpers/_/_object_spread_props");
var _object_without_properties = require("@swc/helpers/_/_object_without_properties");
var _sliced_to_array = require("@swc/helpers/_/_sliced_to_array");
var _react = /*#__PURE__*/ _interop_require_wildcard._(require("react"));
var _components = require("@tarojs/components");
var _classnames = /*#__PURE__*/ _interop_require_default._(require("classnames"));
var _iconsreacttaro = require("@nutui/icons-react-taro");
var _taro = /*#__PURE__*/ _interop_require_wildcard._(require("@tarojs/taro"));
var _typings = require("../../utils/typings");
var _index = /*#__PURE__*/ _interop_require_default._(require("../tabpane/index"));
var _usepropsvalue = require("../../hooks/use-props-value");
var _useforceupdate = require("../../hooks/use-force-update");
var _raf = /*#__PURE__*/ _interop_require_default._(require("../../utils/raf"));
var _useuuid = require("../../hooks/use-uuid");
var _configprovider = require("../configprovider/configprovider");
var _platform = require("../../utils/taro/platform");
var defaultProps = (0, _object_spread_props._)((0, _object_spread._)({}, _typings.ComponentDefaults), {
    tabStyle: {},
    activeColor: '',
    direction: 'horizontal',
    activeType: 'line',
    duration: 300,
    autoHeight: false
});
var classPrefix = 'nut-tabs';
var Tabs = function Tabs(props) {
    var rtl = (0, _configprovider.useRtl)();
    var _ref = (0, _object_spread._)({}, defaultProps, props), activeColor = _ref.activeColor, tabStyle = _ref.tabStyle, direction = _ref.direction, activeType = _ref.activeType, duration = _ref.duration, align = _ref.align, title = _ref.title, name = _ref.name, children = _ref.children, onClick = _ref.onClick, onChange = _ref.onChange, className = _ref.className, autoHeight = _ref.autoHeight, outerValue = _ref.value, outerDefaultValue = _ref.defaultValue, rest = (0, _object_without_properties._)(_ref, [
        "activeColor",
        "tabStyle",
        "direction",
        "activeType",
        "duration",
        "align",
        "title",
        "name",
        "children",
        "onClick",
        "onChange",
        "className",
        "autoHeight",
        "value",
        "defaultValue"
    ]);
    var uuid = (0, _useuuid.useUuid)();
    var tabsRef = (0, _react.useRef)(null);
    var _usePropsValue = (0, _sliced_to_array._)((0, _usepropsvalue.usePropsValue)({
        value: outerValue,
        defaultValue: outerDefaultValue,
        onChange: onChange
    }), 2), value = _usePropsValue[0], setValue = _usePropsValue[1];
    var titleItemsRef = (0, _react.useRef)([]);
    var getTitles = function getTitles() {
        var titles = [];
        _react.default.Children.forEach(children, function(child, idx) {
            if (/*#__PURE__*/ _react.default.isValidElement(child)) {
                var _$props = child.props;
                if ((_$props === null || _$props === void 0 ? void 0 : _$props.title) || (_$props === null || _$props === void 0 ? void 0 : _$props.value)) {
                    titles.push({
                        title: _$props.title,
                        value: _$props.value || idx,
                        disabled: _$props.disabled
                    });
                }
            }
        });
        return titles;
    };
    var titles = (0, _react.useRef)(getTitles());
    var forceUpdate = (0, _useforceupdate.useForceUpdate)();
    (0, _react.useEffect)(function() {
        titles.current = getTitles();
        var current = '';
        titles.current.forEach(function(title) {
            if (title.value === value) {
                current = value;
            }
        });
        if (current !== '' && current !== value) {
            setValue(current);
        } else {
            forceUpdate();
        }
    }, [
        children
    ]);
    var classes = (0, _classnames.default)(classPrefix, "".concat(classPrefix, "-").concat(direction), className);
    var _obj;
    var classesTitle = (0, _classnames.default)("".concat(classPrefix, "-titles"), (_obj = {}, (0, _define_property._)(_obj, "".concat(classPrefix, "-titles-").concat(activeType), activeType), (0, _define_property._)(_obj, "".concat(classPrefix, "-titles-").concat(align), align), _obj));
    var getRect = function getRect(selector) {
        return new Promise(function(resolve) {
            var _tabsRef_current;
            var query = (0, _taro.createSelectorQuery)();
            var scope = (_tabsRef_current = tabsRef.current) === null || _tabsRef_current === void 0 ? void 0 : _tabsRef_current._scope;
            var scopedQuery = scope ? query.in(scope) : query;
            scopedQuery.select(selector).boundingClientRect().exec(function() {
                var rect = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : [];
                resolve(rect[0]);
            });
        });
    };
    var getAllRect = function getAllRect(selector) {
        return new Promise(function(resolve) {
            var _tabsRef_current;
            var query = (0, _taro.createSelectorQuery)();
            var scope = (_tabsRef_current = tabsRef.current) === null || _tabsRef_current === void 0 ? void 0 : _tabsRef_current._scope;
            var scopedQuery = scope ? query.in(scope) : query;
            scopedQuery.selectAll(selector).boundingClientRect().exec(function() {
                var rect = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : [];
                resolve(rect[0]);
            });
        });
    };
    var scrollWithAnimation = (0, _react.useRef)(false);
    var _useState = (0, _sliced_to_array._)((0, _react.useState)(0), 2), scrollLeft = _useState[0], setScrollLeft = _useState[1];
    var _useState1 = (0, _sliced_to_array._)((0, _react.useState)(0), 2), scrollTop = _useState1[0], setScrollTop = _useState1[1];
    var scrollDirection = function scrollDirection(to, direction) {
        // 使用ScrollView组件此处不需要手动raf scrollLeft
        if (direction === 'horizontal') setScrollLeft(to);
        else setScrollTop(to);
    };
    var scrollIntoView = function scrollIntoView(index) {
        (0, _raf.default)(function() {
            Promise.all([
                getRect("#nut-tabs-titles-".concat(name || uuid)),
                getAllRect("#nut-tabs-titles-".concat(name || uuid, " .nut-tabs-titles-item"))
            ]).then(function(param) {
                var _param = (0, _sliced_to_array._)(param, 2), navRect = _param[0], titleRects = _param[1];
                var titleRect = titleRects[index];
                if (!titleRect) return;
                var to = 0;
                if (direction === 'vertical') {
                    var totalHeight = titleRects.reduce(function(sum, curr) {
                        return sum + curr.height;
                    }, 0);
                    var top = titleRects.slice(0, index).reduce(function(prev, curr) {
                        return prev + curr.height;
                    }, 0);
                    to = Math.min(Math.max(0, top - (navRect.height - titleRect.height) / 2), totalHeight - navRect.height);
                } else {
                    var totalWidth = titleRects.reduce(function(sum, curr) {
                        return sum + curr.width;
                    }, 0);
                    var left = titleRects.slice(0, index).reduce(function(prev, curr) {
                        return prev + curr.width;
                    }, 0);
                    to = Math.min(Math.max(0, left - (navRect.width - titleRect.width) / 2), totalWidth - navRect.width);
                }
                scrollDirection(to, direction);
                (0, _taro.nextTick)(function() {
                    scrollWithAnimation.current = true;
                });
            });
        });
    };
    var getContentStyle = function getContentStyle() {
        var index = titles.current.findIndex(function(t) {
            return String(t.value) === String(value);
        });
        index = index < 0 ? 0 : index;
        // 适配 安卓 处理，临时方案，hack
        if ((0, _platform.td)()) {
            return {
                transform: direction === 'horizontal' ? "translate3d(".concat(rtl ? '' : '-').concat(index * 50, "%, 0, 0)") : "translate3d( 0, -".concat(index * 50, "%, 0)"),
                transitionDuration: "".concat(duration, "ms")
            };
        }
        return {
            transform: direction === 'horizontal' ? "translate3d(".concat(rtl ? '' : '-').concat(index * 100, "%, 0, 0)") : "translate3d( 0, -".concat(index * 100, "%, 0)"),
            transitionDuration: "".concat(duration, "ms")
        };
    };
    (0, _react.useEffect)(function() {
        var index = titles.current.findIndex(function(t) {
            return String(t.value) === String(value);
        });
        index = index < 0 ? 0 : index;
        scrollIntoView(index);
    }, [
        value
    ]);
    var tabChange = function tabChange(item) {
        onClick && onClick(item.value);
        if (!item.disabled) {
            setValue(item.value);
        }
    };
    return /*#__PURE__*/ _react.default.createElement(_components.View, (0, _object_spread._)({
        className: classes,
        ref: tabsRef
    }, rest), /*#__PURE__*/ _react.default.createElement(_components.ScrollView, {
        enableFlex: true,
        scrollX: direction === 'horizontal',
        scrollY: direction === 'vertical',
        scrollLeft: scrollLeft,
        scrollTop: scrollTop,
        enhanced: true,
        showScrollbar: false,
        scrollWithAnimation: rtl && _taro.default.getEnv() !== 'WEB' ? false : scrollWithAnimation.current,
        id: "nut-tabs-titles-".concat(name || uuid),
        className: classesTitle,
        style: tabStyle
    }, /*#__PURE__*/ _react.default.createElement(_components.View, {
        className: "nut-tabs-list"
    }, !!title && typeof title === 'function' ? title() : titles.current.map(function(item, index) {
        var _obj;
        return /*#__PURE__*/ _react.default.createElement(_components.View, {
            key: item.value,
            ref: function ref(ref) {
                return titleItemsRef.current.push(ref);
            },
            id: "scrollIntoView".concat(index),
            onClick: function onClick() {
                return tabChange(item);
            },
            className: (0, _classnames.default)("".concat(classPrefix, "-titles-item"), (_obj = {}, (0, _define_property._)(_obj, "nut-tabs-titles-item-active", !item.disabled && String(item.value) === String(value)), (0, _define_property._)(_obj, "nut-tabs-titles-item-disabled", item.disabled), (0, _define_property._)(_obj, "nut-tabs-titles-item-".concat(align), align), _obj))
        }, activeType === 'line' && /*#__PURE__*/ _react.default.createElement(_components.View, {
            className: (0, _classnames.default)("".concat(classPrefix, "-titles-item-line"), "".concat(classPrefix, "-titles-item-line-").concat(direction)),
            style: {
                background: activeColor
            }
        }), activeType === 'smile' && /*#__PURE__*/ _react.default.createElement(_components.View, {
            className: "".concat(classPrefix, "-titles-item-smile")
        }, /*#__PURE__*/ _react.default.createElement(_iconsreacttaro.JoySmile, {
            color: activeColor,
            className: "".concat(classPrefix, "-titles-item-smile-icon")
        })), /*#__PURE__*/ _react.default.createElement(_components.View, {
            className: (0, _classnames.default)((0, _define_property._)({}, "".concat(classPrefix, "-ellipsis"), direction === 'vertical'), "".concat(classPrefix, "-titles-item-text")),
            style: {
                color: activeColor
            }
        }, item.title));
    }))), /*#__PURE__*/ _react.default.createElement(_components.View, {
        className: "".concat(classPrefix, "-content-wrap")
    }, /*#__PURE__*/ _react.default.createElement(_components.View, {
        className: "".concat(classPrefix, "-content"),
        style: getContentStyle()
    }, _react.default.Children.map(children, function(child, idx) {
        if (!/*#__PURE__*/ _react.default.isValidElement(child)) return null;
        return /*#__PURE__*/ _react.default.cloneElement(child, (0, _object_spread_props._)((0, _object_spread._)({}, child.props), {
            active: value === child.props.value,
            autoHeightClassName: autoHeight && String(value) !== String(child.props.value || idx) ? 'inactive' : undefined
        }));
    }))));
};
Tabs.displayName = 'NutTabs';
Tabs.TabPane = _index.default;
