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 = ["getId", "getLabel", "disabled", "value"],
  _excluded2 = ["value", "options", "groups", "getId", "getLabel", "getGroup", "getOptGroup", "onChange", "onSearch", "optionRenderer", "groupRenderer", "optGroupRenderer"];
function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _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(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(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 _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 _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 _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 { MenuImperative } from '../MenuImperative/MenuImperative';
import { MultiSelect } from '../MultiSelect/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