var _excluded = ["className", "disabled", "error", "loading", "onKeyDown", "options", "value"];
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 _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 _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 React from 'react';
import { OverlayTrigger } from '../OverlayTrigger/OverlayTrigger';
import { Select } from '../Select/Select';
import { isEventSource } from '../_hooks/ClickOutside';
import { useI18nContext } from '../_hooks/I18n';
import { TieredSelectContext } from './TieredSelect';
import { TieredSelectMenu } from './TieredSelectMenu';
function stopProp(e) {
  if (e.key === 'Escape' || e.key === 'Esc') {
    e.stopPropagation();
  }
}
var empty = [];
var hideKeys = {
  overlay: ['Escape', 'Esc'],
  target: ['Escape', 'Esc']
};
export var LeafSelectionTieredSelect = /*#__PURE__*/React.forwardRef(function LeafSelectionTieredSelect(_ref, ref) {
  var className = _ref.className,
    _ref$disabled = _ref.disabled,
    disabled = _ref$disabled === void 0 ? false : _ref$disabled,
    _ref$error = _ref.error,
    error = _ref$error === void 0 ? false : _ref$error,
    _ref$loading = _ref.loading,
    loading = _ref$loading === void 0 ? false : _ref$loading,
    onKeyDown = _ref.onKeyDown,
    _ref$options = _ref.options,
    options = _ref$options === void 0 ? empty : _ref$options,
    _ref$value = _ref.value,
    value = _ref$value === void 0 ? empty : _ref$value,
    props = _objectWithoutProperties(_ref, _excluded);
  var _React$useContext = React.useContext(TieredSelectContext),
    afterHide = _React$useContext.afterHide,
    afterShow = _React$useContext.afterShow,
    beforeHide = _React$useContext.beforeHide,
    _beforeShow = _React$useContext.beforeShow,
    block = _React$useContext.block,
    getGroupId = _React$useContext.getGroupId,
    getNextGroupId = _React$useContext.getNextGroupId,
    getValueString = _React$useContext.getValueString,
    i18nScope = _React$useContext.i18nScope,
    isLeaf = _React$useContext.isLeaf,
    onChange = _React$useContext.onChange,
    onClear = _React$useContext.onClear,
    onNavigate = _React$useContext.onNavigate,
    onSearch = _React$useContext.onSearch,
    tabIndex = _React$useContext.tabIndex;
  var I18n = useI18nContext();
  var tieredSelectMenuRef = React.useRef(null);
  var tieredSelectButtonRef = React.useRef(null);
  var clearRef = /*#__PURE__*/React.createRef();
  var _React$useState = React.useState(''),
    _React$useState2 = _slicedToArray(_React$useState, 2),
    valueString = _React$useState2[0],
    setValueString = _React$useState2[1];
  var _React$useState3 = React.useState(null),
    _React$useState4 = _slicedToArray(_React$useState3, 2),
    currentTier = _React$useState4[0],
    setCurrentTier = _React$useState4[1];

  // internal value used for navigation
  var _React$useState5 = React.useState(value),
    _React$useState6 = _slicedToArray(_React$useState5, 2),
    internalValue = _React$useState6[0],
    setInternalValue = _React$useState6[1];
  // value to reset to if navigation occurs but no selection has been made
  var _React$useState7 = React.useState(value),
    _React$useState8 = _slicedToArray(_React$useState7, 2),
    previousValue = _React$useState8[0],
    setPreviousValue = _React$useState8[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 if not a leaf node
      // otherwise we want to show the parent of the last tier in value
      if (isLeaf && !isLeaf(lastEntryInValue)) {
        setCurrentTier(getNextGroupId(lastEntryInValue));
      } else {
        setCurrentTier(getGroupId(lastEntryInValue));
      }
    } else {
      setCurrentTier(null);
      setInternalValue([]);
      setPreviousValue([]);
      setValueString('');
    }
  }, [getGroupId, getValueString, getNextGroupId, isLeaf, value]);
  var internalOnChange = React.useCallback(function (selection) {
    setInternalValue(selection.value);
    setPreviousValue(selection.value);
    setValueString(getValueString(selection.value));
    setCurrentTier(getGroupId(selection.item));
    onChange(selection);
  }, [getGroupId, onChange, getValueString]);
  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);
      if (isLeaf && isLeaf(lastValue)) {
        setCurrentTier(getGroupId(lastValue));
      } else {
        setCurrentTier(getNextGroupId(lastValue));
      }
    }
    return beforeHide && beforeHide(e);
  }, [beforeHide, getGroupId, getNextGroupId, isLeaf, 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=LeafSelectionTieredSelect.js.map