"use strict";

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

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

var _propTypes = _interopRequireDefault(require("prop-types"));

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

var _util = require("../util");

var _nav = _interopRequireDefault(require("./tabs/nav"));

var _content = _interopRequireDefault(require("./tabs/content"));

var _tabItem = _interopRequireDefault(require("./tabs/tab-item"));

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

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }

function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; }

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (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; }

function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }

function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }

function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }

function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }

function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }

function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }

function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }

function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

var noop = function noop() {};
/** Tab */


var Tab =
/*#__PURE__*/
function (_Component) {
  _inherits(Tab, _Component);

  function Tab(props, context) {
    var _this;

    _classCallCheck(this, Tab);

    _this = _possibleConstructorReturn(this, _getPrototypeOf(Tab).call(this, props, context));

    _defineProperty(_assertThisInitialized(_this), "handleTriggerEvent", function (eventType, key) {
      var _this$props = _this.props,
          triggerType = _this$props.triggerType,
          onClick = _this$props.onClick,
          onChange = _this$props.onChange;

      if (triggerType === eventType) {
        onClick(key);

        _this.setActiveKey(key);

        if (_this.state.activeKey !== key) {
          onChange(key);
        }
      }
    });

    _defineProperty(_assertThisInitialized(_this), "onNavKeyDown", function (e) {
      var keyCode = e.keyCode;

      if (keyCode >= _util.KEYCODE.LEFT && keyCode <= _util.KEYCODE.DOWN) {
        e.preventDefault();
      }

      var newKey;

      if (keyCode === _util.KEYCODE.RIGHT || keyCode === _util.KEYCODE.DOWN) {
        newKey = _this.getNextActiveKey(true);

        _this.handleTriggerEvent(_this.props.triggerType, newKey);
      } else if (keyCode === _util.KEYCODE.LEFT || keyCode === _util.KEYCODE.UP) {
        newKey = _this.getNextActiveKey(false);

        _this.handleTriggerEvent(_this.props.triggerType, newKey);
      }
    });

    _this.state = {
      activeKey: _this.getDefaultActiveKey(props)
    };
    return _this;
  }

  _createClass(Tab, [{
    key: "UNSAFE_componentWillReceiveProps",
    value: function UNSAFE_componentWillReceiveProps(nextProps) {
      if (nextProps.activeKey && this.state.activeKey !== nextProps.activeKey) {
        this.setState({
          activeKey: nextProps.activeKey
        });
      }
    }
  }, {
    key: "getDefaultActiveKey",
    value: function getDefaultActiveKey(props) {
      var activeKey = props.activeKey || props.defaultActiveKey;

      if (!activeKey) {
        _react["default"].Children.forEach(props.children, function (child, index) {
          if (_react["default"].isValidElement(child)) {
            /* eslint-disable eqeqeq */
            if (activeKey == undefined && !child.props.disabled) {
              activeKey = child.key || index;
            }
          }
        });
      }

      return activeKey;
    }
  }, {
    key: "getNextActiveKey",
    value: function getNextActiveKey(isNext) {
      var _this2 = this;

      var children = [];

      _react["default"].Children.forEach(this.props.children, function (child) {
        if (_react["default"].isValidElement(child)) {
          if (!child.props.disabled) {
            if (isNext) {
              children.push(child);
            } else {
              children.unshift(child);
            }
          }
        }
      });

      var length = children.length;
      var key = length && children[0].key;
      children.forEach(function (child, i) {
        if (child.key === _this2.state.activeKey) {
          if (i === length - 1) {
            key = children[0].key;
          } else {
            key = children[i + 1].key;
          }
        }
      });
      return key;
    }
  }, {
    key: "setActiveKey",
    value: function setActiveKey(key) {
      var activeKey = this.state.activeKey; // 如果 key 没变，或者受控状态下，则跳过

      if (key === activeKey || 'activeKey' in this.props) {
        return;
      }

      this.setState({
        activeKey: key
      });
    }
  }, {
    key: "render",
    value: function render() {
      var _classnames;

      var _this$props2 = this.props,
          prefix = _this$props2.prefix,
          animation = _this$props2.animation,
          shape = _this$props2.shape,
          size = _this$props2.size,
          extra = _this$props2.extra,
          excessMode = _this$props2.excessMode,
          tabPosition = _this$props2.tabPosition,
          tabRender = _this$props2.tabRender,
          triggerType = _this$props2.triggerType,
          lazyLoad = _this$props2.lazyLoad,
          unmountInactiveTabs = _this$props2.unmountInactiveTabs,
          popupProps = _this$props2.popupProps,
          navStyle = _this$props2.navStyle,
          navClassName = _this$props2.navClassName,
          contentStyle = _this$props2.contentStyle,
          contentClassName = _this$props2.contentClassName,
          className = _this$props2.className,
          onClose = _this$props2.onClose,
          children = _this$props2.children,
          rtl = _this$props2.rtl,
          others = _objectWithoutProperties(_this$props2, ["prefix", "animation", "shape", "size", "extra", "excessMode", "tabPosition", "tabRender", "triggerType", "lazyLoad", "unmountInactiveTabs", "popupProps", "navStyle", "navClassName", "contentStyle", "contentClassName", "className", "onClose", "children", "rtl"]);

      var activeKey = this.state.activeKey;
      var tabs = (0, _utils.toArray)(children);
      var newPosition = tabPosition;

      if (rtl && ['left', 'right'].indexOf(tabPosition) >= 0) {
        newPosition = tabPosition === 'left' ? 'right' : 'left';
      }

      var classNames = (0, _classnames2["default"])((_classnames = {}, _defineProperty(_classnames, "".concat(prefix, "tabs"), true), _defineProperty(_classnames, "".concat(prefix, "tabs-").concat(shape), shape), _defineProperty(_classnames, "".concat(prefix, "tabs-vertical"), shape === 'wrapped' && ['left', 'right'].indexOf(tabPosition) >= 0), _defineProperty(_classnames, "".concat(prefix, "tabs-").concat(newPosition), shape === 'wrapped'), _defineProperty(_classnames, "".concat(prefix + size), size), _classnames), className);
      var navProps = {
        prefix: prefix,
        rtl: rtl,
        animation: animation,
        activeKey: activeKey,
        excessMode: excessMode,
        extra: extra,
        tabs: tabs,
        tabPosition: tabPosition,
        tabRender: tabRender,
        triggerType: triggerType,
        popupProps: popupProps,
        onClose: onClose,
        onTriggerEvent: this.handleTriggerEvent,
        onKeyDown: this.onNavKeyDown,
        style: navStyle,
        className: navClassName
      };
      var contentProps = {
        prefix: prefix,
        activeKey: activeKey,
        lazyLoad: lazyLoad,
        unmountInactiveTabs: unmountInactiveTabs,
        style: contentStyle,
        className: contentClassName
      };
      var tabChildren = [_react["default"].createElement(_nav["default"], _extends({
        key: "tab-nav"
      }, navProps)), _react["default"].createElement(_content["default"], _extends({
        key: "tab-content"
      }, contentProps), tabs)];

      if (tabPosition === 'bottom') {
        tabChildren.reverse();
      }

      return _react["default"].createElement("div", _extends({
        dir: rtl ? 'rtl' : undefined,
        className: classNames
      }, _util.obj.pickOthers(Tab.propTypes, others)), tabChildren);
    }
  }]);

  return Tab;
}(_react.Component);

exports["default"] = Tab;

_defineProperty(Tab, "propTypes", {
  prefix: _propTypes["default"].string,
  rtl: _propTypes["default"].bool,

  /**
   * 被激活的选项卡的 key, 赋值则tab为受控组件, 用户无法切换
   */
  activeKey: _propTypes["default"].oneOfType([_propTypes["default"].number, _propTypes["default"].string]),

  /**
   * 初始化时被激活的选项卡的 key
   */
  defaultActiveKey: _propTypes["default"].oneOfType([_propTypes["default"].number, _propTypes["default"].string]),

  /**
   * 外观形态
   */
  shape: _propTypes["default"].oneOf(['pure', 'wrapped', 'text', 'capsule']),

  /**
   * 是否开启动效
   */
  animation: _propTypes["default"].bool,

  /**
   * 选项卡过多时的滑动模式
   */
  excessMode: _propTypes["default"].oneOf(['slide', 'dropdown']),

  /**
   * 导航选项卡的位置，只适用于包裹型（wrapped）选项卡
   */
  tabPosition: _propTypes["default"].oneOf(['top', 'bottom', 'left', 'right']),

  /**
   * 尺寸
   */
  size: _propTypes["default"].oneOf(['small', 'medium']),

  /**
   * 激活选项卡的触发方式
   */
  triggerType: _propTypes["default"].oneOf(['hover', 'click']),

  /**
   * 是否延迟加载 TabPane 的内容, 默认开启, 即不提前渲染
   */
  lazyLoad: _propTypes["default"].bool,

  /**
   * 是否自动卸载未处于激活状态的选项卡
   */
  unmountInactiveTabs: _propTypes["default"].bool,

  /**
   * 导航条的自定义样式
   */
  navStyle: _propTypes["default"].object,

  /**
   * 导航条的自定义样式类
   */
  navClassName: _propTypes["default"].string,

  /**
   * 内容区容器的自定义样式
   */
  contentStyle: _propTypes["default"].object,

  /**
   * 内容区容器的自定义样式类
   */
  contentClassName: _propTypes["default"].string,

  /**
   * 导航栏附加内容
   */
  extra: _propTypes["default"].node,

  /**
   * 点击单个选项卡时触发的回调
   */
  onClick: _propTypes["default"].func,

  /**
   * 选项卡发生切换时的事件回调
   * @param {String|Number} key 改变后的 key
   */
  onChange: _propTypes["default"].func,

  /**
   * 选项卡被关闭时的事件回调
   * @param {String|Number} key   关闭的选项卡的 key
   */
  onClose: _propTypes["default"].func,

  /**
   * 自定义选项卡模板渲染函数
   * @param {String} key 当前 Tab.Item 的 key 值
   * @param {Object} props 传给 Tab.Item 的所有属性键值对
   * @return {ReactNode} 返回自定义组件
   */
  tabRender: _propTypes["default"].func,

  /**
   * 弹层属性透传, 只有当 excessMode 为 dropdown 时生效
   */
  popupProps: _propTypes["default"].object,
  children: _propTypes["default"].any,
  className: _propTypes["default"].string
});

_defineProperty(Tab, "defaultProps", {
  prefix: 'next-',
  shape: 'pure',
  size: 'medium',
  animation: false,
  tabPosition: 'top',
  excessMode: 'slide',
  triggerType: 'click',
  lazyLoad: true,
  unmountInactiveTabs: false,
  onClick: noop,
  onChange: noop,
  onClose: noop
});

Tab.Item = _tabItem["default"];