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 = ["className", "disabled", "loading", "onKeyDown", "options", "value", "style"],
  _excluded2 = ["afterHide", "afterShow", "beforeHide", "beforeShow", "block", "getGroupId", "getId", "getLabel", "getNextGroupId", "i18nScope", "isTierDisabled", "onSelect", "onNavigate", "onScrollBottom", "onSearch", "tabIndex"];
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 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 _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 { Button } from '../Button/Button';
import { OverlayTrigger } from '../OverlayTrigger/OverlayTrigger';
import { TieredSelectContext } from '../TieredSelect/TieredSelect';
import { TieredSelectMenu } from '../TieredSelect/TieredSelectMenu';
import { always, defaultGetGroupId, defaultGetId, defaultGetLabel, defaultGetNextGroupId, defaultIsTierDisabled, empty, findPath, getPathKey, hideKeys, noop } from './TieredDropdown.helpers';
import { useSearch } from './useSearch';
var TieredDropdownInternal = /*#__PURE__*/React.forwardRef(function TieredDropdownInternal(_ref, ref) {
  var className = _ref.className,
    _ref$disabled = _ref.disabled,
    disabled = _ref$disabled === void 0 ? false : _ref$disabled,
    _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,
    style = _ref.style,
    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,
    getLabel = _React$useContext.getLabel,
    getGroupId = _React$useContext.getGroupId,
    getNextGroupId = _React$useContext.getNextGroupId,
    isLeaf = _React$useContext.isLeaf,
    onChange = _React$useContext.onChange,
    onNavigate = _React$useContext.onNavigate,
    onSearch = _React$useContext.onSearch,
    tabIndex = _React$useContext.tabIndex;
  var searchablePaths = React.useMemo(function () {
    if (onSearch) {
      return [];
    }
    var paths = [];
    var optionsByNextGroupId = options.reduce(function (map, option) {
      var nextGroupId = getNextGroupId(option);
      if (nextGroupId) {
        return _objectSpread(_objectSpread({}, map), {}, _defineProperty({}, nextGroupId, option));
      }
      return map;
    }, {});
    options.forEach(function (item) {
      if (!getNextGroupId(item)) {
        var path = findPath(optionsByNextGroupId, item, getGroupId);
        var pathKey = getPathKey(path, getLabel);
        paths.push({
          path: path,
          pathKey: pathKey,
          label: pathKey,
          node: item
        });
      }
    });
    return paths;
  }, [getGroupId, getLabel, getNextGroupId, onSearch, options]);
  var _useSearch = useSearch({
      items: searchablePaths,
      keysToSearch: ['pathKey']
    }),
    searchTerm = _useSearch.searchTerm,
    filteredItems = _useSearch.filteredItems,
    setSearch = _useSearch.setSearch;
  var menuOptions = React.useMemo(function () {
    return (searchTerm === null || searchTerm === void 0 ? void 0 : searchTerm.length) > 0 ? filteredItems : options;
  }, [filteredItems, options, searchTerm]);
  var tieredSelectMenuRef = React.useRef(null);
  var _React$useState = React.useState(null),
    _React$useState2 = _slicedToArray(_React$useState, 2),
    currentTier = _React$useState2[0],
    setCurrentTier = _React$useState2[1];

  // internal value used for navigation
  var _React$useState3 = React.useState(value),
    _React$useState4 = _slicedToArray(_React$useState3, 2),
    internalValue = _React$useState4[0],
    setInternalValue = _React$useState4[1];
  var internalOnNavigate = React.useCallback(function (nextGroupId, value) {
    setInternalValue(value);
    setCurrentTier(nextGroupId);
    onNavigate === null || onNavigate === void 0 ? void 0 : onNavigate(nextGroupId, value);
  }, [onNavigate]);
  var internalOnSearch = React.useCallback(function (event) {
    if (onSearch === undefined) {
      setSearch(event.target.value || '');
    } else {
      onSearch(event);
    }
  }, [onSearch, setSearch]);

  /**
   * Emulates on select
   */
  var internalOnChange = React.useCallback(function (selection) {
    if ((searchTerm === null || searchTerm === void 0 ? void 0 : searchTerm.length) > 0) {
      onChange === null || onChange === void 0 ? void 0 : onChange(_objectSpread(_objectSpread({}, selection), {}, {
        value: selection.item.path,
        item: selection.item.node
      }));
    } else {
      onChange === null || onChange === void 0 ? void 0 : onChange(selection);
    }
  }, [onChange, searchTerm]);

  /**
   * Used to reset state after selection
   */
  var internalAfterHide = React.useCallback(function () {
    setCurrentTier(null);
    setInternalValue([]);
    setSearch('');
    afterHide && afterHide();
  }, [afterHide]);

  // if value prop changes, update value state, current tier, and set button label
  // else open to root
  React.useEffect(function () {
    if ((value === null || value === void 0 ? void 0 : value.length) > 0) {
      var lastEntryInValue = value[value.length - 1];
      setInternalValue(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) || null);
      }
    } else {
      setCurrentTier(null);
      setInternalValue([]);
    }
  }, [getGroupId, getNextGroupId, isLeaf, value]);
  return /*#__PURE__*/React.createElement(OverlayTrigger, {
    afterHide: internalAfterHide,
    afterShow: afterShow,
    beforeHide: beforeHide,
    beforeShow: function beforeShow(e) {
      return _beforeShow && _beforeShow(e);
    },
    canFlip: true,
    hideKeys: hideKeys,
    overlay: disabled ? null : /*#__PURE__*/React.createElement(TieredSelectMenu, _extends({
      currentTier: currentTier,
      options: menuOptions,
      loading: loading,
      menuRef: tieredSelectMenuRef,
      onNavigate: internalOnNavigate,
      onSearch: internalOnSearch,
      onChange: internalOnChange,
      value: internalValue,
      previousValue: []
    }, props)),
    placement: "bottom-left",
    ref: ref,
    trigger: "click"
  }, /*#__PURE__*/React.createElement(Button, {
    "data-qa": props['data-qa'],
    block: block,
    className: className,
    disabled: disabled,
    icon: props.icon,
    iconRight: props.iconRight,
    loading: loading,
    size: props.size,
    style: style,
    tabIndex: tabIndex,
    variant: props.variant
  }, props.children));
});
export var TieredDropdown = /*#__PURE__*/React.forwardRef(function TieredDropdown(_ref2, ref) {
  var _ref2$afterHide = _ref2.afterHide,
    afterHide = _ref2$afterHide === void 0 ? noop : _ref2$afterHide,
    _ref2$afterShow = _ref2.afterShow,
    afterShow = _ref2$afterShow === void 0 ? noop : _ref2$afterShow,
    _ref2$beforeHide = _ref2.beforeHide,
    beforeHide = _ref2$beforeHide === void 0 ? always : _ref2$beforeHide,
    _ref2$beforeShow = _ref2.beforeShow,
    beforeShow = _ref2$beforeShow === void 0 ? always : _ref2$beforeShow,
    block = _ref2.block,
    _ref2$getGroupId = _ref2.getGroupId,
    getGroupId = _ref2$getGroupId === void 0 ? defaultGetGroupId : _ref2$getGroupId,
    _ref2$getId = _ref2.getId,
    getId = _ref2$getId === void 0 ? defaultGetId : _ref2$getId,
    _ref2$getLabel = _ref2.getLabel,
    getLabel = _ref2$getLabel === void 0 ? defaultGetLabel : _ref2$getLabel,
    _ref2$getNextGroupId = _ref2.getNextGroupId,
    getNextGroupId = _ref2$getNextGroupId === void 0 ? defaultGetNextGroupId : _ref2$getNextGroupId,
    _ref2$i18nScope = _ref2.i18nScope,
    i18nScope = _ref2$i18nScope === void 0 ? 'core.tieredDropdown' : _ref2$i18nScope,
    _ref2$isTierDisabled = _ref2.isTierDisabled,
    isTierDisabled = _ref2$isTierDisabled === void 0 ? defaultIsTierDisabled : _ref2$isTierDisabled,
    _ref2$onSelect = _ref2.onSelect,
    onSelect = _ref2$onSelect === void 0 ? noop : _ref2$onSelect,
    onNavigate = _ref2.onNavigate,
    onScrollBottom = _ref2.onScrollBottom,
    onSearch = _ref2.onSearch,
    tabIndex = _ref2.tabIndex,
    props = _objectWithoutProperties(_ref2, _excluded2);
  var isLeaf = React.useCallback(function (tier) {
    return !getNextGroupId(tier);
  }, [getNextGroupId]);
  return /*#__PURE__*/React.createElement(TieredSelectContext.Provider, {
    value: {
      afterHide: afterHide,
      afterShow: afterShow,
      beforeHide: beforeHide,
      beforeShow: beforeShow,
      block: block,
      getGroupId: getGroupId,
      getId: getId,
      getLabel: getLabel,
      getNextGroupId: getNextGroupId,
      getValueString: function getValueString() {
        return '';
      },
      i18nScope: i18nScope,
      isTierDisabled: isTierDisabled,
      isLeaf: isLeaf,
      onChange: onSelect,
      onNavigate: onNavigate,
      onScrollBottom: onScrollBottom,
      onSearch: onSearch,
      tabIndex: tabIndex
    }
  }, /*#__PURE__*/React.createElement(TieredDropdownInternal, _extends({
    ref: ref
  }, props, {
    value: []
  })));
});
//# sourceMappingURL=TieredDropdown.js.map