"use strict";

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

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

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

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

var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));

var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass"));

var _assertThisInitialized2 = _interopRequireDefault(require("@babel/runtime/helpers/assertThisInitialized"));

var _inherits2 = _interopRequireDefault(require("@babel/runtime/helpers/inherits"));

var _possibleConstructorReturn2 = _interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn"));

var _getPrototypeOf2 = _interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf"));

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

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

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

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

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

var _js = require("../../globals/js");

var _excluded = ["ariaLabel", "disableAnimation", "inline", "className", "customTabContent", "triggerHref", "role", "onSelectionChange"];

function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = (0, _getPrototypeOf2.default)(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = (0, _getPrototypeOf2.default)(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return (0, _possibleConstructorReturn2.default)(this, result); }; }

function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }

var prefix = _js.settings.prefix;
/** Tabs allow users to navigate easily between views within the same context */

var Tabs = /*#__PURE__*/function (_React$Component) {
  (0, _inherits2.default)(Tabs, _React$Component);

  var _super = _createSuper(Tabs);

  function Tabs(props) {
    var _this;

    (0, _classCallCheck2.default)(this, Tabs);
    _this = _super.call(this, props);
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "getTabAt", function (index) {
      return _this["tab".concat(index)] || _react.default.Children.toArray(_this.props.children)[index];
    });
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "getSizes", function () {
      if (_this.rootRef.current === null || _this.rootRef.current.length > 1) {
        return null;
      }

      var rootBounds = _this.rootRef.current.getBoundingClientRect();

      var sizes = {};
      Object.values(_this.rootRef.current.children).forEach(function (el, key) {
        var bounds = el.children[0].getBoundingClientRect();
        var left = bounds.left - rootBounds.left;
        var right = rootBounds.right - bounds.right;
        sizes[key] = {
          left: left,
          right: right
        };
      });

      _this.setState({
        sizes: sizes
      });

      return sizes;
    });
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "setTabAt", function (index, tabRef) {
      _this["tab".concat(index)] = tabRef;
    });
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "handleTabClick", function (onSelectionChange) {
      return function (index, label, evt) {
        if (evt) {
          evt.preventDefault();
        }

        _this.selectTabAt(index, onSelectionChange);
      };
    });
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "handleTabKeyDown", function (onSelectionChange) {
      return function (index, label, evt) {
        var key = evt.key || evt.which;

        if (key === 'Enter' || key === 13 || key === ' ' || key === 32) {
          _this.selectTabAt(index, onSelectionChange);
        }
      };
    });
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "handleTabAnchorFocus", function (onSelectionChange) {
      return function (index) {
        var tabCount = _react.default.Children.count(_this.props.children) - 1;
        var tabIndex = index;

        if (index < 0) {
          tabIndex = tabCount;
        } else if (index > tabCount) {
          tabIndex = 0;
        }

        var tab = _this.getTabAt(tabIndex);

        if (tab) {
          _this.selectTabAt(tabIndex, onSelectionChange);

          if (tab.tabAnchor) {
            tab.tabAnchor.focus();
          }
        }
      };
    });
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "selectTabAt", function (index, onSelectionChange) {
      if (_this.state.selected !== index) {
        _this.setState({
          selected: index
        });

        if (typeof onSelectionChange === 'function') {
          onSelectionChange(index);
        }
      }
    });
    _this.state = {}; // Create the ref

    _this.rootRef = /*#__PURE__*/_react.default.createRef();
    return _this;
  }

  (0, _createClass2.default)(Tabs, [{
    key: "componentDidMount",
    value: function componentDidMount() {
      this.getSizes();
      window.addEventListener('resize', this.getSizes);
    }
  }, {
    key: "componentWillUnmount",
    value: function componentWillUnmount() {
      window.removeEventListener('resize', this.getSizes);
    }
  }, {
    key: "getTabs",
    value: function getTabs() {
      return _react.default.Children.map(this.props.children, function (tab) {
        return tab;
      });
    }
  }, {
    key: "render",
    value: function render() {
      var _this2 = this;

      var _this$props = this.props,
          ariaLabel = _this$props.ariaLabel,
          disableAnimation = _this$props.disableAnimation,
          inline = _this$props.inline,
          className = _this$props.className,
          customTabContent = _this$props.customTabContent,
          triggerHref = _this$props.triggerHref,
          role = _this$props.role,
          onSelectionChange = _this$props.onSelectionChange,
          other = (0, _objectWithoutProperties2.default)(_this$props, _excluded);
      var _this$state = this.state,
          selected = _this$state.selected,
          sizes = _this$state.sizes;
      var tabsWithProps = this.getTabs().map(function (tab, index) {
        var newTab = /*#__PURE__*/_react.default.cloneElement(tab, {
          index: index,
          selected: index === selected,
          handleTabClick: _this2.handleTabClick(onSelectionChange),
          handleTabAnchorFocus: _this2.handleTabAnchorFocus(onSelectionChange),
          ref: function ref(e) {
            _this2.setTabAt(index, e);
          },
          handleTabKeyDown: _this2.handleTabKeyDown(onSelectionChange)
        });

        return newTab;
      });
      var tabContentWithProps = !customTabContent ? _react.default.Children.map(tabsWithProps, function (tab) {
        var _tab$props = tab.props,
            children = _tab$props.children,
            selected = _tab$props.selected;

        if (!children) {
          return null;
        }

        return /*#__PURE__*/_react.default.createElement(_TabContent.default, {
          className: "".concat(prefix, "--tab-content"),
          "aria-hidden": !selected,
          hidden: !selected,
          selected: selected
        }, children);
      }) : null;
      var classes = {
        tabs: (0, _classnames.default)("".concat(prefix, "--tabs"), (0, _defineProperty2.default)({}, "".concat(prefix, "--tabs--no-animation"), disableAnimation), className),
        tablist: (0, _classnames.default)("".concat(prefix, "--tabs__nav"), (0, _defineProperty2.default)({}, "".concat(prefix, "--tabs__nav--inline"), inline))
      };
      var sizeBar = sizes ? sizes[selected] : undefined;
      return /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement("nav", (0, _extends2.default)({}, other, {
        className: classes.tabs,
        role: role
      }), /*#__PURE__*/_react.default.createElement("div", {
        className: "".concat(prefix, "--tabs__nav__bar"),
        style: sizeBar
      }), /*#__PURE__*/_react.default.createElement("ul", {
        ref: this.rootRef,
        role: "tablist",
        className: classes.tablist
      }, tabsWithProps)), tabContentWithProps);
    }
  }], [{
    key: "getDerivedStateFromProps",
    value: function getDerivedStateFromProps(_ref, state) {
      var selected = _ref.selected;
      var prevSelected = state.prevSelected;
      return prevSelected === selected ? null : {
        selected: selected,
        prevSelected: selected
      };
    }
  }]);
  return Tabs;
}(_react.default.Component);

(0, _defineProperty2.default)(Tabs, "propTypes", {
  /**
   * Specify the text to be read by screen-readers when visiting the <Tabs>
   * component
   */
  ariaLabel: _propTypes.default.string,

  /**
   * Pass in a collection of <Tab> children to be rendered depending on the
   * currently selected tab
   */
  children: _propTypes.default.node,

  /**
   * Provide a className that is applied to the root <nav> component for the
   * <Tabs>
   */
  className: _propTypes.default.string,

  /**
   * Provide a customTabContent by using independent action triggers
   * inside the Tabs
   */
  customTabContent: _propTypes.default.bool,

  /**
   * Specify whether the animation should be used
   */
  disableAnimation: _propTypes.default.bool,

  /**
   * Specify whether the Tabs are displayed inline
   */
  inline: _propTypes.default.bool,

  /**
   * Specify whether the Tab content is hidden
   */
  hidden: _propTypes.default.bool,

  /**
   * By default, this value is "navigation". You can also provide an alternate
   * role if it makes sense from the accessibility-side
   */
  role: _propTypes.default.string.isRequired,

  /**
   * Optionally provide an `onClick` handler that is invoked when a <Tab> is
   * clicked
   */
  onClick: _propTypes.default.func,

  /**
   * Optionally provide an `onKeyDown` handler that is invoked when keyed
   * navigation is triggered
   */
  onKeyDown: _propTypes.default.func,

  /**
   * Provide an optional handler that is called whenever the selection
   * changes. This method is called with the index of the tab that was
   * selected
   */
  onSelectionChange: _propTypes.default.func,

  /**
   * Provide a string that represents the `href` for the triggered <Tab>
   */
  triggerHref: _propTypes.default.string.isRequired,

  /**
   * Optionally provide an index for the currently selected <Tab>
   */
  selected: _propTypes.default.number
});
(0, _defineProperty2.default)(Tabs, "defaultProps", {
  role: 'navigation',
  triggerHref: '#',
  selected: 0,
  ariaLabel: 'listbox'
});
var _default = Tabs;
exports.default = _default;