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 = ["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() { _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 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 _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 { 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([]);
    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