Liferay.Loader.define("frontend-taglib-clay@6.3.12/data_set_display/management_bar/components/filters/AutocompleteFilter", ['module', 'exports', 'require', '@frontend-taglib-clay$clayui/autocomplete', '@frontend-taglib-clay$clayui/button', '@frontend-taglib-clay$clayui/drop-down', '@frontend-taglib-clay$clayui/form', '@frontend-taglib-clay$clayui/label', '@frontend-taglib-clay$clayui/loading-indicator', 'frontend-js-react-web', 'frontend-js-web', 'frontend-taglib-clay$prop-types', 'frontend-js-react-web$react', '../../../utilities/index', '../../../utilities/logError'], 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 _autocomplete = _interopRequireDefault(require("@frontend-taglib-clay$clayui/autocomplete"));

    var _button = _interopRequireDefault(require("@frontend-taglib-clay$clayui/button"));

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

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

    var _label = _interopRequireDefault(require("@frontend-taglib-clay$clayui/label"));

    var _loadingIndicator = _interopRequireDefault(require("@frontend-taglib-clay$clayui/loading-indicator"));

    var _frontendJsReactWeb = require("frontend-js-react-web");

    var _frontendJsWeb = require("frontend-js-web");

    var _propTypes = _interopRequireDefault(require("frontend-taglib-clay$prop-types"));

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

    var _index = require("../../../utilities/index");

    var _logError = require("../../../utilities/logError");

    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 _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;
      }
    }

    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;
    }

    var DEFAULT_PAGE_SIZE = 10;

    function fetchData(apiURL, searchParam) {
      var currentPage = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1;
      var url = new URL(apiURL, themeDisplay.getPortalURL());
      url.searchParams.append('page', currentPage);
      url.searchParams.append('pageSize', DEFAULT_PAGE_SIZE);

      if (searchParam) {
        url.searchParams.append('search', encodeURIComponent(searchParam));
      }

      return (0, _frontendJsWeb.fetch)(url, {
        headers: {
          'Accept-Language': (0, _index.getAcceptLanguageHeaderParam)()
        }
      }).then(function (response) {
        return response.json();
      });
    }

    function Item(props) {
      var Input = props.selectionType === 'single' ? _form.ClayRadio : _form.ClayCheckbox;
      return (/*#__PURE__*/_react.default.createElement("li", null, /*#__PURE__*/_react.default.createElement(Input, {
          checked: props.selected,
          label: props.label,
          onChange: props.onChange,
          value: props.value
        }))
      );
    }

    function composeMultipleValuesOdataString(key, values, exclude) {
      return "".concat(key, "/any(x:").concat(values.map(function (value) {
        return "(x ".concat(exclude ? 'ne' : 'eq', " ").concat(typeof value === 'string' ? "'".concat(value, "'") : value, ")");
      }).join(exclude ? ' and ' : ' or '), ")");
    }

    function composeSingleValuesOdataString(key, value, exclude) {
      return "".concat(key, " ").concat(exclude ? 'ne' : 'eq', " ").concat(typeof value === 'string' ? "'".concat(value, "'") : value);
    }

    var formatValue = function formatValue(value, exclude) {
      return (exclude ? "(".concat(Liferay.Language.get('exclude'), ") ") : '') + value.map(function (el) {
        return el.label;
      }).join(', ');
    };

    function getOdataString(selectedItems, key, selectionType, exclude) {
      if (selectedItems === null || selectedItems === void 0 ? void 0 : selectedItems.length) {
        var values = selectedItems.map(function (item) {
          return item.value;
        });
        return selectionType === 'multiple' ? composeMultipleValuesOdataString(key, values, exclude) : composeSingleValuesOdataString(key, values[0], exclude);
      }

      return null;
    }

    function AutocompleteFilter(_ref) {
      var actions = _ref.actions,
          apiURL = _ref.apiURL,
          id = _ref.id,
          inputPlaceholder = _ref.inputPlaceholder,
          itemKey = _ref.itemKey,
          itemLabelProp = _ref.itemLabel,
          selectionType = _ref.selectionType,
          valueProp = _ref.value;

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

      var _useState3 = (0, _react.useState)(''),
          _useState4 = _slicedToArray(_useState3, 2),
          search = _useState4[0],
          setSearch = _useState4[1];

      var _useState5 = (0, _react.useState)((valueProp === null || valueProp === void 0 ? void 0 : valueProp.items) || []),
          _useState6 = _slicedToArray(_useState5, 2),
          selectedItems = _useState6[0],
          setSelectedItems = _useState6[1];

      var _useState7 = (0, _react.useState)(null),
          _useState8 = _slicedToArray(_useState7, 2),
          items = _useState8[0],
          updateItems = _useState8[1];

      var _useState9 = (0, _react.useState)(false),
          _useState10 = _slicedToArray(_useState9, 2),
          loading = _useState10[0],
          setLoading = _useState10[1];

      var _useState11 = (0, _react.useState)(1),
          _useState12 = _slicedToArray(_useState11, 2),
          currentPage = _useState12[0],
          setCurrentPage = _useState12[1];

      var _useState13 = (0, _react.useState)(0),
          _useState14 = _slicedToArray(_useState13, 2),
          total = _useState14[0],
          updateTotal = _useState14[1];

      var scrollingArea = (0, _react.useRef)(null);

      var _useState15 = (0, _react.useState)(false),
          _useState16 = _slicedToArray(_useState15, 2),
          scrollingAreaRendered = _useState16[0],
          setScrollingAreaRendered = _useState16[1];

      var infiniteLoader = (0, _react.useRef)(null);

      var _useState17 = (0, _react.useState)(false),
          _useState18 = _slicedToArray(_useState17, 2),
          infiniteLoaderRendered = _useState18[0],
          setInfiniteLoaderRendered = _useState18[1];

      var _useState19 = (0, _react.useState)(!!(valueProp === null || valueProp === void 0 ? void 0 : valueProp.exclude)),
          _useState20 = _slicedToArray(_useState19, 2),
          exclude = _useState20[0],
          setExclude = _useState20[1];

      var loaderVisible = items && items.length < total;
      (0, _react.useEffect)(function () {
        setSelectedItems((valueProp === null || valueProp === void 0 ? void 0 : valueProp.items) || []);
      }, [valueProp]);
      (0, _react.useEffect)(function () {
        if (query === search) {
          return;
        }

        setCurrentPage(1);
        setSearch(query);
      }, [query, search]);
      var isMounted = (0, _frontendJsReactWeb.useIsMounted)();
      (0, _react.useEffect)(function () {
        setLoading(true);
        fetchData(apiURL, search, currentPage).then(function (data) {
          if (!isMounted()) {
            return;
          }

          setLoading(false);

          if (currentPage === 1) {
            updateItems(data.items);
          } else {
            updateItems(function (items) {
              return [].concat(_toConsumableArray(items), _toConsumableArray(data.items));
            });
          }

          updateTotal(data.totalCount);
        }).catch(function (error) {
          (0, _logError.logError)(error);

          if (isMounted()) {
            setLoading(false);
          }
        });
      }, [currentPage, isMounted, search, apiURL]);
      var setScrollingArea = (0, _react.useCallback)(function (node) {
        scrollingArea.current = node;
        setScrollingAreaRendered(true);
      }, []);
      var setInfiniteLoader = (0, _react.useCallback)(function (node) {
        infiniteLoader.current = node;
        setInfiniteLoaderRendered(true);
      }, []);
      var setObserver = (0, _react.useCallback)(function () {
        if (!scrollingArea.current || !infiniteLoader.current || !IntersectionObserver) {
          return;
        }

        var options = {
          root: scrollingArea.current,
          rootMargin: '0px',
          threshold: 1.0
        };
        var observer = new IntersectionObserver(function (entries) {
          if (entries[0].intersectionRatio <= 0) {
            return;
          }

          setCurrentPage(function (page) {
            return page + 1;
          });
        }, options);
        observer.observe(infiniteLoader.current);
      }, []);
      (0, _react.useEffect)(function () {
        if (scrollingAreaRendered && infiniteLoaderRendered && loaderVisible) {
          setObserver();
        }
      }, [scrollingAreaRendered, infiniteLoaderRendered, loaderVisible, setObserver]);
      var actionType = 'edit';

      if ((valueProp === null || valueProp === void 0 ? void 0 : valueProp.items) && !selectedItems.length) {
        actionType = 'delete';
      }

      if (!valueProp) {
        actionType = 'add';
      }

      var submitDisabled = true;

      if (actionType === 'delete' || !valueProp && selectedItems.length || valueProp && (0, _index.isValuesArrayChanged)(valueProp.items, selectedItems) || valueProp && selectedItems.length && valueProp.exclude !== exclude) {
        submitDisabled = false;
      }

      return (/*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_dropDown.default.Caption, null, /*#__PURE__*/_react.default.createElement(_autocomplete.default, null, /*#__PURE__*/_react.default.createElement(_autocomplete.default.Input, {
          onChange: function onChange(event) {
            return setQuery(event.target.value);
          },
          placeholder: inputPlaceholder
        }), loading && /*#__PURE__*/_react.default.createElement(_autocomplete.default.LoadingIndicator, null)), selectedItems.length ? /*#__PURE__*/_react.default.createElement("div", {
          className: "mt-2 selected-elements-wrapper"
        }, selectedItems.map(function (selectedItem) {
          return (/*#__PURE__*/_react.default.createElement(_label.default, {
              closeButtonProps: {
                onClick: function onClick() {
                  return setSelectedItems(function (items) {
                    return items.filter(function (item) {
                      return item.value !== selectedItem.value;
                    });
                  });
                }
              },
              key: selectedItem.value
            }, selectedItem.label)
          );
        })) : null), /*#__PURE__*/_react.default.createElement(_dropDown.default.Divider, null), /*#__PURE__*/_react.default.createElement(_dropDown.default.Caption, {
          className: "py-0"
        }, /*#__PURE__*/_react.default.createElement("div", {
          className: "row"
        }, /*#__PURE__*/_react.default.createElement("div", {
          className: "col"
        }, /*#__PURE__*/_react.default.createElement("label", {
          htmlFor: "autocomplete-exclude-".concat(id)
        }, Liferay.Language.get('exclude'))), /*#__PURE__*/_react.default.createElement("div", {
          className: "col-auto"
        }, /*#__PURE__*/_react.default.createElement(_form.ClayToggle, {
          id: "autocomplete-exclude-".concat(id),
          onToggle: function onToggle() {
            return setExclude(!exclude);
          },
          toggled: exclude
        })))), /*#__PURE__*/_react.default.createElement(_dropDown.default.Divider, null), /*#__PURE__*/_react.default.createElement(_dropDown.default.Caption, null, /*#__PURE__*/_react.default.createElement("div", {
          className: "form-group"
        }, items && items.length ? /*#__PURE__*/_react.default.createElement("ul", {
          className: "inline-scroller mb-n2 mx-n2 px-2",
          ref: setScrollingArea
        }, items.map(function (item) {
          var itemValue = item[itemKey];
          var itemLabel = (0, _index.getValueFromItem)(item, itemLabelProp);
          var newValue = {
            label: itemLabel,
            value: itemValue
          };
          return (/*#__PURE__*/_react.default.createElement(Item, {
              key: itemValue,
              label: itemLabel,
              onChange: function onChange() {
                setSelectedItems(selectedItems.find(function (el) {
                  return el.value === itemValue;
                }) ? selectedItems.filter(function (el) {
                  return el.value !== itemValue;
                }) : selectionType === 'multiple' ? [].concat(_toConsumableArray(selectedItems), [newValue]) : [newValue]);
              },
              selected: Boolean(selectedItems.find(function (el) {
                return el.value === itemValue;
              })),
              selectionType: selectionType,
              value: itemValue
            })
          );
        }), loaderVisible && /*#__PURE__*/_react.default.createElement(_loadingIndicator.default, {
          ref: setInfiniteLoader,
          small: true
        })) : /*#__PURE__*/_react.default.createElement("div", {
          className: "mt-2 p-2 text-muted"
        }, Liferay.Language.get('no-items-were-found')))), /*#__PURE__*/_react.default.createElement(_dropDown.default.Divider, null), /*#__PURE__*/_react.default.createElement(_dropDown.default.Caption, null, /*#__PURE__*/_react.default.createElement(_button.default, {
          disabled: submitDisabled,
          onClick: function onClick() {
            return actionType !== 'delete' ? actions.updateFilterState(id, {
              exclude: exclude,
              items: selectedItems
            }, formatValue(selectedItems, exclude), getOdataString(selectedItems, id, selectionType, exclude)) : actions.updateFilterState(id);
          },
          small: true
        }, actionType === 'add' && Liferay.Language.get('add-filter'), actionType === 'edit' && Liferay.Language.get('edit-filter'), actionType === 'delete' && Liferay.Language.get('delete-filter'))))
      );
    }

    AutocompleteFilter.defaultProps = {
      selectionType: 'multiple'
    };
    var _default = AutocompleteFilter;
    exports.default = _default;
    //# sourceMappingURL=AutocompleteFilter.js.map
  }
});
//# sourceMappingURL=AutocompleteFilter.js.map