import _extends from "@babel/runtime/helpers/extends";
import _defineProperty from "@babel/runtime/helpers/defineProperty";
import _slicedToArray from "@babel/runtime/helpers/slicedToArray";
import _objectWithoutProperties from "@babel/runtime/helpers/objectWithoutProperties";
import _typeof from "@babel/runtime/helpers/typeof";
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"];
import React, { useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react';
import { observable } from 'mobx';
import classnames from 'classnames';
import ModalProvider from '../../pro/es/modal-provider';
import { iteratorSome } from '../../pro/es/_util/iteratorUtils';
import getReactNodeText from '../../pro/es/_util/getReactNodeText';
import { TabsPosition, TabsType } from './enum';
import { getDataAttr, getDefaultActiveKey, getDefaultActiveKeyInGroup, getDefaultGroupKey, getHeader, isVertical, normalizePanes } from './utils';
import { Size } from '../_util/enum';
import warning from '../_util/warning';
import TabBar from './TabBar';
import TabContent from './TabContent';
import isFlexSupported from '../_util/isFlexSupported';
import KeyCode from '../_util/KeyCode';
import TabsContext from './TabsContext';
import ConfigContext from '../config-provider/ConfigContext';

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 _typeof(animated) === 'object';
}

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

  var _useContext = useContext(ConfigContext),
      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 = _objectWithoutProperties(props, _excluded);

  var hasPropActiveKey = ('activeKey' in props);
  var prefixCls = getPrefixCls('tabs', customizePrefixCls);
  var saveCustomized = useCallback(function (newCustomized) {
    if (customizable) {
      setCustomized(newCustomized);

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

  var _useMemo = useMemo(function () {
    return normalizePanes(children, customized, {
      tabDraggable: tabDraggable,
      tabTitleEditable: tabTitleEditable,
      tabCountHideable: tabCountHideable
    });
  }, [children, customized, tabDraggable, tabTitleEditable, tabCountHideable]),
      _useMemo2 = _slicedToArray(_useMemo, 2),
      totalPanelsMap = _useMemo2[0],
      groupedPanelsMap = _useMemo2[1];

  var defaultChangeable = useMemo(function () {
    if (propDefaultChangeable !== undefined) {
      return propDefaultChangeable;
    }

    var tabsDefaultChangeable = getConfig('tabsDefaultChangeable');
    return tabsDefaultChangeable;
  }, []);
  var defaultActiveKey = useMemo(function () {
    var option = {
      activeKey: propActiveKey,
      defaultActiveKey: propDefaultActiveKey
    };
    return getDefaultActiveKey(totalPanelsMap, groupedPanelsMap, option);
  }, []);
  var customizedDefaultActiveKey = 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 = useMemo(function () {
    if (customizedDefaultActiveKey !== undefined) {
      if (onChange && customizedDefaultActiveKey !== defaultActiveKey) {
        onChange(customizedDefaultActiveKey);
      }

      return customizedDefaultActiveKey;
    }

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

  var _useState = useState(actuallyDefaultActiveKey),
      _useState2 = _slicedToArray(_useState, 2),
      activeKey = _useState2[0],
      setActiveKey = _useState2[1];

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

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

          if (found) {
            groupKey = key;
          }

          return found;
        });

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

      return 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 = useRef(refCurrent);
  ref.current = refCurrent;
  var tabRef = useRef(null);
  var changeActiveKey = 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 = useMemo(function () {
    return 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 !== TabsType.line) {
    tabPaneAnimated = 'animated' in props ? tabPaneAnimated : false;
  }

  if (flex) {
    tabPaneAnimated = false;
  }

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

    if (!targetKey) {
      return;
    }

    if (onEdit) {
      onEdit(targetKey, 'remove');
    }
  }, [onEdit]);
  useEffect(function () {
    if (hasPropActiveKey) {
      if (propActiveKey !== activeKey) {
        setActiveKey(propActiveKey);
      }
    } else if (activeKey === undefined || !totalPanelsMap.has(activeKey)) {
      setActiveKey(getDefaultActiveKeyInGroup(currentPanelMap));
    }
  }, [hasPropActiveKey, propActiveKey, activeKey, totalPanelsMap, currentPanelMap]);
  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 = getHeader(currentPanel);
        var promises = [getReactNodeText(title)];

        if (groupTab) {
          promises.push(getReactNodeText(groupTab));
        }

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

          onTabsChange({
            activeKey: activeKey,
            activeGroupKey: $activeGroupKey,
            title: title,
            groupTitle: groupTitle,
            code: customizedCode
          });
        });
      }
    }
  }, [activeKey, onTabsChange, customizedCode]);
  var cls = classnames(prefixCls, "".concat(prefixCls, "-").concat(tabPosition), "".concat(prefixCls, "-").concat(type), isVertical(tabPosition) ? "".concat(prefixCls, "-vertical") : "".concat(prefixCls, "-horizontal"), (_classnames = {}, _defineProperty(_classnames, "".concat(prefixCls, "-").concat(size), !!size), _defineProperty(_classnames, "".concat(prefixCls, "-card"), isCard), _defineProperty(_classnames, "".concat(prefixCls, "-flex"), flex), _defineProperty(_classnames, "".concat(prefixCls, "-no-animation"), !tabPaneAnimated), _defineProperty(_classnames, 'no-flex', !isFlexSupported()), _classnames), className);
  var extraContent = !hideAdd && type === TabsType['editable-card'] ?
  /*#__PURE__*/
  // Add new tab handler
  React.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.createElement(TabBar, _extends({
    key: "tabBar"
  }, tabBarProps)), /*#__PURE__*/React.createElement(TabContent, _extends({
    key: "tabContent"
  }, tabContentProps))];

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

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

    if (keyCode === KeyCode.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.createElement("div", _extends({
    tabIndex: -1,
    ref: tabRef,
    className: cls,
    style: style,
    onScrollCapture: tabPaneAnimated ? handleScroll : undefined,
    onKeyDown: handleKeyDown
  }, getDataAttr(restProps)), contents);
  return /*#__PURE__*/React.createElement(TabsContext.Provider, {
    value: value
  }, customizable ? /*#__PURE__*/React.createElement(ModalProvider, null, tabs) : tabs);
};

TabsWithContext.displayName = 'TabsWithContext';
export default TabsWithContext;
//# sourceMappingURL=TabsWithContext.js.map
