"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.Select = void 0;
var _react = _interopRequireWildcard(require("react"));
var _classnames = _interopRequireDefault(require("classnames"));
var _OptionContent = require("./OptionContent/OptionContent");
var _Styles = require("./Styles");
var _useForkRef = _interopRequireDefault(require("../../utils/useForkRef"));
var _Autocomplete = require("../Autocomplete");
var _Menu = require("../Menu/Menu");
var _excluded = ["type", "mode", "target", "options", "selected", "mixed", "position", "onChange", "placeholder", "emptyAction", "disableSearch", "forceCloseMenu", "selectClassName", "keepSameOptionsOrder", "onSelectOpen", "onSelectClose", "renderOption", "handleDefaultOptionChange", "preselectDefaultValue", "startAdornment", "endAdornment", "focusInput"];
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(e) { return e ? t : r; })(e); }
function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && Object.prototype.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; }
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(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(arr) { if (Array.isArray(arr)) return arr; }
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; }
var Select = exports.Select = function Select(_ref) {
  var _ref$type = _ref.type,
    type = _ref$type === void 0 ? "single" : _ref$type,
    mode = _ref.mode,
    target = _ref.target,
    options = _ref.options,
    _ref$selected = _ref.selected,
    selected = _ref$selected === void 0 ? [] : _ref$selected,
    _ref$mixed = _ref.mixed,
    mixed = _ref$mixed === void 0 ? [] : _ref$mixed,
    _ref$position = _ref.position,
    position = _ref$position === void 0 ? "bottom-start" : _ref$position,
    _ref$onChange = _ref.onChange,
    onChange = _ref$onChange === void 0 ? function () {
      return null;
    } : _ref$onChange,
    placeholder = _ref.placeholder,
    _ref$emptyAction = _ref.emptyAction,
    emptyAction = _ref$emptyAction === void 0 ? function () {
      return null;
    } : _ref$emptyAction,
    _ref$disableSearch = _ref.disableSearch,
    disableSearch = _ref$disableSearch === void 0 ? false : _ref$disableSearch,
    forceCloseMenu = _ref.forceCloseMenu,
    selectClassName = _ref.selectClassName,
    _ref$keepSameOptionsO = _ref.keepSameOptionsOrder,
    keepSameOptionsOrder = _ref$keepSameOptionsO === void 0 ? false : _ref$keepSameOptionsO,
    onSelectOpen = _ref.onSelectOpen,
    onSelectClose = _ref.onSelectClose,
    renderOption = _ref.renderOption,
    handleDefaultOptionChange = _ref.handleDefaultOptionChange,
    _ref$preselectDefault = _ref.preselectDefaultValue,
    preselectDefaultValue = _ref$preselectDefault === void 0 ? type === "single" : _ref$preselectDefault,
    startAdornment = _ref.startAdornment,
    endAdornment = _ref.endAdornment,
    _ref$focusInput = _ref.focusInput,
    focusInput = _ref$focusInput === void 0 ? false : _ref$focusInput,
    prop = _objectWithoutProperties(_ref, _excluded);
  if (disableSearch && (startAdornment || endAdornment)) {
    console.warn("Adornments are not visible when search bar is hidden");
  }
  var childNode = (0, _react.useRef)();
  var elementRef = (0, _react.useRef)(null);
  var handleRef = (0, _useForkRef.default)(childNode, elementRef);
  var Tag = !target ? "div" : _Menu.Menu;
  var formRef = (0, _react.useRef)(null);
  var _useState = (0, _react.useState)(false),
    _useState2 = _slicedToArray(_useState, 2),
    open = _useState2[0],
    setOpen = _useState2[1];
  var selectedOptions = (0, _react.useMemo)(function () {
    return selected instanceof Array ? selected : [selected];
  }, [selected]);
  var selectOptions = (0, _react.useMemo)(function () {
    if (!options) {
      return [];
    }
    return options;
  }, [options]);
  var allOptionValues = (0, _react.useMemo)(function () {
    return selectOptions.reduce(function (acc, option) {
      if (!(0, _Autocomplete.isOptionGroup)(option)) {
        return [...acc, option.id];
      }
      var allGroupOptions = option.options.map(function (option) {
        return option.id;
      });
      return [...acc, ...allGroupOptions];
    }, []);
  }, [selectOptions]);
  var mixedOptions = (0, _react.useRef)(type === "multiple" && mixed.length ? mixed : []);
  var removeFromMixedOptions = (0, _react.useCallback)(function (idsToRemove) {
    mixedOptions.current = mixedOptions.current.filter(function (mixedOption) {
      return !idsToRemove.includes(mixedOption);
    });
  }, []);
  var isAllOptionsChecked = (0, _react.useMemo)(function () {
    return allOptionValues.every(function (option) {
      return selectedOptions.includes(option);
    });
  }, [allOptionValues, selectedOptions]);
  var someOptionsChecked = (0, _react.useMemo)(function () {
    return allOptionValues.some(function (option) {
      return selectedOptions.includes(option);
    });
  }, [allOptionValues, selectedOptions]);
  (0, _react.useEffect)(function () {
    if (open && target || !target && focusInput) {
      var _childNode$current;
      childNode === null || childNode === void 0 || (_childNode$current = childNode.current) === null || _childNode$current === void 0 || _childNode$current.focus();
    }
  }, [focusInput, open, target]);
  var handleChange = (0, _react.useCallback)(function (selectedValue) {
    if (forceCloseMenu) {
      if (typeof onSelectClose === "function") onSelectClose();
      setOpen(false);
    }
    if (selectedValue !== undefined && selectedValue !== selected && !(selectedValue instanceof Array && selectedValue.includes(undefined))) {
      onChange(selectedValue);
      type === "multiple" && mixedOptions.current.length && removeFromMixedOptions(selectedValue);
    }
  }, [forceCloseMenu, selected, onSelectClose, onChange, type, removeFromMixedOptions]);
  var onClose = (0, _react.useCallback)(function () {
    setOpen(false);
    if (onSelectClose) {
      onSelectClose();
    }
  }, [onSelectClose]);
  var onOpen = (0, _react.useCallback)(function () {
    setOpen(true);
    if (onSelectOpen) {
      onSelectOpen();
    }
  }, [onSelectOpen]);
  var props = (0, _react.useMemo)(function () {
    if (target) {
      return {
        menuClassName: (0, _classnames.default)("c-select", selectClassName),
        onClose,
        onOpen,
        target,
        mode,
        open,
        position,
        onPopperOpen: function onPopperOpen() {
          var _elementRef$current;
          return elementRef === null || elementRef === void 0 || (_elementRef$current = elementRef.current) === null || _elementRef$current === void 0 ? void 0 : _elementRef$current.focus();
        }
      };
    }
    return {
      className: (0, _classnames.default)("c-select", selectClassName)
    };
  }, [target, selectClassName, onClose, onOpen, mode, open, position]);
  var handleEmptyAction = (0, _react.useCallback)(function (value) {
    var _formRef$current;
    emptyAction(value);
    if (forceCloseMenu) {
      setOpen(false);
    }
    (_formRef$current = formRef.current) === null || _formRef$current === void 0 || _formRef$current.reset();
  }, [emptyAction, forceCloseMenu]);
  var handleDefaultOptionChangeCallback = (0, _react.useCallback)(function () {
    if (type === "multiple") {
      if (selectedOptions.length === allOptionValues.length) {
        if (typeof handleDefaultOptionChange === "function") {
          handleDefaultOptionChange();
        } else {
          onChange([]);
        }
      } else {
        if (typeof handleDefaultOptionChange === "function") {
          handleDefaultOptionChange();
        } else {
          onChange(allOptionValues);
        }
      }
    } else {
      if (typeof handleDefaultOptionChange === "function") {
        handleDefaultOptionChange();
      } else {
        onChange("");
      }
    }
    if (forceCloseMenu) {
      setOpen(false);
    }
  }, [onChange, type, forceCloseMenu, selectedOptions.length, allOptionValues, handleDefaultOptionChange]);
  var handleRenderOption = (0, _react.useCallback)(function (option, props) {
    if (typeof renderOption === "function") {
      return renderOption(option, props);
    }
    return /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_OptionContent.OptionContent, {
      imageUrl: option.image,
      color: option.color,
      textColor: option.textColor,
      name: option.name,
      additionalInfo: option.additionalInfo
    }), option.id === null ? type === "multiple" ? /*#__PURE__*/_react.default.createElement(_Styles.StyledCheckbox, _extends({
      checked: isAllOptionsChecked,
      mixed: someOptionsChecked && !isAllOptionsChecked
    }, props)) : /*#__PURE__*/_react.default.createElement(_Styles.StyledRadioButton, _extends({
      checked: selectedOptions.length < 1 || !selectedOptions[0]
    }, props)) : type === "multiple" ? /*#__PURE__*/_react.default.createElement(_Styles.StyledCheckbox, _extends({
      mixed: mixedOptions.current.includes(option.id)
    }, props)) : /*#__PURE__*/_react.default.createElement(_Styles.StyledRadioButton, props));
  }, [isAllOptionsChecked, renderOption, type, someOptionsChecked, selectedOptions]);
  return /*#__PURE__*/_react.default.createElement(Tag, props, /*#__PURE__*/_react.default.createElement("div", null, !disableSearch ? /*#__PURE__*/_react.default.createElement(_Styles.StyledSelectForm, {
    ref: formRef
  }, startAdornment ? /*#__PURE__*/_react.default.createElement(_Styles.StyledStartAdornment, null, startAdornment) : null, /*#__PURE__*/_react.default.createElement(_Styles.StyledSelectInput, {
    ref: handleRef,
    placeholder: placeholder
  }), endAdornment ? /*#__PURE__*/_react.default.createElement(_Styles.StyledEndAdornment, null, endAdornment) : null) : null, /*#__PURE__*/_react.default.createElement(_Autocomplete.Autocomplete, _extends({}, prop, {
    clearInputOnSelect: true,
    inputEl: childNode,
    handleEmptyAction: handleEmptyAction,
    selected: selected,
    handleChange: handleChange,
    renderOption: handleRenderOption,
    options: options,
    mixedOptions: mixedOptions.current,
    handleDefaultOptionChange: handleDefaultOptionChangeCallback,
    type: type,
    preselectDefaultValue: preselectDefaultValue,
    keepSameOptionsOrder: keepSameOptionsOrder
  }))));
};
Select.displayName = "Select";
//# sourceMappingURL=Select.js.map