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 = ["onClick"],
  _excluded2 = ["children", "emptyMessage"],
  _excluded3 = ["children", "currentTier", "footer", "loading", "loadingMore", "menuRef", "onNavigate", "onSearch", "onChange", "options", "value", "previousValue"],
  _excluded4 = ["className", "disabled", "error", "loading", "onKeyDown", "options", "value"];
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 _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 _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 { ChevronRight, Home, Plus } from '@procore/core-icons/dist';
import React from 'react';
import { Box } from '../Box/Box';
import { Breadcrumbs } from '../Breadcrumbs/Breadcrumbs';
import { Button } from '../Button/Button';
import { FlexList } from '../FlexList/FlexList';
import { Input } from '../Input/Input';
import { MenuImperative, useMenuImperativeControlNavigation } from '../MenuImperative/MenuImperative';
import { CloseOnFocus, OverlayTrigger, useOverlayTriggerContext } from '../OverlayTrigger/OverlayTrigger';
import { Select } from '../Select/Select';
import { Spinner } from '../Spinner/Spinner';
import { Typography } from '../Typography/Typography';
import { isEventSource } from '../_hooks/ClickOutside';
import { useI18nContext } from '../_hooks/I18n';
import { TieredSelectContext, useHighlightItemEffects } from './TieredSelect';
import { StyledTieredSelect, StyledTieredSelectArrowButton, StyledTieredSelectBreadcrumbs, StyledTieredSelectHome, StyledTieredSelectLoadingMore, StyledTieredSelectOption, StyledTieredSelectOverlay, StyledTieredSelectSpinnerOverlay } from './TieredSelect.styles';
function stopProp(e) {
  if (e.key === 'Escape' || e.key === 'Esc') {
    e.stopPropagation();
  }
}
var empty = [];
var hideKeys = {
  overlay: ['Escape', 'Esc'],
  target: ['Escape', 'Esc']
};
function ArrowButton(_ref) {
  var _onClick = _ref.onClick,
    props = _objectWithoutProperties(_ref, _excluded);
  var i18n = useI18nContext();
  return /*#__PURE__*/React.createElement(StyledTieredSelectArrowButton, _extends({
    "aria-label": i18n.t('core.tieredSelect.goToTier')
  }, props, {
    icon: /*#__PURE__*/React.createElement(ChevronRight, null),
    onClick: function onClick(event) {
      event.preventDefault();
      event.stopPropagation();
      _onClick && _onClick(event);
    },
    size: "sm",
    tabIndex: -1,
    variant: "tertiary"
  }));
}
var QuickCreateInput = /*#__PURE__*/React.forwardRef(function QuickCreateInput(_ref2, ref) {
  var autoFocus = _ref2.autoFocus,
    onSubmit = _ref2.onSubmit,
    placeholder = _ref2.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(_ref3) {
  var children = _ref3.children,
    emptyMessage = _ref3.emptyMessage,
    props = _objectWithoutProperties(_ref3, _excluded2);
  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 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,
    onNavigate = _ref4.onNavigate,
    onSearch = _ref4.onSearch,
    onChange = _ref4.onChange,
    _ref4$options = _ref4.options,
    options = _ref4$options === void 0 ? empty : _ref4$options,
    value = _ref4.value,
    previousValue = _ref4.previousValue,
    props = _objectWithoutProperties(_ref4, _excluded3);
  var _React$useContext = React.useContext(TieredSelectContext),
    getGroupId = _React$useContext.getGroupId,
    getId = _React$useContext.getId,
    getLabel = _React$useContext.getLabel,
    getNextGroupId = _React$useContext.getNextGroupId,
    i18nScope = _React$useContext.i18nScope,
    onQuickCreate = _React$useContext.onQuickCreate,
    onScrollBottom = _React$useContext.onScrollBottom;
  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) {
      var _menuRef$current3;
      var newValue = [].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 = value.slice(0, Math.max(0, value.length - 1));
      var 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();
    if (e.key === 'Right' || e.key === 'ArrowRight') {
      onNavigateForward(tier);
      return;
    }
    if (e.key === 'Left' || e.key === 'ArrowLeft') {
      onNavigateBackward();
      return;
    }
    (_menuNavigationTrigge = menuNavigationTriggerProps.onKeyDown) === null || _menuNavigationTrigge === void 0 ? void 0 : _menuNavigationTrigge.call(menuNavigationTriggerProps, e);
  }
  function onTierSelect(selection) {
    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);
  }
  function showBreadcrumbs() {
    return value.length && searchIsEmpty;
  }
  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]);
  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, null, /*#__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, null, /*#__PURE__*/React.createElement(Button, {
      block: true,
      icon: /*#__PURE__*/React.createElement(Plus, {
        size: "md"
      }),
      onClick: function onClick() {
        return setIsQuickCreating(true);
      },
      onKeyDown: handleQuickCreate,
      size: "sm"
    }, I18n.t('quickCreateActionLabel', {
      scope: i18nScope
    })));
  }, [I18n, customFooter, handleQuickCreate, i18nScope, isQuickCreating, onQuickCreate, onQuickCreateSubmit]);
  function isTierSelected(tier) {
    if (previousValue.length) {
      return getId(tier) === getId(previousValue[previousValue.length - 1]);
    }
    return false;
  }
  return /*#__PURE__*/React.createElement(StyledTieredSelectOverlay, {
    ref: ref,
    shadowStrength: 2
  }, /*#__PURE__*/React.createElement(StyledTieredSelectSpinnerOverlay, {
    "data-qa": "tiered-select-loading",
    "data-loading": loading,
    loading: loading,
    label: I18n.t('spinnerLabel', {
      scope: i18nScope
    }) || '',
    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: I18n.t('searchPlaceholder', {
      scope: i18nScope
    })
  }, 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.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(StyledTieredSelectOption, {
      item: tier,
      key: "".concat(getId(tier), "-").concat(index),
      selected: isTierSelected(tier)
    }, getLabel(tier), (getNextGroupId(tier) || onQuickCreate) && /*#__PURE__*/React.createElement(Box, {
      paddingLeft: "sm"
    }, /*#__PURE__*/React.createElement(ArrowButton, {
      "data-qa": "tiered-select-arrow",
      onClick: function onClick() {
        return onNavigateForward(tier);
      }
    })));
  }).concat(loadingMore && !loading ? [/*#__PURE__*/React.createElement(StyledTieredSelectLoadingMore, {
    "data-qa": "tiered-select-loading-more",
    key: 'tiered-select-loading-more'
  }, /*#__PURE__*/React.createElement(Spinner, {
    size: "sm"
  }))] : [])) : /*#__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
  }))));
});
export var TierSelectionTieredSelect = /*#__PURE__*/React.forwardRef(function TierSelectionTieredSelect(_ref5, ref) {
  var className = _ref5.className,
    _ref5$disabled = _ref5.disabled,
    disabled = _ref5$disabled === void 0 ? false : _ref5$disabled,
    _ref5$error = _ref5.error,
    error = _ref5$error === void 0 ? false : _ref5$error,
    _ref5$loading = _ref5.loading,
    loading = _ref5$loading === void 0 ? false : _ref5$loading,
    onKeyDown = _ref5.onKeyDown,
    _ref5$options = _ref5.options,
    options = _ref5$options === void 0 ? empty : _ref5$options,
    _ref5$value = _ref5.value,
    value = _ref5$value === void 0 ? empty : _ref5$value,
    props = _objectWithoutProperties(_ref5, _excluded4);
  var _React$useContext2 = React.useContext(TieredSelectContext),
    afterHide = _React$useContext2.afterHide,
    afterShow = _React$useContext2.afterShow,
    beforeHide = _React$useContext2.beforeHide,
    _beforeShow = _React$useContext2.beforeShow,
    block = _React$useContext2.block,
    getLabel = _React$useContext2.getLabel,
    getNextGroupId = _React$useContext2.getNextGroupId,
    getValueString = _React$useContext2.getValueString,
    i18nScope = _React$useContext2.i18nScope,
    isLeaf = _React$useContext2.isLeaf,
    onChange = _React$useContext2.onChange,
    onClear = _React$useContext2.onClear,
    onNavigate = _React$useContext2.onNavigate,
    onSearch = _React$useContext2.onSearch,
    tabIndex = _React$useContext2.tabIndex;
  var I18n = useI18nContext();
  var tieredSelectMenuRef = React.useRef(null);
  var tieredSelectButtonRef = React.useRef(null);
  var clearRef = /*#__PURE__*/React.createRef();
  var _React$useState5 = React.useState(''),
    _React$useState6 = _slicedToArray(_React$useState5, 2),
    valueString = _React$useState6[0],
    setValueString = _React$useState6[1];
  var _React$useState7 = React.useState(null),
    _React$useState8 = _slicedToArray(_React$useState7, 2),
    currentTier = _React$useState8[0],
    setCurrentTier = _React$useState8[1];

  // internal value used for navigation
  var _React$useState9 = React.useState(value),
    _React$useState10 = _slicedToArray(_React$useState9, 2),
    internalValue = _React$useState10[0],
    setInternalValue = _React$useState10[1];
  // value to reset to if navigation occurs but no selection has been made
  var _React$useState11 = React.useState(value),
    _React$useState12 = _slicedToArray(_React$useState11, 2),
    previousValue = _React$useState12[0],
    setPreviousValue = _React$useState12[1];

  // if value prop changes, update value state, current tier, and set button label
  // else open to root
  React.useEffect(function () {
    var lastEntryInValue = value[value.length - 1];
    if (value.length > 0) {
      setInternalValue(value);
      setPreviousValue(value);
      setValueString(getValueString(value));
      // show children of last tier in value
      setCurrentTier(getNextGroupId(lastEntryInValue));
    } else {
      setCurrentTier(null);
      setInternalValue([]);
      setPreviousValue([]);
      setValueString('');
    }
  }, [getValueString, getNextGroupId, isLeaf, value]);
  var internalOnChange = React.useCallback(function (selection) {
    setInternalValue(selection.value);
    setPreviousValue(selection.value);
    setValueString(getValueString(selection.value));
    setCurrentTier(getNextGroupId(selection.item));
    onChange(selection);
  }, [getNextGroupId, getValueString, onChange]);
  var internalOnNavigate = React.useCallback(function (nextGroupId, value) {
    setInternalValue(value);
    setCurrentTier(nextGroupId);
    onNavigate && onNavigate(nextGroupId, value);
  }, [onNavigate]);
  var internalOnClear = React.useCallback(function (event) {
    setValueString('');
    setInternalValue([]);
    setPreviousValue([]);
    internalOnNavigate(null, []);
    onClear && onClear(event);
  }, [internalOnNavigate, onClear]);
  var internalOnSearch = React.useCallback(function (event) {
    onSearch && onSearch(event);
  }, [onSearch]);
  var internalBeforeHide = React.useCallback(function (e) {
    var _tieredSelectMenuRef$;
    var isEscapeKey = e instanceof KeyboardEvent && (e.key === 'Escape' || e.key === 'Esc');
    var isClickOutside = e instanceof MouseEvent && !isEventSource({
      current: tieredSelectMenuRef === null || tieredSelectMenuRef === void 0 ? void 0 : (_tieredSelectMenuRef$ = tieredSelectMenuRef.current) === null || _tieredSelectMenuRef$ === void 0 ? void 0 : _tieredSelectMenuRef$.el
    }, e);
    var lastValue = previousValue[previousValue.length - 1];
    if (valueString && (isClickOutside || isEscapeKey)) {
      setInternalValue(previousValue);
      setCurrentTier(getNextGroupId(lastValue));
    }
    return beforeHide && beforeHide(e);
  }, [beforeHide, getNextGroupId, tieredSelectMenuRef, previousValue, valueString]);
  return /*#__PURE__*/React.createElement(OverlayTrigger, {
    autoFocus: true,
    afterHide: afterHide,
    afterShow: afterShow,
    beforeHide: internalBeforeHide,
    beforeShow: function beforeShow(e) {
      return _beforeShow && e.target !== clearRef.current && _beforeShow(e);
    },
    canFlip: true,
    hideKeys: hideKeys,
    overlay: /*#__PURE__*/React.createElement(TieredSelectMenu, _extends({
      currentTier: currentTier,
      options: options,
      loading: loading,
      menuRef: tieredSelectMenuRef,
      onNavigate: internalOnNavigate,
      onSearch: internalOnSearch,
      onChange: internalOnChange,
      value: internalValue,
      previousValue: previousValue
    }, props, {
      onKeyDown: stopProp
    })),
    placement: "bottom-left",
    ref: ref,
    trigger: "click"
  }, /*#__PURE__*/React.createElement(Select.Button, {
    block: block,
    className: className,
    clearRef: clearRef,
    disabled: disabled,
    error: error,
    label: valueString,
    loading: loading,
    placeholder: I18n.t('placeholder', {
      scope: i18nScope
    }),
    onClear: internalOnClear,
    ref: tieredSelectButtonRef,
    tabIndex: tabIndex
  }, valueString || I18n.t('placeholder', {
    scope: i18nScope
  })));
});
//# sourceMappingURL=TierSelectionTieredSelect.js.map