function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }
var _excluded = ["children"],
  _excluded2 = ["as", "disabled", "role", "active", "children", "onBlur", "onFocus", "onMount", "onUnmount", "overflowing", "dropdown", "variant"],
  _excluded3 = ["children", "className", "dark", "qa"];
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" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) 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) { var _i = null == arr ? null : "undefined" != typeof Symbol && arr[Symbol.iterator] || arr["@@iterator"]; if (null != _i) { var _s, _e, _x, _r, _arr = [], _n = !0, _d = !1; try { if (_x = (_i = _i.call(arr)).next, 0 === i) { if (Object(_i) !== _i) return; _n = !1; } else for (; !(_n = (_s = _x.call(_i)).done) && (_arr.push(_s.value), _arr.length !== i); _n = !0); } catch (err) { _d = !0, _e = err; } finally { try { if (!_n && null != _i["return"] && (_r = _i["return"](), Object(_r) !== _r)) return; } finally { if (_d) throw _e; } } return _arr; } }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); 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 = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); }
function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
function _extends() { _extends = Object.assign ? Object.assign.bind() : 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; }
import { CaretDown, CaretUp } from '@procore/core-icons/dist';
import React from 'react';
import { useButton } from '@react-aria/button';
import { MenuImperative } from '../MenuImperative/MenuImperative';
import { OverlayTrigger, useOverlayTriggerContext } from '../OverlayTrigger/OverlayTrigger';
import { useI18nContext } from '../_hooks/I18n';
import { useResize } from '../_hooks/Resize';
import { addSubcomponents } from '../_utils/addSubcomponents';
import { getBoundingRect } from '../_utils/dom';
import { mergeRefs } from '../_utils/mergeRefs';
import { StyledDropdownTab, StyledDropdownTabInner, StyledLink, StyledOverlay, StyledTab, StyledTabInner, StyledTabList, StyledTabs } from './Tabs.styles';
function noop() {}
export var Link = /*#__PURE__*/React.forwardRef(function Link(_ref, ref) {
  var children = _ref.children,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/React.createElement(StyledLink, _extends({
    ref: ref
  }, props), children);
});

/**

 We use tabs to navigate between different, but related content.
 Tabs are commonly used on tool landing pages and on item detail pages.

 @since 10.19.0

 @see [Storybook](https://procore.github.io/core/core-react/latest/?path=/story/demos-tabs--demo)

 @see [Design Guidelines](https://design.procore.com/tabs)

 */

function TabInternal(_ref2, ref) {
  var as = _ref2.as,
    disabled = _ref2.disabled,
    role = _ref2.role,
    _ref2$active = _ref2.active,
    active = _ref2$active === void 0 ? false : _ref2$active,
    children = _ref2.children,
    onBlur = _ref2.onBlur,
    onFocus = _ref2.onFocus,
    _ref2$onMount = _ref2.onMount,
    onMount = _ref2$onMount === void 0 ? noop : _ref2$onMount,
    _ref2$onUnmount = _ref2.onUnmount,
    onUnmount = _ref2$onUnmount === void 0 ? noop : _ref2$onUnmount,
    _ref2$overflowing = _ref2.overflowing,
    overflowing = _ref2$overflowing === void 0 ? false : _ref2$overflowing,
    _ref2$dropdown = _ref2.dropdown,
    dropdown = _ref2$dropdown === void 0 ? false : _ref2$dropdown,
    _ref2$variant = _ref2.variant,
    variant = _ref2$variant === void 0 ? '' : _ref2$variant,
    props = _objectWithoutProperties(_ref2, _excluded2);
  var _ref3 = props,
    onPress = _ref3.onPress;
  var _useButton = useButton(_objectSpread(_objectSpread({}, props), {}, {
      onBlur: onBlur,
      onFocus: onFocus,
      elementType: role === 'link' ? 'a' : role === 'button' ? 'button' : 'div',
      isDisabled: disabled,
      onPress: onPress,
      type: 'button'
    }), ref // TODO fix polymorphic type
    ),
    buttonProps = _useButton.buttonProps;
  var a11yProps = role === 'button' ? _objectSpread(_objectSpread({}, buttonProps), {}, {
    'aria-current': active,
    as: as || 'button',
    $clickable: !disabled
  }) : role === 'link' ? _objectSpread(_objectSpread({}, buttonProps), {}, {
    'aria-current': active,
    as: as || 'a',
    $clickable: !disabled
  }) : role === 'tab' ? {
    role: 'tab',
    onBlur: onBlur,
    onFocus: onFocus
  } : {
    onBlur: onBlur,
    onFocus: onFocus
  };
  var innerRef = React.useRef(null);
  React.useEffect(function () {
    onMount(innerRef.current);
    return onUnmount;
  }, []);
  var validChild = /*#__PURE__*/React.isValidElement(children);
  return (
    /*#__PURE__*/
    // @ts-ignore
    React.createElement(StyledTab, _extends({
      ref: mergeRefs(ref, innerRef)
    }, a11yProps, props), /*#__PURE__*/React.createElement(StyledTabInner, {
      active: active || variant === 'active',
      dark: props.dark
    }, validChild ? /*#__PURE__*/React.cloneElement(children, {
      'aria-current': active || variant === 'active' ? true : undefined
    }) : children))
  );
}
export var Tab = /*#__PURE__*/React.forwardRef(TabInternal);
export var MoreMenu = /*#__PURE__*/React.forwardRef(function MoreMenu(_ref4, ref) {
  var children = _ref4.children,
    id = _ref4.id;
  var ctx = useOverlayTriggerContext();
  var menuRef = React.useRef(null);
  React.useEffect(function () {
    var _menuRef$current, _menuRef$current$el, _menuRef$current2, _menuRef$current3;
    (_menuRef$current = menuRef.current) === null || _menuRef$current === void 0 ? void 0 : (_menuRef$current$el = _menuRef$current.el) === null || _menuRef$current$el === void 0 ? void 0 : _menuRef$current$el.focus();
    (_menuRef$current2 = menuRef.current) === null || _menuRef$current2 === void 0 ? void 0 : _menuRef$current2.highlightFirst();
    (_menuRef$current3 = menuRef.current) === null || _menuRef$current3 === void 0 ? void 0 : _menuRef$current3.highlightSelected();
  }, []);
  function onSelect(selection) {
    ctx.hide(selection.event);
  }
  return /*#__PURE__*/React.createElement(StyledOverlay, {
    ref: ref
  }, /*#__PURE__*/React.createElement(MenuImperative, {
    id: id,
    role: "menu",
    ref: menuRef,
    onSelect: onSelect
  }, /*#__PURE__*/React.createElement(MenuImperative.Options, null, React.Children.map(children, function (child, i) {
    if ( /*#__PURE__*/React.isValidElement(child)) {
      return /*#__PURE__*/React.createElement(MenuImperative.Item, {
        item: null,
        key: i,
        selected: child.props.active
      }, /*#__PURE__*/React.cloneElement(child, {
        ref: null
      }));
    }
  }))));
});
var Tabs_ = /*#__PURE__*/React.forwardRef(function Tabs(_ref5, ref) {
  var children = _ref5.children,
    className = _ref5.className,
    _ref5$dark = _ref5.dark,
    dark = _ref5$dark === void 0 ? false : _ref5$dark,
    qa = _ref5.qa,
    props = _objectWithoutProperties(_ref5, _excluded3);
  var i18n = useI18nContext();
  var _React$useState = React.useState(false),
    _React$useState2 = _slicedToArray(_React$useState, 2),
    moreMenuIsShown = _React$useState2[0],
    setMoreMenuIsShown = _React$useState2[1];
  var _React$useState3 = React.useState([]),
    _React$useState4 = _slicedToArray(_React$useState3, 2),
    tabElements = _React$useState4[0],
    setTabElements = _React$useState4[1];
  var _React$useState5 = React.useState(0),
    _React$useState6 = _slicedToArray(_React$useState5, 2),
    cutoffIndex = _React$useState6[0],
    setCutoffIndex = _React$useState6[1];
  var containerRef = React.useRef(null);
  function recalculate() {
    var container = getBoundingRect(containerRef.current);
    var _tabElements$reduce = tabElements.reduce(function (acc, el) {
        if (!el) {
          return acc;
        }
        var rect = getBoundingRect(el);
        return {
          subtotals: [].concat(_toConsumableArray(acc.subtotals), [acc.total + rect.width]),
          total: acc.total + rect.width
        };
      }, {
        subtotals: new Array(),
        total: 0
      }),
      subtotals = _tabElements$reduce.subtotals;
    var index = subtotals.findIndex(function (val) {
      return val >= container.width;
    });
    setCutoffIndex(index);
  }
  useResize({
    onResize: recalculate
  });
  React.useEffect(recalculate);
  var filtered = React.Children.toArray(children).filter(function (child) {
    return child;
  });
  var overflowing = filtered.slice(cutoffIndex - 1);
  var isOverflowingActive = React.Children.toArray(overflowing).some(function (child) {
    return /*#__PURE__*/React.isValidElement(child) && child.props.active;
  });
  return /*#__PURE__*/React.createElement(StyledTabs, _extends({
    ref: ref,
    dark: dark,
    index: cutoffIndex
  }, props), /*#__PURE__*/React.createElement(StyledTabList, {
    ref: containerRef
  }, filtered.map(function (child, i) {
    if ( /*#__PURE__*/React.isValidElement(child)) return /*#__PURE__*/React.cloneElement(child, {
      dark: dark,
      onMount: function onMount(el) {
        setTabElements(function (elements) {
          var oldElements = _toConsumableArray(elements);
          oldElements[i] = el;
          return oldElements;
        });
      },
      onUnmount: function onUnmount() {
        setTabElements(function (elements) {
          var oldElements = _toConsumableArray(elements);
          oldElements[i] = null;
          return oldElements;
        });
      }
    }); // TODO fix type
  }), /*#__PURE__*/React.createElement(OverlayTrigger, {
    autoFocus: true,
    beforeShow: function beforeShow() {
      return setMoreMenuIsShown(true);
    },
    afterHide: function afterHide() {
      return setMoreMenuIsShown(false);
    },
    trigger: "click",
    passA11yPropsToOverlay: true,
    placement: "bottom-right",
    overlay: /*#__PURE__*/React.createElement(MoreMenu, null, overflowing),
    ref: ref,
    role: "menu"
  }, /*#__PURE__*/React.createElement(StyledDropdownTab, {
    "aria-hidden": !overflowing.length,
    as: "button"
  }, /*#__PURE__*/React.createElement(StyledDropdownTabInner, {
    active: isOverflowingActive,
    dark: dark
  }, /*#__PURE__*/React.createElement(StyledLink, {
    "data-qa": qa === null || qa === void 0 ? void 0 : qa.more
  }, i18n.t('core.tabs.more')), moreMenuIsShown ? /*#__PURE__*/React.createElement(CaretUp, {
    size: "sm"
  }) : /*#__PURE__*/React.createElement(CaretDown, {
    size: "sm"
  }))))));
});
Tabs_.displayName = 'Tabs';
Link.displayName = 'Tabs.Link';

// @ts-ignore
Tab.displayName = 'Tabs.Tab';
export var Tabs = addSubcomponents({
  Link: Link,
  Tab: Tab
}, Tabs_);
//# sourceMappingURL=Tabs.js.map