'use strict';

exports.__esModule = true;

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _propTypes = require('prop-types');

var _propTypes2 = _interopRequireDefault(_propTypes);

var _classnames = require('classnames');

var _classnames2 = _interopRequireDefault(_classnames);

var _is = require('is');

var _is2 = _interopRequireDefault(_is);

var _context2 = require('./context');

var _context3 = _interopRequireDefault(_context2);

var _tabBody = require('./tab-body');

var _tabBody2 = _interopRequireDefault(_tabBody);

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

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

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

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

var Tab = function (_React$Component) {
  _inherits(Tab, _React$Component);

  function Tab() {
    var _temp, _this, _ret;

    _classCallCheck(this, Tab);

    for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }

    return _ret = (_temp = (_this = _possibleConstructorReturn(this, _React$Component.call.apply(_React$Component, [this].concat(args))), _this), _this.handleKeyDown = function (e) {
      var nextIdent = null;
      var prevIdent = null;
      _this.context.tabIds.forEach(function (ident, key) {
        if (_this.context.activeTab === ident) {
          nextIdent = key === _this.context.tabIds.size - 1 ? _this.context.tabIds.get(0) : _this.context.tabIds.get(key + 1);
          prevIdent = key === 0 ? _this.context.tabIds.get(_this.context.tabIds.size - 1) : _this.context.tabIds.get(key - 1);
        }
      });
      if (e.key === 'ArrowRight') {
        var body = document.getElementById(_this.context.tabContainerBodyId);
        if (_this.context.tabRefs[nextIdent]) {
          _this.context.setActiveTab(nextIdent);
        } else if (!body.getElementsByClassName('ma__tab-container--nested')[0] && e.currentTarget.closest('div.ma__tab-container').parentElement.closest('div.ma__tab-container') && e.currentTarget.closest('div.ma__tab-container').parentElement.closest('div.ma__tab-container').getElementsByClassName('ma__tab-title--active')[0].nextElementSibling) {
          // If the TabContainer has a parent TabContainer, and that container has a next selectable sibling.
          if (e.currentTarget.closest('div.ma__tab-container').parentElement.closest('div.ma__tab-container') && e.currentTarget.closest('div.ma__tab-container').parentElement.closest('div.ma__tab-container').getElementsByClassName('ma__tab-title--active')[0].nextElementSibling) {
            var nextTab = e.currentTarget.closest('div.ma__tab-container').parentElement.closest('div.ma__tab-container').getElementsByClassName('ma__tab-title--active')[0].nextElementSibling.getElementsByTagName('button')[0];
            nextTab.removeAttribute('tabindex');
            nextTab.focus();
          }
        }
      }
      if (e.key === 'ArrowLeft') {
        var _body = document.getElementById(_this.context.tabContainerBodyId);
        if (_this.context.tabRefs[prevIdent]) {
          _this.context.setActiveTab(prevIdent);
        } else if (!_body.getElementsByClassName('ma__tab-container--nested')[0]) {
          // If the TabContainer has a parent TabContainer, and that container has a previous selectable sibling.
          if (e.currentTarget.closest('div.ma__tab-container').parentElement.closest('div.ma__tab-container') && e.currentTarget.closest('div.ma__tab-container').parentElement.closest('div.ma__tab-container').getElementsByClassName('ma__tab-title--active')[0].previousElementSibling) {
            var prevTab = e.currentTarget.closest('div.ma__tab-container').parentElement.closest('div.ma__tab-container').getElementsByClassName('ma__tab-title--active')[0].previousElementSibling.getElementsByTagName('button')[0];
            prevTab.removeAttribute('tabindex');
            prevTab.focus();
          }
        }
      }
    }, _temp), _possibleConstructorReturn(_this, _ret);
  }

  Tab.prototype.render = function render() {
    var _this2 = this;

    var _props = this.props,
        tabIdent = _props.tabIdent,
        active = _props.active,
        tabRef = _props.tabRef;
    var _context = this.context,
        setActiveTab = _context.setActiveTab,
        activeTab = _context.activeTab;

    var tabClasses = (0, _classnames2.default)({
      'ma__tab-title': true,
      'ma__tab-title--active': active
    });
    var buttonProps = {
      onClick: function onClick(e) {
        e.target.scrollIntoView({ behavior: 'smooth', block: 'nearest', inline: 'center' });
        e.persist();
        if (activeTab !== tabIdent) {
          setActiveTab(tabIdent);
        }
        if (_is2.default.fn(_this2.props.handleClick)) {
          _this2.props.handleClick(e, tabIdent, _this2.props.children);
        }
      },
      onKeyDown: this.handleKeyDown,
      id: tabIdent,
      'aria-selected': active,
      'aria-controls': this.context.tabContainerBodyId,
      role: 'tab',
      ref: tabRef,
      tabIndex: active ? 0 : -1
    };
    return _react2.default.createElement(
      _react2.default.Fragment,
      null,
      _react2.default.createElement(
        'li',
        { role: 'presentation', className: tabClasses },
        _react2.default.createElement(
          'button',
          buttonProps,
          this.props.title
        )
      ),
      global.window && _react2.default.createElement(
        _tabBody2.default,
        { active: activeTab === tabIdent, tabContainerBodyId: this.context.tabContainerBodyId },
        this.props.children
      )
    );
  };

  return Tab;
}(_react2.default.Component);

Tab.contextType = _context3.default;

Tab.defaultProps = {
  active: false
};

Tab.propTypes = process.env.NODE_ENV !== "production" ? {
  /** The text of the tab. */
  title: _propTypes2.default.string.isRequired,
  /** A callback function ran after the tab has been clicked. */
  handleClick: _propTypes2.default.func,
  /** Sets if the tab is the currently active tab or not. */
  active: _propTypes2.default.bool,
  /** The unique identifier set by TabContainer. */
  tabIdent: _propTypes2.default.string,
  /** Children passed to tab container (tab content) */
  children: _propTypes2.default.node,
  /** The tabs ref */
  tabRef: _propTypes2.default.oneOfType([_propTypes2.default.object, _propTypes2.default.any])
} : {};

exports.default = Tab;
module.exports = exports['default'];