"use strict";

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

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

  _jsxRuntime = function () {
    return data;
  };

  return data;
}

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

  _react = function () {
    return data;
  };

  return data;
}

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

  _clsx = function () {
    return data;
  };

  return data;
}

var _useRefs = _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 (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 Tabs = (0, _react().forwardRef)((props, ref) => {
  const {
    prefixCls,
    createNamespace
  } = (0, _react().useContext)(_ConfigProviderContext.default);
  const popupContext = (0, _react().useContext)(_PopupContext.default);
  const [bem] = createNamespace('tabs', prefixCls);
  const {
    children,
    color,
    align,
    background
  } = props;
  const root = (0, _react().useRef)(null);
  const swiperRef = (0, _react().useRef)(null);
  const [wrapRef, setWrapRef] = (0, _react().useState)(null);
  const initChange = (0, _react().useRef)(false);
  const lockScroll = (0, _react().useRef)(false);
  const stickyFixed = (0, _react().useRef)(false);
  const navRef = (0, _react().useRef)(null);
  const scroller = (0, _useScrollParent.default)(root);
  const windowSize = (0, _useWindowSize.default)();
  const [titleRefs, setTitleRefs] = (0, _useRefs.default)();
  const [contentRefs, setContentRefs] = (0, _useRefs.default)();
  const tabHeight = (0, _react().useMemo)(() => {
    if (!wrapRef) return 0;
    return (0, _utils.getVisibleHeight)(wrapRef);
  }, [wrapRef]);
  const tabHeightRef = (0, _react().useRef)(tabHeight);
  tabHeightRef.current = tabHeight;
  const [state, setState] = (0, _hooks.useSetState)({
    inited: false,
    position: '',
    currentIndex: -1,
    lineStyle: {
      backgroundColor: props.color
    }
  });
  const childrenList = (0, _react().useMemo)(() => (0, _utils.parseChildList)(props.children), [props.children]); // whether the nav is scrollable

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

  const getTabName = (tab, index) => {
    var _a;

    return (_a = tab === null || tab === void 0 ? void 0 : tab.name) !== null && _a !== void 0 ? _a : index;
  };

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

  const scrollIntoView = immediate => {
    const nav = navRef.current;

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

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

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

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

    const title = titles[state.currentIndex];
    const {
      lineWidth,
      lineHeight
    } = props;
    const left = title.offsetLeft + title.offsetWidth / 2;
    const 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)) {
      const height = (0, _utils.addUnit)(lineHeight);
      lineStyle.height = height;
      lineStyle.borderRadius = height;
    }

    setState({
      lineStyle
    });
  };

  const findAvailableTab = (index, initial) => {
    var _a;

    const diff = index < state.currentIndex ? -1 : 1;

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

      if (!((_a = childrenList[index]) === null || _a === void 0 ? void 0 : _a.disabled)) {
        return index;
      }

      index += diff;
    }

    return null;
  };

  const setCurrentIndex = (currentIndex, initial) => {
    var _a;

    const newIndex = findAvailableTab(currentIndex, initial);

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

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

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

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


  const setCurrentIndexByName = (name, initial) => {
    const currentIndex = childrenList.findIndex((tab, index) => getTabName(tab, index) === name);
    setCurrentIndex(currentIndex < 0 ? 0 : currentIndex, initial);
  };

  const scrollToCurrentContent = (immediate, current) => {
    if (props.scrollspy) {
      const target = contentRefs[current !== null && current !== void 0 ? current : state.currentIndex];

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

  const onClickTab = (item, index, event) => {
    var _a;

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

  const scrollTo = name => {
    setCurrentIndexByName(name);
    scrollToCurrentContent(true);
  };

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

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

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

    return titleRefs.length - 1;
  };

  const onScroll = () => {
    if (props.scrollspy && !lockScroll.current) {
      let 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);
      }
    }
  };

  const onStickyScroll = params => {
    var _a;

    stickyFixed.current = params.isFixed;
    (_a = props.onScroll) === null || _a === void 0 ? void 0 : _a.call(props, params);
  };

  const renderNav = () => {
    return childrenList.map((item, index) => {
      return (0, _jsxRuntime().jsx)(_TabsTitle.default, {
        ref: setTitleRefs(index),
        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: event => {
          onClickTab(item, index, event);
        }
      }, item.key);
    });
  };

  const renderHeader = () => {
    const {
      type,
      border
    } = props;
    return (0, _jsxRuntime().jsx)("div", Object.assign({
      ref: setWrapRef,
      className: (0, _clsx().default)([bem('wrap', {
        scrollable
      }), {
        [_constant.BORDER_TOP_BOTTOM]: type === 'line' && border
      }])
    }, {
      children: (0, _jsxRuntime().jsxs)("div", Object.assign({
        ref: navRef,
        role: "tablist",
        className: (0, _clsx().default)(bem('nav', [type, {
          complete: scrollable,
          start: align === 'start'
        }])),
        style: navStyle
      }, {
        children: [props.navRight, renderNav(), type === 'line' && (0, _jsxRuntime().jsx)("div", {
          className: (0, _clsx().default)(bem('line')),
          style: state.lineStyle
        }), props.navRight]
      }))
    }));
  };

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

    if (stickyFixed.current && props.stickyInitScrollbar && !props.scrollspy) {
      // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
      (0, _utils.setRootScrollTop)(Math.ceil((0, _utils.getElementTop)(root.current) - offsetTopPx));
    }
  }, [state.currentIndex]);

  const initialRun = () => {
    setCurrentIndexByName(props.active, true);
    scrollIntoView(true);
    setState({
      inited: true
    });
  };

  (0, _react().useEffect)(() => {
    initialRun(); // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);
  (0, _hooks.useUpdateEffect)(() => {
    if (popupContext.visible) {
      setLine();
    }
  }, [popupContext.visible]);
  (0, _useEventListener.default)('scroll', onScroll, {
    target: scroller,
    depends: [state.currentIndex]
  });
  (0, _react().useImperativeHandle)(ref, () => {
    var _a, _b;

    return {
      resize: setLine,
      scrollTo,
      swiper: swiperRef.current ? {
        enable: (_a = swiperRef.current) === null || _a === void 0 ? void 0 : _a.enable,
        disable: (_b = swiperRef.current) === null || _b === void 0 ? void 0 : _b.disable
      } : undefined
    };
  });

  const onStickyChange = () => {
    setLine(true);
  };

  return (0, _jsxRuntime().jsx)(_TabsContext.default.Provider, Object.assign({
    value: {
      props,
      currentName,
      scrollIntoView,
      setLine
    }
  }, {
    children: (0, _jsxRuntime().jsxs)("div", Object.assign({
      ref: root,
      className: (0, _clsx().default)(props.className, bem([props.type]))
    }, {
      children: [props.sticky ? (0, _jsxRuntime().jsxs)(_sticky.default, Object.assign({
        container: root,
        offsetTop: offsetTopPx,
        onChange: onStickyChange,
        onScroll: onStickyScroll
      }, {
        children: [renderHeader(), props.navBottom]
      })) : (0, _jsxRuntime().jsxs)(_jsxRuntime().Fragment, {
        children: [renderHeader(), props.navBottom]
      }), (0, _jsxRuntime().jsx)(_TabsContent.default, Object.assign({
        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
      }, {
        children: _react().default.Children.toArray(children).filter(Boolean).map((node, index) => _react().default.cloneElement(node, {
          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;