"use strict";

exports.__esModule = true;
exports.default = void 0;

var _react = _interopRequireWildcard(require("react"));

var _clsx = _interopRequireDefault(require("clsx"));

var _useRefs3 = _interopRequireDefault(require("../hooks/use-refs"));

var _useScrollParent = _interopRequireDefault(require("../hooks/use-scroll-parent"));

var _useWindowSize = _interopRequireDefault(require("../hooks/use-window-size"));

var _sticky = _interopRequireDefault(require("../sticky"));

var _TabsTitle = _interopRequireDefault(require("./TabsTitle"));

var _TabsContent = _interopRequireDefault(require("./TabsContent"));

var _TabsContext = _interopRequireDefault(require("./TabsContext"));

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

var _interceptor = require("../utils/interceptor");

var _constant = require("../utils/constant");

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

var _useEventListener = _interopRequireDefault(require("../hooks/use-event-listener"));

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

var _ConfigProviderContext = _interopRequireDefault(require("../config-provider/ConfigProviderContext"));

var _PopupContext = _interopRequireDefault(require("../popup/PopupContext"));

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

var Tabs = /*#__PURE__*/(0, _react.forwardRef)(function (props, ref) {
  var _useContext = (0, _react.useContext)(_ConfigProviderContext.default),
      prefixCls = _useContext.prefixCls,
      createNamespace = _useContext.createNamespace;

  var popupContext = (0, _react.useContext)(_PopupContext.default);

  var _createNamespace = createNamespace('tabs', prefixCls),
      bem = _createNamespace[0];

  var children = props.children,
      color = props.color,
      align = props.align,
      background = props.background;
  var root = (0, _react.useRef)(null);
  var swiperRef = (0, _react.useRef)(null);

  var _useState = (0, _react.useState)(null),
      wrapRef = _useState[0],
      setWrapRef = _useState[1];

  var initChange = (0, _react.useRef)(false);
  var lockScroll = (0, _react.useRef)(false);
  var stickyFixed = (0, _react.useRef)(false);
  var navRef = (0, _react.useRef)(null);
  var scroller = (0, _useScrollParent.default)(root);
  var windowSize = (0, _useWindowSize.default)();

  var _useRefs = (0, _useRefs3.default)(),
      titleRefs = _useRefs[0],
      setTitleRefs = _useRefs[1];

  var _useRefs2 = (0, _useRefs3.default)(),
      contentRefs = _useRefs2[0],
      setContentRefs = _useRefs2[1];

  var tabHeight = (0, _react.useMemo)(function () {
    if (!wrapRef) return 0;
    return (0, _utils.getVisibleHeight)(wrapRef);
  }, [wrapRef]);
  var tabHeightRef = (0, _react.useRef)(tabHeight);
  tabHeightRef.current = tabHeight;

  var _useSetState = (0, _hooks.useSetState)({
    inited: false,
    position: '',
    currentIndex: -1,
    lineStyle: {
      backgroundColor: props.color
    }
  }),
      state = _useSetState[0],
      setState = _useSetState[1];

  var childrenList = (0, _react.useMemo)(function () {
    return (0, _utils.parseChildList)(props.children);
  }, [props.children]); // whether the nav is scrollable

  var scrollable = (0, _react.useMemo)(function () {
    return childrenList.length > props.swipeThreshold || !props.ellipsis;
  }, [childrenList.length, props.swipeThreshold, props.ellipsis]);
  var navStyle = (0, _react.useMemo)(function () {
    return {
      borderColor: color,
      background: background
    };
  }, [color, background]);

  var getTabName = function getTabName(tab, index) {
    var _tab$name;

    return (_tab$name = tab == null ? void 0 : tab.name) != null ? _tab$name : index;
  };

  var currentName = (0, _react.useMemo)(function () {
    var activeTab = childrenList[state.currentIndex];
    return activeTab ? getTabName(activeTab, state.currentIndex) : 0;
  }, [childrenList, state.currentIndex]);
  var offsetTopPx = (0, _react.useMemo)(function () {
    return (0, _utils.unitToPx)(props.offsetTop);
  }, [props.offsetTop]); // scroll active tab into view

  var scrollIntoView = function scrollIntoView(immediate) {
    var nav = navRef.current;

    if (!scrollable || !nav || !titleRefs || !titleRefs[state.currentIndex]) {
      return;
    }

    var title = titleRefs[state.currentIndex];
    var to = title.offsetLeft - (nav.offsetWidth - title.offsetWidth) / 2;
    (0, _utils.scrollLeftTo)(nav, to, immediate ? 0 : +props.duration);
  };

  var setLine = function setLine(immediate) {
    var shouldAnimate = state.inited;
    if (immediate) shouldAnimate = false;
    var titles = titleRefs;
    var hidden = (0, _utils.isHidden)(root.current);

    if (!titles || !titles[state.currentIndex] || props.type !== 'line' || hidden) {
      return;
    }

    var title = titles[state.currentIndex];
    var lineWidth = props.lineWidth,
        lineHeight = props.lineHeight;
    var left = title.offsetLeft + title.offsetWidth / 2;
    var lineStyle = {
      width: (0, _utils.addUnit)(lineWidth),
      backgroundColor: props.color,
      transform: "translateX(" + left + "px) translateX(-50%)"
    };

    if (shouldAnimate) {
      lineStyle.transitionDuration = props.duration + "ms";
    }

    if ((0, _utils.isDef)(lineHeight)) {
      var height = (0, _utils.addUnit)(lineHeight);
      lineStyle.height = height;
      lineStyle.borderRadius = height;
    }

    setState({
      lineStyle: lineStyle
    });
  };

  var findAvailableTab = function findAvailableTab(index) {
    var diff = index < state.currentIndex ? -1 : 1;

    while (index >= 0 && index < childrenList.length) {
      if (!childrenList[index].disabled) {
        return index;
      }

      index += diff;
    }

    return null;
  };

  var setCurrentIndex = function setCurrentIndex(currentIndex) {
    var newIndex = findAvailableTab(currentIndex);

    if (!(0, _utils.isDef)(newIndex)) {
      return;
    }

    var newTab = childrenList[newIndex];
    var newName = getTabName(newTab, newIndex);
    var shouldEmitChange = state.currentIndex !== null;
    setState({
      currentIndex: newIndex
    });

    if (!initChange.current) {
      initChange.current = true;
      return;
    }

    if (initChange.current) {
      if (shouldEmitChange) {
        props.onChange == null ? void 0 : props.onChange(newName, newTab.title);
      }
    }
  }; // correct the index of active tab


  var setCurrentIndexByName = function setCurrentIndexByName(name) {
    var currentIndex = childrenList.findIndex(function (tab, index) {
      return getTabName(tab, index) === name;
    });
    setCurrentIndex(currentIndex < 0 ? 0 : currentIndex);
  };

  var scrollToCurrentContent = function scrollToCurrentContent(immediate, current) {
    if (props.scrollspy) {
      var target = contentRefs[current != null ? current : state.currentIndex];

      if (target && scroller) {
        var to = (0, _utils.getElementTop)(target, scroller) - (offsetTopPx + tabHeightRef.current);
        lockScroll.current = true;
        (0, _utils.scrollTopTo)(scroller, to, immediate ? 0 : +props.duration, function () {
          lockScroll.current = false;
        });
      }
    }
  };

  var onClickTab = function onClickTab(item, index, event) {
    var title = item.title,
        _item$disabled = item.disabled,
        disabled = _item$disabled === void 0 ? false : _item$disabled;
    var name = getTabName(item, index);
    props.onClickTab == null ? void 0 : props.onClickTab({
      name: name,
      title: title,
      event: event,
      disabled: disabled
    });
    if (disabled) return;
    (0, _interceptor.callInterceptor)({
      interceptor: props.beforeChange,
      args: [name],
      done: function done() {
        if (index !== state.currentIndex) {
          setCurrentIndex(index);
          scrollToCurrentContent(false, index);
        }
      }
    });
  };

  var scrollTo = function scrollTo(name) {
    setCurrentIndexByName(name);
    scrollToCurrentContent(true);
  };

  var getCurrentIndexOnScroll = function getCurrentIndexOnScroll() {
    var scrollOffset = offsetTopPx + tabHeightRef.current; // eslint-disable-next-line no-plusplus

    for (var index = 0; index < contentRefs.length; index++) {
      var $el = contentRefs[index];
      var top = (0, _utils.getVisibleTop)($el);

      if (top > scrollOffset) {
        return index === 0 ? 0 : index - 1;
      }
    }

    return titleRefs.length - 1;
  };

  var onScroll = function onScroll() {
    if (props.scrollspy && !lockScroll.current) {
      var index = getCurrentIndexOnScroll();

      if (typeof props.scrollspy === 'object') {
        if (props.scrollspy.autoFocusLast && (0, _utils2.isReachBottom)(props.scrollspy.reachBottomThreshold)) {
          index = titleRefs.length - 1;
        }
      }

      if (index !== state.currentIndex) {
        setCurrentIndex(index);
      }
    }
  };

  var onStickyScroll = function onStickyScroll(params) {
    stickyFixed.current = params.isFixed;
    props.onScroll == null ? void 0 : props.onScroll(params);
  };

  var renderNav = function renderNav() {
    return childrenList.map(function (item, index) {
      return /*#__PURE__*/_react.default.createElement(_TabsTitle.default, {
        ref: setTitleRefs(index),
        key: item.key,
        dot: item.dot,
        type: props.type,
        badge: item.badge,
        title: item.title,
        color: props.color,
        style: item.titleStyle,
        className: item.titleClass,
        isActive: index === state.currentIndex,
        disabled: item.disabled,
        scrollable: scrollable,
        renderTitle: item.renderTitle,
        activeColor: props.titleActiveColor,
        inactiveColor: props.titleInactiveColor,
        showZeroBadge: item.showZeroBadge,
        onClick: function onClick(event) {
          onClickTab(item, index, event);
        }
      });
    });
  };

  var renderHeader = function renderHeader() {
    var _ref;

    var type = props.type,
        border = props.border;
    return /*#__PURE__*/_react.default.createElement("div", {
      ref: setWrapRef,
      className: (0, _clsx.default)([bem('wrap', {
        scrollable: scrollable
      }), (_ref = {}, _ref[_constant.BORDER_TOP_BOTTOM] = type === 'line' && border, _ref)])
    }, /*#__PURE__*/_react.default.createElement("div", {
      ref: navRef,
      role: "tablist",
      className: (0, _clsx.default)(bem('nav', [type, {
        complete: scrollable,
        start: align === 'start'
      }])),
      style: navStyle
    }, props.navRight, renderNav(), type === 'line' && /*#__PURE__*/_react.default.createElement("div", {
      className: (0, _clsx.default)(bem('line')),
      style: state.lineStyle
    }), props.navRight));
  };

  (0, _hooks.useUpdateEffect)(function () {
    setLine();
  }, [props.color, windowSize.width]);
  (0, _hooks.useUpdateEffect)(function () {
    if (props.active !== currentName) {
      setCurrentIndexByName(props.active);
    }
  }, [props.active]);
  (0, _hooks.useUpdateEffect)(function () {
    if (state.inited) {
      setCurrentIndexByName(props.active || currentName);
      setLine();
      scrollIntoView(true);
    }
  }, [_react.default.Children.count(children)]);
  (0, _hooks.useUpdateEffect)(function () {
    scrollIntoView();
    setLine(); // scroll to correct position

    if (stickyFixed.current && props.stickyInitScrollbar && !props.scrollspy) {
      (0, _utils.setRootScrollTop)(Math.ceil((0, _utils.getElementTop)(root.current) - offsetTopPx));
    }
  }, [state.currentIndex]);

  var init = function init() {
    setCurrentIndexByName(props.active);
    scrollIntoView(true);
    setState({
      inited: true
    });
  };

  (0, _react.useEffect)(function () {
    init();
  }, []);
  (0, _hooks.useUpdateEffect)(function () {
    if (popupContext.visible) {
      setLine();
    }
  }, [popupContext.visible]);
  (0, _useEventListener.default)('scroll', onScroll, {
    target: scroller,
    depends: [state.currentIndex]
  });
  (0, _react.useImperativeHandle)(ref, function () {
    var _swiperRef$current, _swiperRef$current2;

    return {
      resize: setLine,
      scrollTo: scrollTo,
      swiper: swiperRef.current ? {
        enable: (_swiperRef$current = swiperRef.current) == null ? void 0 : _swiperRef$current.enable,
        disable: (_swiperRef$current2 = swiperRef.current) == null ? void 0 : _swiperRef$current2.disable
      } : undefined
    };
  });

  var onStickyChange = function onStickyChange() {
    setLine(true);
  };

  return /*#__PURE__*/_react.default.createElement(_TabsContext.default.Provider, {
    value: {
      props: props,
      currentName: currentName,
      scrollIntoView: scrollIntoView,
      setLine: setLine
    }
  }, /*#__PURE__*/_react.default.createElement("div", {
    ref: root,
    className: (0, _clsx.default)(props.className, bem([props.type]))
  }, props.sticky ? /*#__PURE__*/_react.default.createElement(_sticky.default, {
    container: root,
    offsetTop: offsetTopPx,
    onChange: onStickyChange,
    onScroll: onStickyScroll
  }, renderHeader(), props.navBottom) : /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, renderHeader(), props.navBottom), /*#__PURE__*/_react.default.createElement(_TabsContent.default, {
    swiperRef: swiperRef,
    count: childrenList.length,
    inited: state.inited,
    animated: props.animated,
    duration: props.duration,
    swipeable: props.swipeable,
    lazyRender: props.lazyRender,
    currentIndex: state.currentIndex,
    onChange: setCurrentIndex
  }, _react.default.Children.toArray(children).filter(Boolean).map(function (node, index) {
    return /*#__PURE__*/_react.default.cloneElement(node, {
      index: index,
      ref: setContentRefs(index)
    });
  }))));
});
Tabs.defaultProps = {
  type: 'line',
  duration: 300,
  swipeThreshold: 5,
  offsetTop: 0,
  ellipsis: true,
  lazyRender: true,
  stickyInitScrollbar: true,
  active: 0,
  align: 'center'
};
var _default = Tabs;
exports.default = _default;