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 = ["getId", "getLabel", "disabled", "value"],
  _excluded2 = ["value", "options", "groups", "getId", "getLabel", "getGroup", "getOptGroup", "onChange", "onSearch", "optionRenderer", "groupRenderer", "optGroupRenderer"];
function _toConsumableArray(r) { return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _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(r) { if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r); }
function _arrayWithoutHoles(r) { if (Array.isArray(r)) return _arrayLikeToArray(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 _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 _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 _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 { MenuImperative } from '../MenuImperative/MenuImperative';
import { MultiSelect } from '../MultiSelect';
import { StyledGroupSelectOption } from './GroupSelect.styles';
var emptyArray = [];
var noop = function noop() {};
var defaultGetId = function defaultGetId(item) {
  return item.id;
};
var defaultGetLabel = function defaultGetLabel(item) {
  return item.label;
};
var defaultGetGroup = function defaultGetGroup(item) {
  return item.options;
};
var defaultGetOptGroup = function defaultGetOptGroup(item) {
  return item.groupId;
};
function defaultOptionRenderer(item, _ref) {
  var getId = _ref.getId,
    getLabel = _ref.getLabel,
    _ref$disabled = _ref.disabled,
    disabled = _ref$disabled === void 0 ? false : _ref$disabled,
    value = _ref.value,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/React.createElement(StyledGroupSelectOption, _extends({}, props, {
    key: "group-select-menu-item-".concat(getId(item)),
    value: value || item,
    disabled: disabled
  }), getLabel(item));
}
function defaultOptGroupRenderer(_ref2) {
  var id = _ref2.id,
    label = _ref2.label;
  return /*#__PURE__*/React.createElement(MenuImperative.Group, {
    key: "group_".concat(id),
    clickable: false
  }, label);
}
function useGroupSelect(_ref3) {
  var value = _ref3.value,
    options = _ref3.options,
    groups = _ref3.groups,
    getId = _ref3.getId,
    getLabel = _ref3.getLabel,
    getGroup = _ref3.getGroup,
    onChange = _ref3.onChange,
    _onSearch = _ref3.onSearch;
  var _React$useState = React.useState(''),
    _React$useState2 = _slicedToArray(_React$useState, 2),
    searchValue = _React$useState2[0],
    setSearchValue = _React$useState2[1];
  var groupOptionsDictionary = React.useMemo(function () {
    return groups.reduce(function (acc, curr) {
      return _objectSpread(_objectSpread({}, acc), {}, _defineProperty({}, getId(curr), getGroup(curr)));
    }, {});
  }, [getGroup, getId, groups]);
  var collectOptionIds = React.useCallback(function (value) {
    return value.reduce(function (acc, cur) {
      return acc.add(getId(cur));
    }, new Set());
  }, [getId]);
  var groupIds = React.useMemo(function () {
    return collectOptionIds(groups);
  }, [collectOptionIds, groups]);
  var isGroup = function isGroup(groupdId) {
    return groupIds.has(groupdId);
  };
  var externalOnSearch = React.useCallback(function (e) {
    if (_onSearch) {
      _onSearch(e);
    }
  }, [_onSearch]);
  var internalOnSearch = React.useCallback(function (e) {
    setSearchValue(e.target.value);
  }, []);
  var onSearch = _onSearch ? externalOnSearch : internalOnSearch;
  var selectedOptions = React.useMemo(function () {
    return value.filter(function (option) {
      return !groupIds.has(getId(option));
    });
  }, [getId, groupIds, value]);
  var selectedOptionIds = React.useMemo(function () {
    return collectOptionIds(selectedOptions);
  }, [collectOptionIds, selectedOptions]);
  var selectedGroups = React.useMemo(function () {
    return groups.filter(function (group) {
      return getGroup(group).length && getGroup(group).every(function (option) {
        return selectedOptionIds.has(getId(option));
      });
    });
  }, [getGroup, getId, groups, selectedOptionIds]);
  var selectedGroupIds = React.useMemo(function () {
    return collectOptionIds(selectedGroups);
  }, [collectOptionIds, selectedGroups]);
  var getGroupOptions = function getGroupOptions(groupOptiodId) {
    var groupOptions = groupOptionsDictionary[groupOptiodId] || [];
    return groupOptions.filter(function (groupOption) {
      return !selectedOptionIds.has(getId(groupOption));
    });
  };
  var onSelect = function onSelect(selection) {
    var newSelected = selection.reduce(function (acc, option) {
      var optionId = getId(option);
      if (isGroup(optionId)) {
        return !selectedGroupIds.has(optionId) ? [].concat(_toConsumableArray(acc), _toConsumableArray(getGroupOptions(optionId))) : acc;
      }
      return [].concat(_toConsumableArray(acc), [option]);
    }, []);
    setSearchValue('');
    onChange(newSelected);
  };
  var searchFilterCallback = React.useCallback(function (option) {
    return getLabel(option).toLowerCase().includes(searchValue.toLowerCase());
  }, [getLabel, searchValue]);
  var computedOptions = _onSearch ? options : options.filter(searchFilterCallback);
  var filteredGroups = _onSearch ? groups : groups.filter(searchFilterCallback);
  var computedGroups = React.useMemo(function () {
    return filteredGroups.filter(function (group) {
      return getGroup(group).length;
    });
  }, [filteredGroups, getGroup]);
  return {
    selectedOptions: selectedOptions,
    computedOptions: [].concat(_toConsumableArray(computedGroups), _toConsumableArray(computedOptions)),
    selectedOptionIds: selectedOptionIds,
    selectedGroupIds: selectedGroupIds,
    isGroup: isGroup,
    onSearch: onSearch,
    onSelect: onSelect
  };
}

/**

 Group select allows users to select multiple options from a single item in a
 menu. Other select components are multi select, and select, tiered select.

 @since 10.19.0

 @see [Storybook](https://stories.core.procore.com/?path=/story/core-react_demos-groupselect--custom-search)

 @see [Design Guidelines](https://design.procore.com/group-select)

 */
export var GroupSelect = /*#__PURE__*/React.forwardRef(function GroupSelect(_ref4, ref) {
  var _ref4$value = _ref4.value,
    value = _ref4$value === void 0 ? emptyArray : _ref4$value,
    _ref4$options = _ref4.options,
    options = _ref4$options === void 0 ? emptyArray : _ref4$options,
    _ref4$groups = _ref4.groups,
    groups = _ref4$groups === void 0 ? emptyArray : _ref4$groups,
    _ref4$getId = _ref4.getId,
    getId = _ref4$getId === void 0 ? defaultGetId : _ref4$getId,
    _ref4$getLabel = _ref4.getLabel,
    getLabel = _ref4$getLabel === void 0 ? defaultGetLabel : _ref4$getLabel,
    _ref4$getGroup = _ref4.getGroup,
    getGroup = _ref4$getGroup === void 0 ? defaultGetGroup : _ref4$getGroup,
    _ref4$getOptGroup = _ref4.getOptGroup,
    getOptGroup = _ref4$getOptGroup === void 0 ? defaultGetOptGroup : _ref4$getOptGroup,
    _ref4$onChange = _ref4.onChange,
    onChange = _ref4$onChange === void 0 ? noop : _ref4$onChange,
    _onSearch = _ref4.onSearch,
    optionRenderer = _ref4.optionRenderer,
    groupRenderer = _ref4.groupRenderer,
    _ref4$optGroupRendere = _ref4.optGroupRenderer,
    optGroupRenderer = _ref4$optGroupRendere === void 0 ? defaultOptGroupRenderer : _ref4$optGroupRendere,
    props = _objectWithoutProperties(_ref4, _excluded2);
  var _useGroupSelect = useGroupSelect({
      value: value,
      options: options,
      groups: groups,
      getId: getId,
      getLabel: getLabel,
      getGroup: getGroup,
      onChange: onChange,
      onSearch: _onSearch
    }),
    selectedOptions = _useGroupSelect.selectedOptions,
    selectedOptionIds = _useGroupSelect.selectedOptionIds,
    selectedGroupIds = _useGroupSelect.selectedGroupIds,
    computedOptions = _useGroupSelect.computedOptions,
    isGroup = _useGroupSelect.isGroup,
    onSelect = _useGroupSelect.onSelect,
    onSearch = _useGroupSelect.onSearch;
  var multiselectOptionRenderer = React.useCallback(function (option) {
    var optionId = getId(option);
    var renderer = (isGroup(optionId) ? groupRenderer : optionRenderer) || defaultOptionRenderer;
    var isSelected = selectedOptionIds.has(optionId);
    var isDisabled = selectedGroupIds.has(optionId);
    return renderer(option, {
      getId: getId,
      getLabel: getLabel,
      value: option,
      selected: isSelected,
      disabled: isDisabled
    });
  }, [getId, getLabel, groupRenderer, isGroup, optionRenderer, selectedGroupIds, selectedOptionIds]);
  return /*#__PURE__*/React.createElement(MultiSelect, _extends({
    ref: ref
  }, props, {
    value: selectedOptions,
    options: computedOptions,
    getId: getId,
    getLabel: getLabel,
    onChange: onSelect,
    onSearch: onSearch,
    getGroup: getOptGroup,
    optionRenderer: multiselectOptionRenderer,
    groupHeaderRenderer: optGroupRenderer
  }));
});
GroupSelect.displayName = 'GroupSelect';
//# sourceMappingURL=GroupSelect.js.map