"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;
var _react = _interopRequireWildcard(require("react"));
var _propTypes = _interopRequireDefault(require("prop-types"));
var _formiga = require("formiga");
var _FInputAddon = require("../../../addon/FInputAddon.cjs");
var _inputPropTypes = require("../../../props/inputPropTypes.cjs");
var _inputDefaultProps = require("../../../props/inputDefaultProps.cjs");
var _useEnabledOptions = require("../useEnabledOptions.cjs");
var _parseValueDependOnOptions = require("../parseValueDependOnOptions.cjs");
var _FISSHidden = _interopRequireDefault(require("./FISSHidden.cjs"));
var _FISSInput = _interopRequireDefault(require("./FISSInput.cjs"));
var _FISSAction = _interopRequireDefault(require("./FISSAction.cjs"));
var _FISSList = _interopRequireDefault(require("./FISSList.cjs"));
var _withWrapControlled = _interopRequireDefault(require("../../../helpers/props/withWrapControlled.cjs"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
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 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); }
var getOptionsLabel = (options, value) => {
  var elOpt = options.find(opt => opt.value == value);
  return (elOpt === null || elOpt === void 0 ? void 0 : elOpt.label) || '';
};
var _FInputSelectSearch = props => {
  var {
    options,
    feedback,
    allowedValues,
    disallowedValues,
    keepHeight,
    creatable,
    onCreate,
    value,
    setValue
  } = props;
  var wrapperRef = (0, _react.useRef)(undefined);
  var filterRef = (0, _react.useRef)(undefined);
  var listRef = (0, _react.useRef)(undefined);
  var [isOpen, setIsOpen] = (0, _react.useState)(false);
  var [optionsMap, setOptionsMap] = (0, _react.useState)([]);
  var [optActive, setOptActive] = (0, _react.useState)(undefined);
  var [shownText, setShownText] = (0, _react.useState)('');
  var [creating, setCreating] = (0, _react.useState)(false);
  var enabledOptions = (0, _useEnabledOptions.useEnabledOptions)(options, allowedValues, disallowedValues);
  var input = (0, _formiga.useInput)(_objectSpread(_objectSpread({}, props), {}, {
    checkValue: props.checkValue != undefined ? v => props.checkValue((0, _parseValueDependOnOptions.parseValueDependOnOptions)(v, enabledOptions)) : undefined
  }));
  (0, _react.useEffect)(() => {
    var onClickOutside = event => {
      if (wrapperRef && wrapperRef.current && !wrapperRef.current.contains(event.target)) {
        if (listRef && listRef.current && !listRef.current.contains(event.target)) {
          handleSearchAbort(event);
        }
      }
    };
    document.addEventListener('mousedown', onClickOutside);
    return () => {
      document.removeEventListener('mousedown', onClickOutside);
    };
  });
  (0, _react.useEffect)(() => {
    var nShownText = getOptionsLabel(enabledOptions, value);
    setShownText(nShownText);
  }, [enabledOptions, value]);
  (0, _react.useEffect)(() => {
    var sfilter = shownText ? shownText.toLowerCase() : '';
    var nOptionsMap = enabledOptions.filter(opt => sfilter.length > 0 ? opt.label.toLowerCase().includes(sfilter) : true);
    setOptionsMap(nOptionsMap);
    if (shownText.length > 0 && creatable) {
      if (nOptionsMap.length == 0) {
        setCreating(true);
      }
    }
  }, [shownText, enabledOptions, creatable]);
  var handleChange = (0, _react.useCallback)((tValue, event) => {
    var nValue = (0, _parseValueDependOnOptions.parseValueDependOnOptions)(tValue, enabledOptions);
    setValue(nValue, true, event);
    input.setValue(nValue);
    var nShownText = getOptionsLabel(enabledOptions, tValue);
    setShownText(nShownText);
    input.validate();
  }, [input, setValue, enabledOptions]);
  var handleSearchStart = (0, _react.useCallback)(_event => {
    if (!isOpen) {
      setIsOpen(true);
    }
    setOptActive(undefined);
  }, [isOpen]);
  var handleSearchType = (0, _react.useCallback)(event => {
    setShownText(event.target.value);
    handleSearchStart(event);
  }, [handleSearchStart]);
  var handleSearchAbort = (0, _react.useCallback)(event => {
    setIsOpen(false);
    setOptActive(undefined);
    if (shownText == '') {
      handleChange('', event);
    }
  }, [shownText, handleChange]);
  var handleSelect = (0, _react.useCallback)((newValue, event) => {
    setIsOpen(false);
    setOptActive(undefined);
    handleChange(newValue, event);
  }, [handleChange]);
  var handleClear = (0, _react.useCallback)(event => {
    setIsOpen(true);
    setOptActive(undefined);
    handleChange('', event);
  }, [handleChange]);
  var handleKeyDown = (0, _react.useCallback)(event => {
    if (event.key == 'ArrowUp' || event.key == 'ArrowDown') {
      event.preventDefault();
      if (isOpen) {
        if (optionsMap.length > 0) {
          var factor = event.key == 'ArrowUp' ? -1 : 1;
          var nOptActive = optActive == undefined ? 0 : optActive + factor;
          setOptActive(nOptActive);
        }
      }
    }
    if (event.key == 'Enter') {
      event.preventDefault();
      if (isOpen) {
        if (optionsMap.length > 0) {
          if (optActive != undefined) {
            var opt = optionsMap[optActive];
            if ((opt === null || opt === void 0 ? void 0 : opt.disabled) !== true) {
              var nValue = opt.value;
              handleSelect(nValue, event);
            }
          }
        }
      }
    }
    return true;
  }, [isOpen, optActive, optionsMap, handleSelect]);
  var handleCreate = (0, _react.useCallback)(event => {
    if (onCreate != undefined) {
      onCreate(shownText, event);
    }
    setCreating(false);
  }, [shownText, onCreate]);
  return /*#__PURE__*/_react.default.createElement("div", {
    className: "formiga-reactstrap-select-search",
    ref: wrapperRef
  }, /*#__PURE__*/_react.default.createElement("div", null, /*#__PURE__*/_react.default.createElement(_FInputAddon.FInputAddon, _extends({}, props, {
    valid: input.valid,
    invalid: !input.valid,
    feedback: isOpen ? undefined : feedback || input.feedback,
    keepHeight: isOpen ? false : keepHeight
  }), /*#__PURE__*/_react.default.createElement(_FISSHidden.default, _extends({}, props, {
    inputRef: input.ref
  })), /*#__PURE__*/_react.default.createElement(_FISSInput.default, _extends({}, props, {
    valid: input.valid,
    filterRef: filterRef,
    shownText: shownText,
    onSearchStart: handleSearchStart,
    onSearchType: handleSearchType,
    onKeyDown: handleKeyDown
  })), /*#__PURE__*/_react.default.createElement(_FISSAction.default, _extends({}, props, {
    creating: creating,
    onCreate: handleCreate,
    onClear: handleClear
  })))), isOpen ? /*#__PURE__*/_react.default.createElement(_FISSList.default, _extends({}, props, {
    listRef: listRef,
    optionsMap: optionsMap,
    onSelect: handleSelect,
    optActive: optActive
  })) : null);
};
var FInputSelectSearch = (0, _withWrapControlled.default)(_FInputSelectSearch);
FInputSelectSearch.propTypes = _objectSpread(_objectSpread({}, _inputPropTypes.inputPropTypes), {}, {
  placeholder: _propTypes.default.string,
  options: _propTypes.default.oneOfType([_propTypes.default.object, _propTypes.default.arrayOf(_propTypes.default.array)]),
  autocomplete: _propTypes.default.oneOf(["on", "off"]),
  clearable: _propTypes.default.bool,
  creatable: _propTypes.default.bool,
  onCreate: _propTypes.default.func,
  maxShownOptions: _propTypes.default.number
});
FInputSelectSearch.defaultProps = _objectSpread(_objectSpread({}, _inputDefaultProps.inputDefaultProps), {}, {
  icon: 'search',
  maxShownOptions: 10
});
var _default = FInputSelectSearch;
exports.default = _default;