function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
var _excluded = ["children", "emptyMessage"],
  _excluded2 = ["children", "currentTier", "footer", "loading", "loadingMore", "menuRef", "onChange", "onNavigate", "onSearch", "options", "previousValue", "value"];
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
function _toConsumableArray(r) { return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _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(r) { if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r); }
function _arrayWithoutHoles(r) { if (Array.isArray(r)) return _arrayLikeToArray(r); }
function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _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(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t["return"] && (u = t["return"](), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
function _arrayWithHoles(r) { if (Array.isArray(r)) return r; }
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }
import { ChevronRight, Help, Home, Plus } from '@procore/core-icons';
import React from 'react';
import { Box } from '../Box';
import { Breadcrumbs } from '../Breadcrumbs';
import { Button } from '../Button';
import { FlexList } from '../FlexList';
import { Input } from '../Input';
import { MenuImperative, useMenuImperativeControlNavigation } from '../MenuImperative/MenuImperative';
import { CloseOnFocus, useOverlayTriggerContext } from '../OverlayTrigger/OverlayTrigger';
import { Spinner } from '../Spinner';
import { Tooltip } from '../Tooltip';
import { Typography } from '../Typography';
import { useI18nContext } from '../_hooks/I18n';
import { TieredSelectContext, useHighlightItemEffects } from './TieredSelect';
import { StyledTieredSelect, StyledTieredSelectBreadcrumbs, StyledTieredSelectHome, StyledTieredSelectIcon, StyledTieredSelectLoadingMore, StyledTieredSelectOption, StyledTieredSelectOverlay, StyledTieredSelectSpinnerOverlay } from './TieredSelect.styles';
function ArrowButton(props) {
  return /*#__PURE__*/React.createElement(StyledTieredSelectIcon, {
    alignItems: "center",
    justifyContent: "center"
  }, /*#__PURE__*/React.createElement(ChevronRight, null));
}
function ItemTooltipIcon() {
  return /*#__PURE__*/React.createElement(StyledTieredSelectIcon, {
    alignItems: "center",
    justifyContent: "center"
  }, /*#__PURE__*/React.createElement(Help, null));
}
var QuickCreateInput = /*#__PURE__*/React.forwardRef(function QuickCreateInput(_ref, ref) {
  var autoFocus = _ref.autoFocus,
    onSubmit = _ref.onSubmit,
    placeholder = _ref.placeholder;
  function onKeyDown(e) {
    if (e.key === 'Enter') {
      onSubmit(e.currentTarget.value);
    }
  }
  return /*#__PURE__*/React.createElement(Box, {
    flexGrow: "1",
    justifyContent: "center",
    padding: "md"
  }, /*#__PURE__*/React.createElement(Input, {
    autoFocus: autoFocus,
    onKeyDown: onKeyDown,
    placeholder: placeholder,
    ref: ref
  }));
});
function Options(_ref2) {
  var children = _ref2.children,
    emptyMessage = _ref2.emptyMessage,
    props = _objectWithoutProperties(_ref2, _excluded);
  if (React.Children.count(children) === 0) {
    return /*#__PURE__*/React.createElement(MenuImperative.Options, null, /*#__PURE__*/React.createElement(Box, _extends({
      paddingLeft: "lg"
    }, props), /*#__PURE__*/React.createElement(Typography, {
      color: "gray45",
      intent: "small",
      italic: true
    }, emptyMessage)));
  }
  return /*#__PURE__*/React.createElement(MenuImperative.Options, null, children);
}
var RenderMenuItem = function RenderMenuItem(_ref3) {
  var _isTierDisabled;
  var tier = _ref3.tier,
    selected = _ref3.selected,
    index = _ref3.index,
    onNavigateForward = _ref3.onNavigateForward;
  var _React$useContext = React.useContext(TieredSelectContext),
    isTierDisabled = _React$useContext.isTierDisabled,
    getNextGroupId = _React$useContext.getNextGroupId,
    onQuickCreate = _React$useContext.onQuickCreate,
    getLabel = _React$useContext.getLabel,
    getId = _React$useContext.getId;
  var tooltip = (_isTierDisabled = isTierDisabled === null || isTierDisabled === void 0 ? void 0 : isTierDisabled(tier)) !== null && _isTierDisabled !== void 0 ? _isTierDisabled : false;
  var isDisabled = Boolean(tooltip);
  var showNextTierArrow = !tooltip && (Boolean(getNextGroupId(tier)) || Boolean(onQuickCreate));
  var overlay = typeof tooltip === 'string' ? tooltip : null;
  var menuItem = /*#__PURE__*/React.createElement(StyledTieredSelectOption, {
    disabled: isDisabled,
    item: tier,
    selected: selected
  }, /*#__PURE__*/React.createElement(React.Fragment, null, getLabel(tier), showNextTierArrow && /*#__PURE__*/React.createElement(Box, {
    paddingLeft: "sm"
  }, /*#__PURE__*/React.createElement(ArrowButton, {
    "data-qa": "tiered-select-arrow",
    onClick: function onClick() {
      return onNavigateForward(tier);
    }
  })), tooltip && /*#__PURE__*/React.createElement(Box, {
    paddingLeft: "sm"
  }, /*#__PURE__*/React.createElement(ItemTooltipIcon, null))));
  if (isDisabled && overlay) {
    return /*#__PURE__*/React.createElement(Tooltip, {
      key: "".concat(getId(tier), "-").concat(index, "-tooltip"),
      overlay: overlay,
      trigger: 'hover',
      placement: "right"
    }, menuItem);
  }
  return menuItem;
};
export var TieredSelectMenu = /*#__PURE__*/React.forwardRef(function TieredSelectMenu(_ref4, ref) {
  var children = _ref4.children,
    currentTier = _ref4.currentTier,
    customFooter = _ref4.footer,
    loading = _ref4.loading,
    loadingMore = _ref4.loadingMore,
    menuRef = _ref4.menuRef,
    onChange = _ref4.onChange,
    onNavigate = _ref4.onNavigate,
    onSearch = _ref4.onSearch,
    _ref4$options = _ref4.options,
    options = _ref4$options === void 0 ? [] : _ref4$options,
    previousValue = _ref4.previousValue,
    value = _ref4.value,
    props = _objectWithoutProperties(_ref4, _excluded2);
  var _React$useContext2 = React.useContext(TieredSelectContext),
    getGroupId = _React$useContext2.getGroupId,
    getId = _React$useContext2.getId,
    getLabel = _React$useContext2.getLabel,
    getNextGroupId = _React$useContext2.getNextGroupId,
    i18nScope = _React$useContext2.i18nScope,
    isTierDisabled = _React$useContext2.isTierDisabled,
    onQuickCreate = _React$useContext2.onQuickCreate,
    onScrollBottom = _React$useContext2.onScrollBottom,
    searchPlaceholder = _React$useContext2.searchPlaceholder;
  var quickCreateRef = React.useRef(null);
  var _useOverlayTriggerCon = useOverlayTriggerContext(),
    hide = _useOverlayTriggerCon.hide;
  var I18n = useI18nContext();
  var _React$useState = React.useState(false),
    _React$useState2 = _slicedToArray(_React$useState, 2),
    isQuickCreating = _React$useState2[0],
    setIsQuickCreating = _React$useState2[1];
  var _React$useState3 = React.useState(''),
    _React$useState4 = _slicedToArray(_React$useState3, 2),
    searchValue = _React$useState4[0],
    setSearchValue = _React$useState4[1];
  var _useMenuImperativeCon = useMenuImperativeControlNavigation(menuRef),
    menuProps = _useMenuImperativeCon.menuProps,
    menuNavigationTriggerProps = _useMenuImperativeCon.menuNavigationTriggerProps;
  var searchIsEmpty = searchValue === '';
  var lastEntryInValue = value[value.length - 1];
  var internalOnSearch = React.useCallback(function (e) {
    setSearchValue(e.target.value);
    onSearch && onSearch(e);
  }, [onSearch]);

  // When searching (all options have been flattened) we dont filter by id
  var filteredOptions = React.useMemo(function () {
    return searchIsEmpty ? options.filter(function (tier) {
      return getGroupId(tier) === currentTier;
    }) : options;
  }, [currentTier, getGroupId, options, searchIsEmpty]);
  useHighlightItemEffects({
    currentTier: currentTier,
    searchValue: searchValue,
    menuRef: menuRef,
    loading: loading,
    loadingMore: loadingMore
  });
  var onNavigateHome = React.useCallback(function () {
    var _menuRef$current;
    onNavigate(null, []);
    (_menuRef$current = menuRef.current) === null || _menuRef$current === void 0 ? void 0 : _menuRef$current.highlightFirst();
  }, [menuRef, onNavigate]);
  var onBreadCrumbNavigate = React.useCallback(function (tier) {
    var _menuRef$current2;
    var newTier = value.indexOf(tier);
    onNavigate(getNextGroupId(tier), value.slice(0, newTier + 1));
    (_menuRef$current2 = menuRef.current) === null || _menuRef$current2 === void 0 ? void 0 : _menuRef$current2.highlightFirst();
  }, [getNextGroupId, menuRef, onNavigate, value]);
  function onNavigateForward(tier) {
    if (searchIsEmpty && !isQuickCreating && tier && !isLeaf(tier)) {
      var _menuRef$current3;
      // if last value was a leaf, replace it when performing next navigation
      var newValue = lastEntryInValue && isLeaf(lastEntryInValue) ? [].concat(_toConsumableArray(value.slice(0, value.length - 1)), [tier]) : [].concat(_toConsumableArray(value), [tier]);
      onNavigate(getNextGroupId(tier), newValue);
      (_menuRef$current3 = menuRef.current) === null || _menuRef$current3 === void 0 ? void 0 : _menuRef$current3.highlightFirst();
    }
  }

  /**
   * need to skip back two levels if coming from a leaf node;
   * out from the leaf and then out of the parent. this is because
   * when tiers aren't selectectable we show the parent of the leaf
   */
  function onNavigateBackward() {
    if (value.length !== 0 && searchIsEmpty) {
      var _menuRef$current4;
      var newValue;
      var newTier;
      if (isLeaf(value[value.length - 1])) {
        newValue = value.slice(0, Math.max(0, value.length - 2));
        newTier = value[Math.max(0, value.length - 2)];
      } else {
        newValue = value.slice(0, Math.max(0, value.length - 1));
        newTier = value[value.length - 1];
      }
      !isQuickCreating && onNavigate(getGroupId(newTier), newValue);
      (_menuRef$current4 = menuRef.current) === null || _menuRef$current4 === void 0 ? void 0 : _menuRef$current4.highlightFirst();
    }
  }
  function onKeyDown(e) {
    var _menuRef$current5, _menuNavigationTrigge;
    var tier = (_menuRef$current5 = menuRef.current) === null || _menuRef$current5 === void 0 ? void 0 : _menuRef$current5.highlighted();
    var isDisabled = isTierDisabled === null || isTierDisabled === void 0 ? void 0 : isTierDisabled(tier);
    if (e.key === 'Right' || e.key === 'ArrowRight') {
      if (isDisabled) {
        return;
      }
      onNavigateForward(tier);
      return;
    }
    if (e.key === 'Left' || e.key === 'ArrowLeft') {
      if (isDisabled) {
        return;
      }
      onNavigateBackward();
      return;
    }
    (_menuNavigationTrigge = menuNavigationTriggerProps.onKeyDown) === null || _menuNavigationTrigge === void 0 ? void 0 : _menuNavigationTrigge.call(menuNavigationTriggerProps, e);
  }
  var isLeaf = React.useCallback(function (tier) {
    return !getNextGroupId(tier);
  }, [getNextGroupId]);
  function onTierSelect(selection) {
    if (isLeaf(selection.item)) {
      var isSameGroup = value.length ? getGroupId(lastEntryInValue) === getGroupId(selection.item) : false;

      // if the selection is in the same group as the old selection, replace the old selection
      var newValue = isSameGroup ? [].concat(_toConsumableArray(value.slice(0, value.length - 1)), [selection.item]) : [].concat(_toConsumableArray(value), [selection.item]);
      onChange(_objectSpread(_objectSpread({}, selection), {}, {
        value: newValue
      }));
      searchValue && internalOnSearch({
        target: {
          value: ''
        }
      });
      hide(selection.event);
    } else {
      onNavigateForward(selection.item);
    }
  }

  // non-selectable tiers can have a leaf node in the root tier, so if selected
  // it will reopen to the root tier and we should not show breadcrumbs
  function showBreadcrumbs() {
    return value.length && searchIsEmpty && !(value.length === 1 && isLeaf(value[value.length - 1]));
  }
  var menuEmptyMessage = searchIsEmpty ? I18n.t('emptyMessage', {
    scope: i18nScope
  }) : I18n.t('searchEmptyMessage', {
    scope: i18nScope
  });
  var handleQuickCreate = React.useCallback(function (e) {
    // stops menu from selecting item and closing on enter press
    e.stopPropagation();
    if (e.key === 'Enter') {
      setIsQuickCreating(true);
    }
  }, [setIsQuickCreating]);
  var onQuickCreateSubmit = React.useCallback(function () {
    onQuickCreate && quickCreateRef.current && onQuickCreate(quickCreateRef.current.value);
    setIsQuickCreating(false);
  }, [onQuickCreate, quickCreateRef, setIsQuickCreating]);
  function isTierSelected(tier) {
    if (previousValue.length) {
      return getId(tier) === getId(previousValue[previousValue.length - 1]);
    }
    return false;
  }
  function RenderLoadingMore() {
    return /*#__PURE__*/React.createElement(StyledTieredSelectLoadingMore, {
      "data-qa": "tiered-select-loading-more"
    }, /*#__PURE__*/React.createElement(Spinner, {
      size: "sm"
    }));
  }
  var RenderFooter = React.useCallback(function () {
    if (customFooter) {
      // Render custom footer, if defined.
      if (typeof customFooter === 'function') {
        return /*#__PURE__*/React.createElement(MenuImperative.Footer, null, customFooter({}));
      }
      return /*#__PURE__*/React.createElement(MenuImperative.Footer, null, customFooter);
    }
    if (onQuickCreate === undefined) {
      // no footer if `onQuickCreate` is not defined.
      return null;
    }
    if (isQuickCreating) {
      // Render `Cancel` and `Create` labels if "quick creating".
      return /*#__PURE__*/React.createElement(MenuImperative.Footer, {
        "data-something": "true"
      }, /*#__PURE__*/React.createElement(FlexList, {
        size: "xs",
        justifyContent: "flex-end"
      }, /*#__PURE__*/React.createElement(Button, {
        onClick: function onClick() {
          return setIsQuickCreating(false);
        },
        size: "sm",
        variant: "tertiary"
      }, I18n.t('quickCreateCancelLabel', {
        scope: i18nScope
      })), /*#__PURE__*/React.createElement(Button, {
        onClick: onQuickCreateSubmit,
        size: "sm"
      }, I18n.t('quickCreateCreateLabel', {
        scope: i18nScope
      }))));
    }
    return /*#__PURE__*/React.createElement(MenuImperative.Footer, {
      "data-something": "true"
    }, /*#__PURE__*/React.createElement(Button, {
      block: true,
      size: "sm",
      icon: /*#__PURE__*/React.createElement(Plus, null),
      onClick: function onClick() {
        return setIsQuickCreating(true);
      },
      onKeyDown: handleQuickCreate
    }, I18n.t('quickCreateActionLabel', {
      scope: i18nScope
    })));
  }, [I18n, customFooter, handleQuickCreate, i18nScope, isQuickCreating, onQuickCreate, onQuickCreateSubmit]);
  return /*#__PURE__*/React.createElement(StyledTieredSelectOverlay, {
    ref: ref,
    shadowStrength: 2
  }, /*#__PURE__*/React.createElement(StyledTieredSelectSpinnerOverlay, {
    "data-qa": "tiered-select-loading",
    "data-loading": loading,
    label: I18n.t('spinnerLabel', {
      scope: i18nScope
    }) || '',
    loading: loading,
    size: "md"
  }, /*#__PURE__*/React.createElement(StyledTieredSelect, _extends({
    onScrollBottom: onScrollBottom,
    onSelect: onTierSelect,
    ref: menuRef
  }, props, menuProps, {
    role: "none"
  }), /*#__PURE__*/React.createElement(MenuImperative.Header, null, !isQuickCreating && /*#__PURE__*/React.createElement(MenuImperative.Search, _extends({
    autoComplete: "false",
    onChange: internalOnSearch,
    placeholder: searchPlaceholder || I18n.t('searchPlaceholder', {
      scope: i18nScope
    }),
    value: searchValue
  }, menuNavigationTriggerProps, {
    onKeyDown: onKeyDown
  })), showBreadcrumbs() ? /*#__PURE__*/React.createElement(StyledTieredSelectBreadcrumbs, {
    $nonInteractive: isQuickCreating
  }, /*#__PURE__*/React.createElement(Breadcrumbs.Crumb, {
    onClick: onNavigateHome
  }, /*#__PURE__*/React.createElement(StyledTieredSelectHome, {
    alignItems: "center",
    justifyContent: "center"
  }, /*#__PURE__*/React.createElement(Home, {
    "data-qa": "tiered-select-home"
  }))), value.filter(function (tier) {
    // we reopen to the parent of leaf nodes, so don't show that breadcrumb
    return !isLeaf(tier);
  }).map(function (tier, index, array) {
    return /*#__PURE__*/React.createElement(Breadcrumbs.Crumb, {
      active: index === array.length - 1,
      key: "".concat(getId(tier), "-").concat(index),
      onClick: function onClick() {
        return onBreadCrumbNavigate(tier);
      }
    }, getLabel(tier));
  })) : null), !isQuickCreating ? /*#__PURE__*/React.createElement(Options, {
    emptyMessage: menuEmptyMessage
  }, filteredOptions.map(function (tier, index) {
    return /*#__PURE__*/React.createElement(RenderMenuItem, {
      key: "menu-item-".concat(getId(tier), "-").concat(index, "}"),
      tier: tier,
      selected: isTierSelected(tier),
      index: index,
      onNavigateForward: onNavigateForward
    });
  }).concat(loadingMore && !loading ? [/*#__PURE__*/React.createElement(RenderLoadingMore, {
    key: "tiered-select-loading-more"
  })] : [])) : /*#__PURE__*/React.createElement(QuickCreateInput, {
    autoFocus: isQuickCreating,
    onSubmit: onQuickCreateSubmit,
    placeholder: I18n.t('quickCreatePlaceholder', {
      scope: i18nScope
    }),
    ref: quickCreateRef
  }), /*#__PURE__*/React.createElement(RenderFooter, null), /*#__PURE__*/React.createElement(CloseOnFocus, {
    hide: hide
  }))));
});
//# sourceMappingURL=TieredSelectMenu.js.map