var _excluded = ["className", "disabled", "error", "loading", "onKeyDown", "options", "value"];
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 _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 _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 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