Liferay.Loader.define("dynamic-data-mapping-form-field-type@5.0.45/Select/Select.es", ['module', 'exports', 'require', '@frontend-taglib-clay$clayui/drop-down', '@frontend-taglib-clay$clayui/form', 'frontend-js-react-web$react', '../FieldBase/ReactFieldBase.es', '../hooks/useSyncValue.es', './HiddenSelectInput.es', './VisibleSelectInput.es'], function (module, exports, require) {
  var define = undefined;
  var global = window;
  {
    function _typeof(obj) {
      "@babel/helpers - typeof";
      if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
        _typeof = function _typeof(obj) {
          return typeof obj;
        };
      } else {
        _typeof = function _typeof(obj) {
          return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
        };
      }return _typeof(obj);
    }

    Object.defineProperty(exports, "__esModule", {
      value: true
    });
    exports["default"] = void 0;

    var _dropDown = _interopRequireDefault(require("@frontend-taglib-clay$clayui/drop-down"));

    var _form = require("@frontend-taglib-clay$clayui/form");

    var _react = _interopRequireWildcard(require("frontend-js-react-web$react"));

    var _ReactFieldBase = require("../FieldBase/ReactFieldBase.es");

    var _useSyncValue3 = require("../hooks/useSyncValue.es");

    var _HiddenSelectInput = _interopRequireDefault(require("./HiddenSelectInput.es"));

    var _VisibleSelectInput = _interopRequireDefault(require("./VisibleSelectInput.es"));

    function _getRequireWildcardCache() {
      if (typeof WeakMap !== "function") return null;var cache = new WeakMap();_getRequireWildcardCache = function _getRequireWildcardCache() {
        return cache;
      };return cache;
    }

    function _interopRequireWildcard(obj) {
      if (obj && obj.__esModule) {
        return obj;
      }if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") {
        return { "default": obj };
      }var cache = _getRequireWildcardCache();if (cache && cache.has(obj)) {
        return cache.get(obj);
      }var newObj = {};var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;for (var key in obj) {
        if (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 _interopRequireDefault(obj) {
      return obj && obj.__esModule ? obj : { "default": obj };
    }

    function _extends() {
      _extends = Object.assign || 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;
    }

    function _slicedToArray(arr, i) {
      return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest();
    }

    function _nonIterableRest() {
      throw new TypeError("Invalid attempt to destructure non-iterable instance");
    }

    function _iterableToArrayLimit(arr, i) {
      if (!(Symbol.iterator in Object(arr) || Object.prototype.toString.call(arr) === "[object Arguments]")) {
        return;
      }var _arr = [];var _n = true;var _d = false;var _e = undefined;try {
        for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
          _arr.push(_s.value);if (i && _arr.length === i) break;
        }
      } catch (err) {
        _d = true;_e = err;
      } finally {
        try {
          if (!_n && _i["return"] != null) _i["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);if (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 = arguments[i] != null ? arguments[i] : {};if (i % 2) {
          ownKeys(Object(source), true).forEach(function (key) {
            _defineProperty(target, key, source[key]);
          });
        } else if (Object.getOwnPropertyDescriptors) {
          Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
        } else {
          ownKeys(Object(source)).forEach(function (key) {
            Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
          });
        }
      }return target;
    }

    function _defineProperty(obj, key, value) {
      if (key in obj) {
        Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true });
      } else {
        obj[key] = value;
      }return obj;
    }

    function _toConsumableArray(arr) {
      return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread();
    }

    function _nonIterableSpread() {
      throw new TypeError("Invalid attempt to spread non-iterable instance");
    }

    function _iterableToArray(iter) {
      if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter);
    }

    function _arrayWithoutHoles(arr) {
      if (Array.isArray(arr)) {
        for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) {
          arr2[i] = arr[i];
        }return arr2;
      }
    }

    /**
     * Mapping to be used to match keyCodes
     * returned from keydown events.
     */
    var KEYCODES = {
      ARROW_DOWN: 40,
      ARROW_UP: 38,
      ENTER: 13,
      SHIFT: 16,
      SPACE: 32,
      TAB: 9
    };
    /**
     * Maximum number of items to be shown without the Search bar
     */

    var MAX_ITEMS = 11;
    /**
     * Appends a new value on the current value state
     * @param options {Object}
     * @param options.value {Array|String}
     * @param options.valueToBeAppended {Array|String}
     * @returns {Array}
     */

    function appendValue(_ref) {
      var value = _ref.value,
          valueToBeAppended = _ref.valueToBeAppended;
      var currentValue = toArray(value);

      var newValue = _toConsumableArray(currentValue);

      if (value) {
        newValue.push(valueToBeAppended);
      }

      return newValue;
    }
    /**
     * Removes a value from the value array.
     * @param options {Object}
     * @param options.value {Array|String}
     * @param options.valueToBeRemoved {Array|String}
     * @returns {Array}
     */

    function removeValue(_ref2) {
      var value = _ref2.value,
          valueToBeRemoved = _ref2.valueToBeRemoved;
      var currentValue = toArray(value);
      return currentValue.filter(function (v) {
        return v !== valueToBeRemoved;
      });
    }
    /**
     * Wraps the given argument into an array.
     * @param value {Array|String}
     */

    function toArray() {
      var value = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
      var newValue = value;

      if (!Array.isArray(newValue)) {
        newValue = [newValue];
      }

      return newValue;
    }

    function normalizeValue(_ref3) {
      var multiple = _ref3.multiple,
          normalizedOptions = _ref3.normalizedOptions,
          predefinedValueArray = _ref3.predefinedValueArray,
          valueArray = _ref3.valueArray;
      var assertValue = valueArray.length ? valueArray : predefinedValueArray;
      var valueWithoutMultiple = assertValue.filter(function (_, index) {
        return multiple ? true : index === 0;
      });
      return valueWithoutMultiple.filter(function (value) {
        return normalizedOptions.some(function (option) {
          return value === option.value;
        });
      });
    }
    /**
     * Some parameters on each option
     * needs to be prepared in case of
     * multiple selected values(when the value state is an array).
     */

    function assertOptionParameters(_ref4) {
      var multiple = _ref4.multiple,
          option = _ref4.option,
          valueArray = _ref4.valueArray;
      var included = valueArray.includes(option.value);
      return _objectSpread({}, option, {
        active: !multiple && included,
        checked: multiple && included,
        type: multiple ? 'checkbox' : 'item'
      });
    }

    function normalizeOptions(_ref5) {
      var fixedOptions = _ref5.fixedOptions,
          multiple = _ref5.multiple,
          options = _ref5.options,
          valueArray = _ref5.valueArray;
      var emptyOption = {
        label: Liferay.Language.get('choose-an-option'),
        value: null
      };
      var newOptions = [].concat(_toConsumableArray(options.map(function (option, index) {
        return _objectSpread({}, assertOptionParameters({
          multiple: multiple,
          option: option,
          valueArray: valueArray
        }), {
          separator: Array.isArray(fixedOptions) && fixedOptions.length > 0 && index === options.length - 1
        });
      })), _toConsumableArray(fixedOptions.map(function (option) {
        return assertOptionParameters({
          multiple: multiple,
          option: option,
          valueArray: valueArray
        });
      }))).filter(function (_ref6) {
        var value = _ref6.value;
        return value !== '';
      });

      if (!multiple) {
        return [emptyOption].concat(_toConsumableArray(newOptions));
      }

      return newOptions;
    }

    function handleDropdownItemClick(_ref7) {
      var currentValue = _ref7.currentValue,
          multiple = _ref7.multiple,
          option = _ref7.option;
      var itemValue = option.value;
      var newValue;

      if (multiple) {
        if (currentValue.includes(itemValue)) {
          newValue = removeValue({
            value: currentValue,
            valueToBeRemoved: itemValue
          });
        } else {
          newValue = appendValue({
            value: currentValue,
            valueToBeAppended: itemValue
          });
        }
      } else if (itemValue === null) {
        newValue = [];
      } else {
        newValue = [itemValue];
      }

      return newValue;
    }

    var DropdownItem = function DropdownItem(_ref8) {
      var currentValue = _ref8.currentValue,
          expand = _ref8.expand,
          index = _ref8.index,
          multiple = _ref8.multiple,
          onSelect = _ref8.onSelect,
          option = _ref8.option,
          options = _ref8.options;
      return _react["default"].createElement(_react["default"].Fragment, null, _react["default"].createElement(_dropDown["default"].Item, {
        active: expand && currentValue === option.label,
        "data-testid": "dropdownItem-".concat(index),
        label: option.label,
        onClick: function onClick(event) {
          event.preventDefault();
          event.stopPropagation();
          onSelect({
            currentValue: currentValue,
            event: event,
            multiple: multiple,
            option: option
          });
        },
        value: options.value
      }, multiple ? _react["default"].createElement(_form.ClayCheckbox, {
        "aria-label": option.label,
        checked: currentValue.includes(option.value),
        "data-testid": "labelItem-".concat(option.value),
        label: option.label,
        onChange: function onChange(event) {
          onSelect({
            currentValue: currentValue,
            event: event,
            multiple: multiple,
            option: option
          });
        }
      }) : option.label), option && option.separator && _react["default"].createElement(_dropDown["default"].Divider, null));
    };

    var DropdownList = function DropdownList(_ref9) {
      var currentValue = _ref9.currentValue,
          expand = _ref9.expand,
          handleSelect = _ref9.handleSelect,
          multiple = _ref9.multiple,
          options = _ref9.options;
      return _react["default"].createElement(_dropDown["default"].ItemList, null, options.map(function (option, index) {
        return _react["default"].createElement(DropdownItem, {
          currentValue: currentValue,
          expand: expand,
          index: index,
          key: "".concat(option.value, "-").concat(index),
          multiple: multiple,
          onSelect: handleSelect,
          option: option,
          options: options
        });
      }));
    };

    var DropdownListWithSearch = function DropdownListWithSearch(_ref10) {
      var currentValue = _ref10.currentValue,
          expand = _ref10.expand,
          handleSelect = _ref10.handleSelect,
          multiple = _ref10.multiple,
          options = _ref10.options;

      var _useState = (0, _react.useState)(''),
          _useState2 = _slicedToArray(_useState, 2),
          query = _useState2[0],
          setQuery = _useState2[1];

      var _useState3 = (0, _react.useState)([]),
          _useState4 = _slicedToArray(_useState3, 2),
          filteredOptions = _useState4[0],
          setFilteredOptions = _useState4[1];

      var emptyOption = {
        label: Liferay.Language.get('choose-an-option'),
        value: null
      };
      (0, _react.useEffect)(function () {
        var result = options.filter(function (option) {
          return option.value && option.label.toLowerCase().includes(query.toLowerCase());
        });
        setFilteredOptions([emptyOption].concat(_toConsumableArray(result))); // eslint-disable-next-line react-hooks/exhaustive-deps
      }, [options, query]);
      return _react["default"].createElement(_react["default"].Fragment, null, _react["default"].createElement(_dropDown["default"].Search, {
        onChange: function onChange(event) {
          return setQuery(event.target.value);
        },
        value: query
      }), filteredOptions.length > 1 ? _react["default"].createElement(DropdownList, {
        currentValue: currentValue,
        expand: expand,
        handleSelect: handleSelect,
        multiple: multiple,
        options: filteredOptions
      }) : _react["default"].createElement("div", {
        className: "dropdown-section text-muted"
      }, Liferay.Language.get('empty-list')));
    };

    var Trigger = (0, _react.forwardRef)(function (_ref11, ref) {
      var onCloseButtonClicked = _ref11.onCloseButtonClicked,
          onTriggerClicked = _ref11.onTriggerClicked,
          onTriggerKeyDown = _ref11.onTriggerKeyDown,
          readOnly = _ref11.readOnly,
          value = _ref11.value,
          otherProps = _objectWithoutProperties(_ref11, ["onCloseButtonClicked", "onTriggerClicked", "onTriggerKeyDown", "readOnly", "value"]);

      return _react["default"].createElement(_react["default"].Fragment, null, !readOnly && _react["default"].createElement(_HiddenSelectInput["default"], _extends({
        value: value
      }, otherProps)), _react["default"].createElement(_VisibleSelectInput["default"], _extends({
        onClick: onTriggerClicked,
        onCloseButtonClicked: onCloseButtonClicked,
        onKeyDown: onTriggerKeyDown,
        readOnly: readOnly,
        ref: ref,
        value: value
      }, otherProps)));
    });

    var Select = function Select(_ref12) {
      var multiple = _ref12.multiple,
          _onCloseButtonClicked = _ref12.onCloseButtonClicked,
          onDropdownItemClicked = _ref12.onDropdownItemClicked,
          onExpand = _ref12.onExpand,
          options = _ref12.options,
          predefinedValue = _ref12.predefinedValue,
          readOnly = _ref12.readOnly,
          value = _ref12.value,
          otherProps = _objectWithoutProperties(_ref12, ["multiple", "onCloseButtonClicked", "onDropdownItemClicked", "onExpand", "options", "predefinedValue", "readOnly", "value"]);

      var menuElementRef = (0, _react.useRef)(null);
      var triggerElementRef = (0, _react.useRef)(null);

      var _useSyncValue = (0, _useSyncValue3.useSyncValue)(value, false),
          _useSyncValue2 = _slicedToArray(_useSyncValue, 2),
          currentValue = _useSyncValue2[0],
          setCurrentValue = _useSyncValue2[1];

      var _useState5 = (0, _react.useState)(false),
          _useState6 = _slicedToArray(_useState5, 2),
          expand = _useState6[0],
          setExpand = _useState6[1];

      var handleFocus = function handleFocus(event, direction) {
        var target = event.target;
        var focusabledElements = event.currentTarget.querySelectorAll('button');

        var targetIndex = _toConsumableArray(focusabledElements).findIndex(function (current) {
          return current === target;
        });

        var nextElement;

        if (direction) {
          nextElement = focusabledElements[targetIndex - 1];
        } else {
          nextElement = focusabledElements[targetIndex + 1];
        }

        if (nextElement) {
          event.preventDefault();
          event.stopPropagation();
          nextElement.focus();
        } else if (targetIndex === 0 && direction) {
          event.preventDefault();
          event.stopPropagation();
          menuElementRef.current.focus();
        }
      };

      var handleSelect = function handleSelect(_ref13) {
        var currentValue = _ref13.currentValue,
            event = _ref13.event,
            multiple = _ref13.multiple,
            option = _ref13.option;
        var newValue = handleDropdownItemClick({
          currentValue: currentValue,
          multiple: multiple,
          option: option
        });
        setCurrentValue(newValue);
        onDropdownItemClicked({
          event: event,
          value: newValue
        });

        if (!multiple) {
          setExpand(false);
          onExpand({
            event: event,
            expand: false
          });
          triggerElementRef.current.firstChild.focus();
        }
      };

      return _react["default"].createElement(_react["default"].Fragment, null, _react["default"].createElement(Trigger, _extends({
        multiple: multiple,
        onCloseButtonClicked: function onCloseButtonClicked(_ref14) {
          var event = _ref14.event,
              value = _ref14.value;
          var newValue = removeValue({
            value: currentValue,
            valueToBeRemoved: value
          });
          setCurrentValue(newValue);

          _onCloseButtonClicked({
            event: event,
            value: newValue
          });
        },
        onTriggerClicked: function onTriggerClicked(event) {
          if (readOnly) {
            return;
          }

          setExpand(!expand);
          onExpand({
            event: event,
            expand: !expand
          });

          if (expand) {
            triggerElementRef.current.firstChild.focus();
          }
        },
        onTriggerKeyDown: function onTriggerKeyDown(event) {
          if ((event.keyCode === KEYCODES.TAB || event.keyCode === KEYCODES.ARROW_DOWN) && !event.shiftKey && expand) {
            event.preventDefault();
            event.stopPropagation();
            var firstElement = menuElementRef.current.querySelector('button');
            firstElement.focus();
          }

          if (event.keyCode === KEYCODES.ENTER || event.keyCode === KEYCODES.SPACE && !event.shiftKey) {
            event.preventDefault();
            event.stopPropagation();
            setExpand(!expand);
            onExpand({
              event: event,
              expand: !expand
            });

            if (expand) {
              triggerElementRef.current.firstChild.focus();
            }
          }
        },
        options: options,
        predefinedValue: predefinedValue,
        readOnly: readOnly,
        ref: triggerElementRef,
        value: currentValue
      }, otherProps)), _react["default"].createElement(_dropDown["default"].Menu, {
        active: expand,
        alignElementRef: triggerElementRef,
        className: "ddm-btn-full ddm-select-dropdown",
        onKeyDown: function onKeyDown(event) {
          switch (event.keyCode) {
            case KEYCODES.ARROW_DOWN:
              handleFocus(event, false);
              break;

            case KEYCODES.ARROW_UP:
              handleFocus(event, true);
              break;

            case KEYCODES.TAB:
              handleFocus(event, event.shiftKey);
              break;

            default:
              break;
          }
        },
        onSetActive: setExpand,
        ref: menuElementRef
      }, options.length > MAX_ITEMS ? _react["default"].createElement(DropdownListWithSearch, {
        currentValue: currentValue,
        expand: expand,
        handleSelect: handleSelect,
        multiple: multiple,
        options: options
      }) : _react["default"].createElement(DropdownList, {
        currentValue: currentValue,
        expand: expand,
        handleSelect: handleSelect,
        multiple: multiple,
        options: options
      })));
    };

    var Main = function Main(_ref15) {
      var _ref15$fixedOptions = _ref15.fixedOptions,
          fixedOptions = _ref15$fixedOptions === void 0 ? [] : _ref15$fixedOptions,
          label = _ref15.label,
          _ref15$localizedValue = _ref15.localizedValue,
          localizedValue = _ref15$localizedValue === void 0 ? {} : _ref15$localizedValue,
          multiple = _ref15.multiple,
          name = _ref15.name,
          _ref15$onBlur = _ref15.onBlur,
          onBlur = _ref15$onBlur === void 0 ? function () {} : _ref15$onBlur,
          onChange = _ref15.onChange,
          _ref15$onFocus = _ref15.onFocus,
          onFocus = _ref15$onFocus === void 0 ? function () {} : _ref15$onFocus,
          _ref15$options = _ref15.options,
          options = _ref15$options === void 0 ? [] : _ref15$options,
          _ref15$predefinedValu = _ref15.predefinedValue,
          predefinedValue = _ref15$predefinedValu === void 0 ? [] : _ref15$predefinedValu,
          _ref15$readOnly = _ref15.readOnly,
          readOnly = _ref15$readOnly === void 0 ? false : _ref15$readOnly,
          _ref15$value = _ref15.value,
          value = _ref15$value === void 0 ? [] : _ref15$value,
          otherProps = _objectWithoutProperties(_ref15, ["fixedOptions", "label", "localizedValue", "multiple", "name", "onBlur", "onChange", "onFocus", "options", "predefinedValue", "readOnly", "value"]);

      var predefinedValueArray = toArray(predefinedValue);
      var valueArray = toArray(value);
      var normalizedOptions = (0, _react.useMemo)(function () {
        return normalizeOptions({
          fixedOptions: fixedOptions,
          multiple: multiple,
          options: options,
          valueArray: valueArray
        });
      }, [fixedOptions, multiple, options, valueArray]);
      value = (0, _react.useMemo)(function () {
        return normalizeValue({
          multiple: multiple,
          normalizedOptions: normalizedOptions,
          predefinedValueArray: predefinedValueArray,
          valueArray: valueArray
        });
      }, [multiple, normalizedOptions, predefinedValueArray, valueArray]);
      return _react["default"].createElement(_ReactFieldBase.FieldBase, _extends({
        label: label,
        localizedValue: localizedValue,
        name: name,
        readOnly: readOnly
      }, otherProps), _react["default"].createElement(Select, _extends({
        multiple: multiple,
        name: name,
        onCloseButtonClicked: function onCloseButtonClicked(_ref16) {
          var event = _ref16.event,
              value = _ref16.value;
          return onChange(event, value);
        },
        onDropdownItemClicked: function onDropdownItemClicked(_ref17) {
          var event = _ref17.event,
              value = _ref17.value;
          return onChange(event, value);
        },
        onExpand: function onExpand(_ref18) {
          var event = _ref18.event,
              expand = _ref18.expand;

          if (expand) {
            onFocus(event);
          } else {
            onBlur(event);
          }
        },
        options: normalizedOptions,
        predefinedValue: predefinedValueArray,
        readOnly: readOnly,
        value: value
      }, otherProps)));
    };

    Main.displayName = 'Select';
    var _default = Main;
    exports["default"] = _default;
    //# sourceMappingURL=Select.es.js.map
  }
});
//# sourceMappingURL=Select.es.js.map