"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault")["default"];

var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard")["default"];

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

var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));

var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));

var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));

var _objectWithoutProperties2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutProperties"));

var _typeof2 = _interopRequireDefault(require("@babel/runtime/helpers/typeof"));

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

var _mobx = require("mobx");

var _classnames2 = _interopRequireDefault(require("classnames"));

var _modalProvider = _interopRequireDefault(require("../../pro/lib/modal-provider"));

var _iteratorUtils = require("../../pro/lib/_util/iteratorUtils");

var _getReactNodeText = _interopRequireDefault(require("../../pro/lib/_util/getReactNodeText"));

var _enum = require("./enum");

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

var _enum2 = require("../_util/enum");

var _warning = _interopRequireDefault(require("../_util/warning"));

var _TabBar = _interopRequireDefault(require("./TabBar"));

var _TabContent = _interopRequireDefault(require("./TabContent"));

var _isFlexSupported = _interopRequireDefault(require("../_util/isFlexSupported"));

var _KeyCode = _interopRequireDefault(require("../_util/KeyCode"));

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

var _ConfigContext = _interopRequireDefault(require("../config-provider/ConfigContext"));

var _excluded = ["tabPosition", "className", "destroyInactiveTabPane", "style", "size", "type", "showMore", "tabBarStyle", "inkBarStyle", "hideAdd", "animated", "tabBarGutter", "onEdit", "tabBarExtraContent", "hideOnlyGroup", "customizedCode", "customizable", "children", "defaultActiveKey", "setCustomized", "customized", "prefixCls", "activeKey", "onChange", "onTabClick", "keyboard", "defaultChangeable", "tabDraggable", "tabTitleEditable", "tabCountHideable", "rippleDisabled", "flex", "restoreDefault"];

function handleScroll(e) {
  var currentTarget = e.currentTarget;
  var ownerDocument = currentTarget.ownerDocument;

  if (ownerDocument) {
    var defaultView = ownerDocument.defaultView;

    if (defaultView) {
      var computedStyle = defaultView.getComputedStyle(currentTarget);

      if (computedStyle.overflowX === 'hidden') {
        currentTarget.scrollLeft = 0;
      }

      if (computedStyle.overflowY === 'hidden') {
        currentTarget.scrollTop = 0;
      }
    }
  }
}

function isAnimated(animated) {
  return (0, _typeof2["default"])(animated) === 'object';
}

var TabsWithContext = function TabsWithContext(props) {
  var _classnames;

  var _useContext = (0, _react.useContext)(_ConfigContext["default"]),
      getConfig = _useContext.getConfig,
      getPrefixCls = _useContext.getPrefixCls;

  var tabPosition = props.tabPosition,
      className = props.className,
      destroyInactiveTabPane = props.destroyInactiveTabPane,
      style = props.style,
      size = props.size,
      type = props.type,
      showMore = props.showMore,
      tabBarStyle = props.tabBarStyle,
      _props$inkBarStyle = props.inkBarStyle,
      inkBarStyle = _props$inkBarStyle === void 0 ? getConfig('tabsInkBarStyle') : _props$inkBarStyle,
      hideAdd = props.hideAdd,
      _props$animated = props.animated,
      animated = _props$animated === void 0 ? true : _props$animated,
      tabBarGutter = props.tabBarGutter,
      onEdit = props.onEdit,
      tabBarExtraContent = props.tabBarExtraContent,
      hideOnlyGroup = props.hideOnlyGroup,
      customizedCode = props.customizedCode,
      customizable = props.customizable,
      children = props.children,
      propDefaultActiveKey = props.defaultActiveKey,
      setCustomized = props.setCustomized,
      customized = props.customized,
      customizePrefixCls = props.prefixCls,
      propActiveKey = props.activeKey,
      onChange = props.onChange,
      onTabClick = props.onTabClick,
      keyboard = props.keyboard,
      propDefaultChangeable = props.defaultChangeable,
      tabDraggable = props.tabDraggable,
      tabTitleEditable = props.tabTitleEditable,
      tabCountHideable = props.tabCountHideable,
      rippleDisabled = props.rippleDisabled,
      flex = props.flex,
      restoreDefault = props.restoreDefault,
      restProps = (0, _objectWithoutProperties2["default"])(props, _excluded);
  var hasPropActiveKey = ('activeKey' in props);
  var prefixCls = getPrefixCls('tabs', customizePrefixCls);
  var saveCustomized = (0, _react.useCallback)(function (newCustomized) {
    if (customizable) {
      setCustomized(newCustomized);

      if (customizedCode) {
        var customizedSave = getConfig('customizedSave');
        customizedSave(customizedCode, newCustomized, 'Tabs');
      }
    }
  }, [customizable, customizedCode]);

  var _useMemo = (0, _react.useMemo)(function () {
    return (0, _utils.normalizePanes)(children, customized, {
      tabDraggable: tabDraggable,
      tabTitleEditable: tabTitleEditable,
      tabCountHideable: tabCountHideable
    });
  }, [children, customized, tabDraggable, tabTitleEditable, tabCountHideable]),
      _useMemo2 = (0, _slicedToArray2["default"])(_useMemo, 2),
      totalPanelsMap = _useMemo2[0],
      groupedPanelsMap = _useMemo2[1];

  var defaultChangeable = (0, _react.useMemo)(function () {
    if (propDefaultChangeable !== undefined) {
      return propDefaultChangeable;
    }

    var tabsDefaultChangeable = getConfig('tabsDefaultChangeable');
    return tabsDefaultChangeable;
  }, []);
  var defaultActiveKey = (0, _react.useMemo)(function () {
    var option = {
      activeKey: propActiveKey,
      defaultActiveKey: propDefaultActiveKey
    };
    return (0, _utils.getDefaultActiveKey)(totalPanelsMap, groupedPanelsMap, option);
  }, []);
  var customizedDefaultActiveKey = (0, _react.useMemo)(function () {
    if (defaultChangeable && customized) {
      var $defaultActiveKey = customized.defaultActiveKey;

      if ($defaultActiveKey !== undefined) {
        var pane = totalPanelsMap.get($defaultActiveKey);

        if (pane && !pane.disabled) {
          return $defaultActiveKey;
        }
      }
    }
  }, [defaultChangeable, customized, totalPanelsMap]);
  var actuallyDefaultActiveKey = (0, _react.useMemo)(function () {
    if (customizedDefaultActiveKey !== undefined) {
      if (onChange && customizedDefaultActiveKey !== defaultActiveKey) {
        onChange(customizedDefaultActiveKey);
      }

      return customizedDefaultActiveKey;
    }

    return defaultActiveKey;
  }, [defaultActiveKey, customizedDefaultActiveKey]);

  var _useState = (0, _react.useState)(actuallyDefaultActiveKey),
      _useState2 = (0, _slicedToArray2["default"])(_useState, 2),
      activeKey = _useState2[0],
      setActiveKey = _useState2[1];

  var activeGroupKey = (0, _react.useMemo)(function () {
    if (groupedPanelsMap.size) {
      if (activeKey) {
        var groupKey;
        (0, _iteratorUtils.iteratorSome)(groupedPanelsMap.entries(), function (_ref) {
          var _ref2 = (0, _slicedToArray2["default"])(_ref, 2),
              key = _ref2[0],
              panelsMap = _ref2[1].panelsMap;

          var found = (0, _iteratorUtils.iteratorSome)(panelsMap.keys(), function (panelKey) {
            return panelKey === activeKey;
          });

          if (found) {
            groupKey = key;
          }

          return found;
        });

        if (groupKey !== undefined) {
          return groupKey;
        }
      }

      return (0, _utils.getDefaultGroupKey)(groupedPanelsMap);
    }
  }, [groupedPanelsMap, activeKey]);
  var currentGroup = activeGroupKey ? groupedPanelsMap.get(activeGroupKey) : undefined;
  var currentPanelMap = currentGroup ? currentGroup.panelsMap : totalPanelsMap;
  var refCurrent = {
    activeGroupKey: activeGroupKey,
    currentGroup: currentGroup,
    currentPanelMap: currentPanelMap
  };
  var ref = (0, _react.useRef)(refCurrent);
  ref.current = refCurrent;
  var tabRef = (0, _react.useRef)(null);
  var changeActiveKey = (0, _react.useCallback)(function (key, byGroup) {
    if (activeKey !== key) {
      if (!byGroup && currentGroup) {
        currentGroup.lastActiveKey = key;
      }

      if (!hasPropActiveKey) {
        setActiveKey(key);
      }

      if (onChange) {
        onChange(key);
      }
    }
  }, [hasPropActiveKey, activeKey, onChange, currentGroup]);
  var validationMap = (0, _react.useMemo)(function () {
    return _mobx.observable.map();
  }, []);
  var value = {
    defaultActiveKey: propDefaultActiveKey,
    actuallyDefaultActiveKey: actuallyDefaultActiveKey,
    propActiveKey: propActiveKey,
    prefixCls: prefixCls,
    keyboard: keyboard,
    tabBarPosition: tabPosition,
    hideOnlyGroup: hideOnlyGroup,
    customizable: customizable,
    customized: customized,
    saveCustomized: saveCustomized,
    activeKey: activeKey,
    activeGroupKey: activeGroupKey,
    changeActiveKey: changeActiveKey,
    groupedPanelsMap: groupedPanelsMap,
    currentPanelMap: currentPanelMap,
    totalPanelsMap: totalPanelsMap,
    validationMap: validationMap,
    onTabClick: onTabClick,
    children: children,
    tabDraggable: tabDraggable,
    tabTitleEditable: tabTitleEditable,
    tabCountHideable: tabCountHideable,
    defaultChangeable: defaultChangeable,
    rippleDisabled: rippleDisabled,
    restoreDefault: restoreDefault
  };
  var inkBarAnimated = isAnimated(animated) ? animated.inkBar : animated;
  var tabPaneAnimated = isAnimated(animated) ? animated.tabPane : animated;
  var onTabsChange = getConfig('onTabsChange'); // card tabs should not have animation

  if (type !== _enum.TabsType.line) {
    tabPaneAnimated = 'animated' in props ? tabPaneAnimated : false;
  }

  if (flex) {
    tabPaneAnimated = false;
  }

  var isCard = type === _enum.TabsType.card || type === _enum.TabsType['editable-card'];
  (0, _warning["default"])(!(isCard && (size === _enum2.Size.small || size === _enum2.Size.large)), 'Tabs[type=card|editable-card] doesn\'t have small or large size, it\'s by designed.');
  var removeTab = (0, _react.useCallback)(function (targetKey, e) {
    e.stopPropagation();

    if (!targetKey) {
      return;
    }

    if (onEdit) {
      onEdit(targetKey, 'remove');
    }
  }, [onEdit]);
  (0, _react.useEffect)(function () {
    if (hasPropActiveKey) {
      if (propActiveKey !== activeKey) {
        setActiveKey(propActiveKey);
      }
    } else if (activeKey === undefined || !totalPanelsMap.has(activeKey)) {
      setActiveKey((0, _utils.getDefaultActiveKeyInGroup)(currentPanelMap));
    }
  }, [hasPropActiveKey, propActiveKey, activeKey, totalPanelsMap, currentPanelMap]);
  (0, _react.useEffect)(function () {
    if (onTabsChange && activeKey) {
      var current = ref.current;
      var currentPanel = current.currentPanelMap.get(activeKey);

      if (currentPanel) {
        var $currentGroup = current.currentGroup,
            $activeGroupKey = current.activeGroupKey;
        var groupTab = $currentGroup ? $currentGroup.group.tab : undefined;
        var title = (0, _utils.getHeader)(currentPanel);
        var promises = [(0, _getReactNodeText["default"])(title)];

        if (groupTab) {
          promises.push((0, _getReactNodeText["default"])(groupTab));
        }

        Promise.all(promises).then(function (_ref3) {
          var _ref4 = (0, _slicedToArray2["default"])(_ref3, 2),
              title = _ref4[0],
              groupTitle = _ref4[1];

          onTabsChange({
            activeKey: activeKey,
            activeGroupKey: $activeGroupKey,
            title: title,
            groupTitle: groupTitle,
            code: customizedCode
          });
        });
      }
    }
  }, [activeKey, onTabsChange, customizedCode]);
  var cls = (0, _classnames2["default"])(prefixCls, "".concat(prefixCls, "-").concat(tabPosition), "".concat(prefixCls, "-").concat(type), (0, _utils.isVertical)(tabPosition) ? "".concat(prefixCls, "-vertical") : "".concat(prefixCls, "-horizontal"), (_classnames = {}, (0, _defineProperty2["default"])(_classnames, "".concat(prefixCls, "-").concat(size), !!size), (0, _defineProperty2["default"])(_classnames, "".concat(prefixCls, "-card"), isCard), (0, _defineProperty2["default"])(_classnames, "".concat(prefixCls, "-flex"), flex), (0, _defineProperty2["default"])(_classnames, "".concat(prefixCls, "-no-animation"), !tabPaneAnimated), (0, _defineProperty2["default"])(_classnames, 'no-flex', !(0, _isFlexSupported["default"])()), _classnames), className);
  var extraContent = !hideAdd && type === _enum.TabsType['editable-card'] ?
  /*#__PURE__*/
  // Add new tab handler
  _react["default"].createElement("div", {
    key: "tabBarExtraContent",
    className: "".concat(prefixCls, "-extra-bar")
  }, tabBarExtraContent) : tabBarExtraContent;
  var tabBarProps = {
    inkBarAnimated: inkBarAnimated,
    extraContent: extraContent,
    style: tabBarStyle,
    tabBarGutter: tabBarGutter,
    type: type,
    showMore: showMore,
    onRemoveTab: removeTab,
    onEdit: onEdit,
    inkBarStyle: inkBarStyle,
    hideAdd: hideAdd
  };
  var tabContentProps = {
    animatedWithMargin: true,
    animated: tabPaneAnimated,
    destroyInactiveTabPane: destroyInactiveTabPane
  };
  var contents = [/*#__PURE__*/_react["default"].createElement(_TabBar["default"], (0, _extends2["default"])({
    key: "tabBar"
  }, tabBarProps)), /*#__PURE__*/_react["default"].createElement(_TabContent["default"], (0, _extends2["default"])({
    key: "tabContent"
  }, tabContentProps))];

  if (tabPosition === _enum.TabsPosition.bottom) {
    contents.reverse();
  }

  var handleKeyDown = (0, _react.useCallback)(function (e) {
    var keyCode = e.keyCode;

    if (keyCode === _KeyCode["default"].TAB) {
      if (tabRef.current) {
        var selector = '[tabindex^="-1"]';
        var findFocusableElements = Array.from(tabRef.current.querySelectorAll(selector));
        findFocusableElements.forEach(function (child) {
          if (child.getAttribute('data-node-key') === activeKey && document.activeElement === tabRef.current) {
            child.focus();
          }
        });
      }
    }
  }, [activeKey]);

  var tabs = /*#__PURE__*/_react["default"].createElement("div", (0, _extends2["default"])({
    tabIndex: -1,
    ref: tabRef,
    className: cls,
    style: style,
    onScrollCapture: tabPaneAnimated ? handleScroll : undefined,
    onKeyDown: handleKeyDown
  }, (0, _utils.getDataAttr)(restProps)), contents);

  return /*#__PURE__*/_react["default"].createElement(_TabsContext["default"].Provider, {
    value: value
  }, customizable ? /*#__PURE__*/_react["default"].createElement(_modalProvider["default"], null, tabs) : tabs);
};

TabsWithContext.displayName = 'TabsWithContext';
var _default = TabsWithContext;
exports["default"] = _default;
//# sourceMappingURL=TabsWithContext.js.map
