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 _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; }

import React from 'react';
import { findDOMNode } from 'react-dom';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import Icon from '../../icon';
import Overlay from '../../overlay';
import Menu from '../../menu';
import Animate from '../../animate';
import { events, KEYCODE, dom } from '../../util';
import { triggerEvents, getOffsetLT, getOffsetWH, isTransformSupported } from './utils';
var floatRight = {
  "float": 'right',
  zIndex: 1
};
var floatLeft = {
  "float": 'left',
  zIndex: 1
};
var Popup = Overlay.Popup;

var Nav =
/*#__PURE__*/
function (_React$Component) {
  _inherits(Nav, _React$Component);

  function Nav(props, context) {
    var _this;

    _classCallCheck(this, Nav);

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

    _defineProperty(_assertThisInitialized(_this), "initialSettings", function () {
      _this.setSlideBtn();

      _this.getDropdownItems(_this.props);
    });

    _defineProperty(_assertThisInitialized(_this), "removeTab", function (key, e) {
      e && e.stopPropagation(); // stop bubble, so that it won't trigger upstream listener

      _this.props.onClose(key);
    });

    _defineProperty(_assertThisInitialized(_this), "onCloseKeyDown", function (key, e) {
      if (e.keyCode === KEYCODE.ENTER) {
        e.stopPropagation();
        e.preventDefault();

        _this.props.onClose(key);
      }
    });

    _defineProperty(_assertThisInitialized(_this), "defaultTabTemplateRender", function (key, _ref) {
      var prefix = _ref.prefix,
          title = _ref.title,
          closeable = _ref.closeable,
          badge = _ref.badge,
          icon = _ref.icon;
      var tail = closeable ? React.createElement(Icon, {
        type: "remove",
        tabIndex: "0",
        onKeyDown: function onKeyDown(e) {
          return _this.onCloseKeyDown(key, e);
        },
        onClick: function onClick(e) {
          return _this.removeTab(key, e);
        },
        className: "".concat(prefix, "tabs-tab-close")
      }) : null;
      var badgeV = badge ? React.createElement("span", {
        className: "".concat(_this.props.prefix, "tabs-tab-badge")
      }, badge) : null;
      var iconV = icon ? React.createElement("span", {
        className: "".concat(_this.props.prefix, "tabs-tab-icon")
      }, icon) : null;
      return React.createElement("div", {
        className: "".concat(_this.props.prefix, "tabs-tab-inner")
      }, iconV, React.createElement("span", {
        className: "".concat(_this.props.prefix, "tabs-tab-title")
      }, title), badgeV, tail);
    });

    _defineProperty(_assertThisInitialized(_this), "renderTabList", function () {
      var _this$props = _this.props,
          prefix = _this$props.prefix,
          activeKey = _this$props.activeKey,
          tabRender = _this$props.tabRender,
          excessMode = _this$props.excessMode;
      var dropdownTabs = _this.state.dropdownTabs;
      var tabs = _this.props.tabs;
      var tabTemplateFn = tabRender || _this.defaultTabTemplateRender;

      if (excessMode === 'dropdown' && dropdownTabs.length && Array.isArray(tabs)) {
        tabs = tabs.slice(0, tabs.length - dropdownTabs.length);
      }

      var rst = [];
      React.Children.forEach(tabs, function (child) {
        var _classnames;

        var _child$props = child.props,
            disabled = _child$props.disabled,
            className = _child$props.className,
            onClick = _child$props.onClick,
            onMouseEnter = _child$props.onMouseEnter,
            onMouseLeave = _child$props.onMouseLeave,
            style = _child$props.style;
        /* eslint-disable eqeqeq */

        var active = activeKey == child.key;
        var cls = classnames((_classnames = {}, _defineProperty(_classnames, "".concat(prefix, "tabs-tab"), true), _defineProperty(_classnames, "disabled", disabled), _defineProperty(_classnames, "active", active), _classnames), className);
        var events = {};

        if (!disabled) {
          events = {
            onClick: _this.onNavItemClick.bind(_assertThisInitialized(_this), child.key, onClick),
            onMouseEnter: _this.onNavItemMouseEnter.bind(_assertThisInitialized(_this), child.key, onMouseEnter),
            onMouseLeave: _this.onNavItemMouseLeave.bind(_assertThisInitialized(_this), child.key, onMouseLeave)
          };
        }

        rst.push(React.createElement("li", _extends({
          role: "tab",
          key: child.key,
          ref: active ? _this.activeTabRefHandler : null,
          "aria-hidden": disabled ? 'true' : 'false',
          "aria-selected": active ? 'true' : 'false',
          tabIndex: active ? 0 : -1,
          className: cls,
          style: style
        }, events), tabTemplateFn(child.key, child.props)));
      });
      return rst;
    });

    _defineProperty(_assertThisInitialized(_this), "scrollToActiveTab", function () {
      if (!_this.activeTab || _this.props.excessMode !== 'slide') {
        return;
      }

      var activeTabWH = getOffsetWH(_this.activeTab);
      var wrapperWH = getOffsetWH(_this.wrapper);
      var activeTabOffset = getOffsetLT(_this.activeTab);
      var wrapperOffset = getOffsetLT(_this.wrapper);
      var target = _this.offset;

      if (activeTabOffset >= wrapperOffset + wrapperWH || activeTabOffset + activeTabWH <= wrapperOffset) {
        _this.setOffset(_this.offset + wrapperOffset - activeTabOffset, true, true);

        return;
      }

      _this.setOffset(target, true, true);
    });

    _defineProperty(_assertThisInitialized(_this), "onPrevClick", function () {
      var wrapperWH = getOffsetWH(_this.wrapper);

      _this.setOffset(_this.offset + wrapperWH, true, false);
    });

    _defineProperty(_assertThisInitialized(_this), "onNextClick", function () {
      var wrapperWH = getOffsetWH(_this.wrapper);

      _this.setOffset(_this.offset - wrapperWH, true, false);
    });

    _defineProperty(_assertThisInitialized(_this), "onSelectMenuItem", function (keys) {
      var _this$props2 = _this.props,
          onTriggerEvent = _this$props2.onTriggerEvent,
          triggerType = _this$props2.triggerType;
      onTriggerEvent(triggerType, keys[0]);
    });

    _defineProperty(_assertThisInitialized(_this), "onWindowResized", function () {
      if (_this.updateTimer) {
        clearTimeout(_this.updateTimer);
      }

      _this.updateTimer = setTimeout(function () {
        _this.setSlideBtn();

        _this.getDropdownItems(_this.props);
      }, 100);
    });

    _defineProperty(_assertThisInitialized(_this), "navRefHandler", function (ref) {
      _this.nav = findDOMNode(ref);
    });

    _defineProperty(_assertThisInitialized(_this), "wrapperRefHandler", function (ref) {
      _this.wrapper = ref;
    });

    _defineProperty(_assertThisInitialized(_this), "navbarRefHandler", function (ref) {
      _this.navbar = ref;
    });

    _defineProperty(_assertThisInitialized(_this), "activeTabRefHandler", function (ref) {
      _this.activeTab = ref;
    });

    _defineProperty(_assertThisInitialized(_this), "prevBtnHandler", function (ref) {
      _this.prevBtn = findDOMNode(ref);
    });

    _defineProperty(_assertThisInitialized(_this), "nextBtnHandler", function (ref) {
      _this.nextBtn = findDOMNode(ref);
    });

    _this.state = {
      showBtn: false,
      dropdownTabs: []
    };
    _this.offset = 0;
    return _this;
  }

  _createClass(Nav, [{
    key: "componentDidMount",
    value: function componentDidMount() {
      if (!this.props.animation) {
        this.initialSettings();
      }

      events.on(window, 'resize', this.onWindowResized);
    }
  }, {
    key: "componentDidUpdate",
    value: function componentDidUpdate(prevProps) {
      var _this2 = this;

      var ctx = this; // 此处通过延时处理，屏蔽动画带来的定位不准确问题（由于要支持ie9，因此无法使用transitionend）

      clearTimeout(ctx.scrollTimer);
      ctx.scrollTimer = setTimeout(function () {
        ctx.scrollToActiveTab();
      }, 410); // transition-duration is set to be .4s, wait for the transition finishes before re-calc

      clearTimeout(ctx.slideTimer);
      ctx.slideTimer = setTimeout(function () {
        ctx.setSlideBtn();

        if (_this2.props.tabs !== prevProps.tabs) {
          _this2.getDropdownItems(_this2.props);
        }
      }, 200);
    }
  }, {
    key: "componentWillUnmount",
    value: function componentWillUnmount() {
      events.off(window, 'resize', this.onWindowResized);
    }
  }, {
    key: "setOffset",

    /**
     * The key method about move
     * @param {number} target position to slide to
     * @param {bool} checkSlideBtn need to check the slide button status or not
     * @param {bool} setActive need to check the active status or not
     */
    value: function setOffset(target) {
      var checkSlideBtn = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
      var setActive = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;
      var _this$props3 = this.props,
          tabPosition = _this$props3.tabPosition,
          rtl = _this$props3.rtl;
      var navWH = getOffsetWH(this.nav, tabPosition);
      var wrapperWH = getOffsetWH(this.wrapper); // target should not be great than 0, i.e. should not over slide to left-most

      target = target >= 0 ? 0 : target; // when need to slide, should not slide to exceed right-most

      target = target <= wrapperWH - navWH && wrapperWH - navWH < 0 ? wrapperWH - navWH : target;
      var relativeOffset = target - this.offset;

      if (this.activeTab && this.props.excessMode === 'slide' && setActive) {
        var activeTabWH = getOffsetWH(this.activeTab);
        var activeTabOffset = getOffsetLT(this.activeTab) + relativeOffset;
        var wrapperOffset = getOffsetLT(this.wrapper);
        target = this._adjustTarget({
          wrapperOffset: wrapperOffset,
          wrapperWH: wrapperWH,
          activeTabWH: activeTabWH,
          activeTabOffset: activeTabOffset,
          rtl: rtl,
          target: target
        });
      }

      if (this.offset !== target) {
        // needs move
        this.offset = target;
        var navOffset = {};
        var navStyle = this.nav.style;
        var canTransform = isTransformSupported(navStyle);

        if (tabPosition === 'left' || tabPosition === 'right') {
          navOffset = canTransform ? {
            value: "translate3d(0, ".concat(target, "px, 0)")
          } : {
            name: 'top',
            value: "".concat(target, "px")
          };
        } else if (!this.props.rtl) {
          navOffset = canTransform ? {
            value: "translate3d(".concat(target, "px, 0, 0)")
          } : {
            name: 'left',
            value: "".concat(target, "px")
          };
        } else {
          navOffset = canTransform ? {
            value: "translate3d(".concat(-target, "px, 0, 0)")
          } : {
            name: 'right',
            value: "".concat(target, "px")
          };
        }

        if (canTransform) {
          _extends(navStyle, {
            transform: navOffset.value,
            webkitTransform: navOffset.value,
            mozTransform: navOffset.value
          });
        } else {
          navStyle[navOffset.name] = navOffset.value;
        }

        if (checkSlideBtn) {
          this.setSlideBtn();
        }
      }
    }
  }, {
    key: "_adjustTarget",
    value: function _adjustTarget(_ref2) {
      var wrapperOffset = _ref2.wrapperOffset,
          wrapperWH = _ref2.wrapperWH,
          activeTabWH = _ref2.activeTabWH,
          activeTabOffset = _ref2.activeTabOffset,
          rtl = _ref2.rtl,
          target = _ref2.target;

      if ( // active tab covers wrapper right edge
      wrapperOffset + wrapperWH < activeTabOffset + activeTabWH && activeTabOffset < wrapperOffset + wrapperWH) {
        if (rtl) {
          target += activeTabOffset + activeTabWH - (wrapperOffset + wrapperWH); // Move more to make active tab totally in visible zone
        } else {
          target -= activeTabOffset + activeTabWH - (wrapperOffset + wrapperWH) + 1;
        }

        return target;
      }

      if ( // active tab covers wrapper left edge
      wrapperOffset < activeTabOffset + activeTabWH && activeTabOffset < wrapperOffset) {
        if (rtl) {
          target -= wrapperOffset - activeTabOffset + 1;
        } else {
          target += wrapperOffset - activeTabOffset;
        }

        return target;
      }

      return target;
    }
  }, {
    key: "_setBtnStyle",
    value: function _setBtnStyle(prev, next) {
      if (this.prevBtn && this.nextBtn) {
        var cls = 'disabled';
        this.prevBtn.disabled = !prev;
        this.nextBtn.disabled = !next;

        if (prev) {
          dom.removeClass(this.prevBtn, cls);
        } else {
          dom.addClass(this.prevBtn, cls);
        }

        if (next) {
          dom.removeClass(this.nextBtn, cls);
        } else {
          dom.addClass(this.nextBtn, cls);
        }
      }
    }
  }, {
    key: "setSlideBtn",
    value: function setSlideBtn() {
      var _this$props4 = this.props,
          tabPosition = _this$props4.tabPosition,
          excessMode = _this$props4.excessMode;

      if (excessMode !== 'slide') {
        return;
      } // TEMP: 这里会受 Animate 影响，re-render 过程中 this.nav 实际上指向的是上次的 tabList 元素，建议暂时关闭 animation 解决


      var navWH = getOffsetWH(this.nav, tabPosition);
      var wrapperWH = getOffsetWH(this.wrapper, tabPosition);
      var navbarWH = getOffsetWH(this.navbar, tabPosition);
      var minOffset = wrapperWH - navWH;
      var next;
      var prev;

      if (minOffset >= 0 || navWH <= navbarWH) {
        next = false;
        prev = false;
        this.setOffset(0, false); // no need to check slide again since this call is invoked from inside setSlideBtn
      } else if (this.offset < 0 && this.offset <= minOffset) {
        prev = true;
        next = false;
      } else if (this.offset >= 0) {
        prev = false;
        next = true;
      } else {
        prev = true;
        next = true;
      }

      if ((prev || next) !== this.state.showBtn) {
        this.setState({
          showBtn: prev || next
        });
      } else {
        this._setBtnStyle(prev, next);
      }
    }
  }, {
    key: "getDropdownItems",
    value: function getDropdownItems(_ref3) {
      var excessMode = _ref3.excessMode,
          tabs = _ref3.tabs;

      if (excessMode !== 'dropdown') {
        return;
      } // 先清空所有下拉项，让其全部横向渲染


      this.setState({
        dropdownTabs: []
      });
      var wrapperWidth = this.wrapper.offsetWidth;
      var childNodes = this.nav.childNodes;
      var index;
      var tabsWidth = 0;

      for (index = 0; index < tabs.length; index++) {
        if (!childNodes[index]) {
          // 横向的不一定全展示，还有的放在drowndown中
          break;
        }

        tabsWidth += childNodes[index].offsetWidth + 24; // 24为右外边距

        if (tabsWidth > wrapperWidth) {
          break;
        }
      }

      if (index !== tabs.length) {
        this.setState({
          dropdownTabs: tabs.slice(index)
        });
      }
    }
  }, {
    key: "onNavItemClick",
    value: function onNavItemClick(key, callback, e) {
      this.props.onTriggerEvent(triggerEvents.CLICK, key);

      if (callback) {
        return callback(key, e);
      }
    }
  }, {
    key: "onNavItemMouseEnter",
    value: function onNavItemMouseEnter(key, callback, e) {
      this.props.onTriggerEvent(triggerEvents.HOVER, key);

      if (callback) {
        return callback(key, e);
      }
    }
  }, {
    key: "onNavItemMouseLeave",
    value: function onNavItemMouseLeave(key, callback, e) {
      if (callback) {
        return callback(key, e);
      }
    }
  }, {
    key: "renderDropdownTabs",
    value: function renderDropdownTabs() {
      var _this3 = this;

      var tabs = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];

      if (!tabs.length) {
        return null;
      }

      var _this$props5 = this.props,
          prefix = _this$props5.prefix,
          activeKey = _this$props5.activeKey,
          triggerType = _this$props5.triggerType,
          popupProps = _this$props5.popupProps,
          rtl = _this$props5.rtl;
      var trigger = React.createElement("button", {
        className: "".concat(prefix, "tabs-btn-down")
      }, React.createElement(Icon, {
        type: "chevron-down"
      }));
      return React.createElement(Popup, _extends({
        rtl: rtl,
        triggerType: triggerType,
        trigger: trigger // container={target => target.parentNode}
        ,
        className: "".concat(prefix, "tabs-bar-popup")
      }, popupProps), React.createElement(Menu, {
        rtl: rtl,
        selectedKeys: [activeKey],
        onSelect: this.onSelectMenuItem,
        selectMode: "single"
      }, tabs.map(function (tab) {
        var _tab$props = tab.props,
            disabled = _tab$props.disabled,
            onClick = _tab$props.onClick,
            onMouseEnter = _tab$props.onMouseEnter,
            onMouseLeave = _tab$props.onMouseLeave;
        var events = {};

        if (!disabled) {
          events = {
            onClick: _this3.onNavItemClick.bind(_this3, tab.key, onClick),
            onMouseEnter: _this3.onNavItemMouseEnter.bind(_this3, tab.key, onMouseEnter),
            onMouseLeave: _this3.onNavItemMouseLeave.bind(_this3, tab.key, onMouseLeave)
          };
        }

        return React.createElement(Menu.Item, _extends({
          key: tab.key
        }, events), tab.props.title);
      })));
    }
  }, {
    key: "render",
    value: function render() {
      var _classnames2;

      var _this$props6 = this.props,
          prefix = _this$props6.prefix,
          tabPosition = _this$props6.tabPosition,
          excessMode = _this$props6.excessMode,
          extra = _this$props6.extra,
          onKeyDown = _this$props6.onKeyDown,
          animation = _this$props6.animation,
          style = _this$props6.style,
          className = _this$props6.className,
          rtl = _this$props6.rtl;
      var state = this.state;
      var nextButton;
      var prevButton;
      var restButton;
      var showNextPrev = state.showBtn;

      if (excessMode === 'dropdown' && state.dropdownTabs.length) {
        restButton = this.renderDropdownTabs(state.dropdownTabs);
        prevButton = null;
        nextButton = null;
      } else if (showNextPrev) {
        prevButton = React.createElement("button", {
          onClick: this.onPrevClick,
          className: "".concat(prefix, "tabs-btn-prev"),
          ref: this.prevBtnHandler
        }, React.createElement(Icon, {
          rtl: rtl,
          type: "chevron-left"
        }));
        nextButton = React.createElement("button", {
          onClick: this.onNextClick,
          className: "".concat(prefix, "tabs-btn-next"),
          ref: this.nextBtnHandler
        }, React.createElement(Icon, {
          rtl: rtl,
          type: "chevron-right"
        }));
        restButton = null;
      } else {
        nextButton = null;
        prevButton = null;
        restButton = null;
      }

      var containerCls = classnames((_classnames2 = {}, _defineProperty(_classnames2, "".concat(prefix, "tabs-nav-container"), true), _defineProperty(_classnames2, "".concat(prefix, "tabs-nav-container-scrolling"), showNextPrev), _classnames2));
      var navCls = "".concat(prefix, "tabs-nav");
      var tabList = this.renderTabList();
      var container = React.createElement("div", {
        className: containerCls,
        onKeyDown: onKeyDown,
        key: "nav-container"
      }, React.createElement("div", {
        className: "".concat(prefix, "tabs-nav-wrap"),
        ref: this.wrapperRefHandler
      }, React.createElement("div", {
        className: "".concat(prefix, "tabs-nav-scroll")
      }, animation ? React.createElement(Animate, {
        role: "tablist",
        "aria-multiselectable": false,
        component: "ul",
        className: navCls,
        animation: navCls,
        singleMode: false,
        ref: this.navRefHandler,
        afterAppear: this.initialSettings
      }, tabList) : React.createElement("ul", {
        role: "tablist",
        className: navCls,
        ref: this.navRefHandler
      }, tabList))), prevButton, nextButton, restButton);
      var navChildren = [container];

      if (extra) {
        var extraProps = {
          className: "".concat(prefix, "tabs-nav-extra"),
          key: 'nav-extra'
        };

        if (tabPosition === 'top' || tabPosition === 'bottom') {
          var _style = rtl ? floatLeft : floatRight;

          navChildren.unshift(React.createElement("div", _extends({}, extraProps, {
            style: _style
          }), extra));
        } else {
          navChildren.push(React.createElement("div", extraProps, extra));
        }
      }

      var navbarCls = classnames(_defineProperty({}, "".concat(prefix, "tabs-bar"), true), className);
      return React.createElement("div", {
        className: navbarCls,
        style: style,
        ref: this.navbarRefHandler
      }, navChildren);
    }
  }]);

  return Nav;
}(React.Component);

_defineProperty(Nav, "propTypes", {
  prefix: PropTypes.string,
  rtl: PropTypes.bool,
  animation: PropTypes.bool,
  activeKey: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
  excessMode: PropTypes.string,
  extra: PropTypes.any,
  tabs: PropTypes.oneOfType([PropTypes.array, PropTypes.object]),
  tabPosition: PropTypes.string,
  tabRender: PropTypes.func,
  triggerType: PropTypes.string,
  popupProps: PropTypes.object,
  onTriggerEvent: PropTypes.func,
  onKeyDown: PropTypes.func,
  onClose: PropTypes.func,
  style: PropTypes.object,
  className: PropTypes.string
});

export default Nav;