"use strict";

function _typeof(obj) { "@babel/helpers - typeof"; 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); }

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

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

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

var _pluralize = _interopRequireDefault(require("pluralize"));

var _ = require("../..");

var _tabNavUtils = require("./tabNavUtils");

var _Tab = require("./Tab");

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 ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }

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

function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }

function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }

function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter); }

function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }

function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }

function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }

function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }

function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }

function _iterableToArrayLimit(arr, i) { if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }

function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }

var Tabs = function Tabs(_ref) {
  var inputItems = _ref.items,
      _onClick = _ref.onClick,
      activeTab = _ref.activeTab,
      setActiveTab = _ref.setActiveTab,
      secondary = _ref.secondary,
      _ref$itemType = _ref.itemType,
      itemType = _ref$itemType === void 0 ? 'tabs' : _ref$itemType;
  var activeTabId = activeTab === null || activeTab === void 0 ? void 0 : activeTab.id; // All tab items, regardless of whether they're in dropdown

  var _useState = (0, _react.useState)((0, _tabNavUtils.resetTabItems)(inputItems)),
      _useState2 = _slicedToArray(_useState, 2),
      items = _useState2[0],
      setItems = _useState2[1]; // Refs for tabs not in dropdown


  var tabRefs = (0, _react.useRef)({}); // Ref for dropdown

  var _useHideOnLostFocus = (0, _.useHideOnLostFocus)(),
      dropdownRef = _useHideOnLostFocus.ref,
      isDropdownVisible = _useHideOnLostFocus.isComponentVisible,
      setIsDropdownVisible = _useHideOnLostFocus.setIsComponentVisible; // If container resizes or order is changed, need to reset dropdown items


  var _useState3 = (0, _react.useState)(false),
      _useState4 = _slicedToArray(_useState3, 2),
      resetDropdownItems = _useState4[0],
      setResetDropdownItems = _useState4[1];

  (0, _react.useEffect)(function () {
    // Need to reset dropdown items if conatiner resized
    var onResize = function onResize() {
      return setResetDropdownItems(true);
    };

    window.addEventListener('resize', onResize);
    return function () {
      return window.removeEventListener('resize', onResize);
    };
  }, []); // On any tab click

  var _onClick2 = function onClick(tab) {
    if (tab.inDropdown) {
      setItems(function (_items) {
        // Get the items before and after this item
        var itemsThatStayInFront = _items.filter(function (i) {
          return i.firstItem && i.id !== tab.id;
        });

        var notFirstItems = _items.filter(function (i) {
          return !i.firstItem && i.id !== tab.id;
        });

        return [].concat(_toConsumableArray(itemsThatStayInFront), [tab], _toConsumableArray(notFirstItems));
      }); // Then reset dropdown items

      setResetDropdownItems(true);
    }

    setActiveTab(tab);
    _onClick && _onClick(tab.id, tab);
  };

  var _useState5 = (0, _react.useState)(true),
      _useState6 = _slicedToArray(_useState5, 2),
      determineDropdownItems = _useState6[0],
      setDetermineDropdownItems = _useState6[1];

  (0, _react.useEffect)(function () {
    // After we reset the dropdown items, then we need to redetermine what they are
    if (resetDropdownItems) {
      tabRefs.current = {};
      setItems(function (oldItems) {
        return (0, _tabNavUtils.resetTabItems)(oldItems);
      });
      setResetDropdownItems(false);
      setDetermineDropdownItems(true);
    }
  }, [resetDropdownItems]); // Also need to redetermine dropdown items if input items change

  (0, _react.useEffect)(function () {
    setItems((0, _tabNavUtils.resetTabItems)(inputItems));
    setDetermineDropdownItems(true);
  }, [inputItems]); // When container width changes, change which tabs show

  (0, _react.useLayoutEffect)(function () {
    var _dropdownRef$current;

    var _ref2 = ((_dropdownRef$current = dropdownRef.current) === null || _dropdownRef$current === void 0 ? void 0 : _dropdownRef$current.getBoundingClientRect()) || {},
        dropdownBottom = _ref2.bottom;

    if (!determineDropdownItems || !dropdownBottom) return;
    var uniqueTabBottomVals = (0, _tabNavUtils.getUniqueElementBottomVals)(tabRefs);
    var baselineBottom = uniqueTabBottomVals[0];
    var newItems = items.map(function (item) {
      var ref = tabRefs.current[item.id];

      if (!ref) {
        return item;
      } // Tab goes in dropdown if on initial render it was
      // pushed to the next line


      var _ref$getBoundingClien = ref.getBoundingClientRect(),
          refBottom = _ref$getBoundingClien.bottom;

      var inDropdown = refBottom > baselineBottom;
      return _objectSpread(_objectSpread({}, item), {}, {
        inDropdown: inDropdown
      });
    });

    if (uniqueTabBottomVals.length > 1) {
      var _dropdownRef$current2;

      // If we're using the dropdown, then we need to account for its width
      var combinedWidthReduced = 0;

      var _ref3 = ((_dropdownRef$current2 = dropdownRef.current) === null || _dropdownRef$current2 === void 0 ? void 0 : _dropdownRef$current2.getBoundingClientRect()) || {
        width: 0
      },
          dropdownWidth = _ref3.width;

      newItems.filter(function (i) {
        return !i.inDropdown;
      }).reverse().some(function (item) {
        var ref = tabRefs.current[item.id];
        var thisItem = newItems.find(function (_item) {
          return _item.id === item.id;
        });

        if (!ref || !thisItem) {
          return false;
        }

        thisItem.inDropdown = true;

        var _ref4 = (ref === null || ref === void 0 ? void 0 : ref.getBoundingClientRect()) || {},
            refWidth = _ref4.width;

        combinedWidthReduced += refWidth;

        if (combinedWidthReduced >= dropdownWidth) {
          return true;
        }

        return false;
      });
    }

    setItems(newItems);
    setDetermineDropdownItems(false);
  }, [items, dropdownRef, determineDropdownItems]);
  var dropdownItems = items.filter(function (i) {
    return i.inDropdown;
  });
  return /*#__PURE__*/_react.default.createElement("div", {
    role: "tablist",
    "aria-orientation": "horizontal",
    className: "grid-row oec-tab-nav--tab-container"
  }, items.filter(function (i) {
    return !i.inDropdown;
  }).map(function (tabItem, index) {
    return /*#__PURE__*/_react.default.createElement(_Tab.Tab, {
      key: "".concat(tabItem.id, "-").concat(index),
      tabItem: tabItem,
      tabRefs: tabRefs,
      isActiveTab: activeTabId === tabItem.id,
      onClick: _onClick2,
      secondary: secondary
    });
  }), /*#__PURE__*/_react.default.createElement("div", {
    ref: dropdownRef,
    className: (0, _classnames.default)('oec-tab-nav--dropdown', {
      'opacity-0': !dropdownItems.length
    })
  }, /*#__PURE__*/_react.default.createElement("button", {
    className: (0, _classnames.default)('oec-tab-nav--tab', {
      'oec-tab-nav--tab__secondary': secondary
    }) // We need to disable this button and sketchily hide it instead of just display: none because it has to exist before the dropdownItems are determined for layout purposes
    ,
    disabled: !dropdownItems.length,
    "aria-hidden": !dropdownItems.length,
    "aria-haspopup": !!dropdownItems.length,
    "aria-expanded": !!dropdownItems.length && isDropdownVisible,
    onClick: function onClick() {
      return setIsDropdownVisible(function (v) {
        return !v;
      });
    }
  }, "+".concat((0, _pluralize.default)(itemType, dropdownItems.length, true))), isDropdownVisible && /*#__PURE__*/_react.default.createElement("ul", {
    className: "position-absolute"
  }, dropdownItems.map(function (tabItem, index) {
    return /*#__PURE__*/_react.default.createElement("li", {
      key: "".concat(index, "-").concat(tabItem.id)
    }, /*#__PURE__*/_react.default.createElement("button", {
      id: tabItem.id,
      role: "tab",
      type: "button",
      "aria-selected": tabItem.id === activeTabId,
      onClick: function onClick() {
        _onClick2(tabItem);

        setIsDropdownVisible(false);
      },
      className: "oec-tab-nav--tab",
      title: tabItem.tabText
    }, /*#__PURE__*/_react.default.createElement("span", null, (0, _tabNavUtils.formatTabText)(tabItem))));
  }))));
};

exports.Tabs = Tabs;