Liferay.Loader.define("commerce-frontend-js@3.0.26/components/autocomplete/Autocomplete", ['module', 'exports', 'require', '@frontend-taglib-clay$clayui/autocomplete', '@frontend-taglib-clay$clayui/drop-down', '@frontend-taglib-clay$clayui/shared', 'frontend-js-react-web$prop-types', 'frontend-js-react-web$react', '../../utilities/debounce', '../../utilities/eventsDefinitions', '../../utilities/index', '../../utilities/modules', '../../utilities/notifications'], 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 _dropDown = _interopRequireDefault(require("@frontend-taglib-clay$clayui/drop-down"));

    var _shared = require("@frontend-taglib-clay$clayui/shared");

    var _propTypes = _interopRequireDefault(require("frontend-js-react-web$prop-types"));

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

    var _debounce = require("../../utilities/debounce");

    var _eventsDefinitions = require("../../utilities/eventsDefinitions");

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

    var _modules = require("../../utilities/modules");

    var _notifications = require("../../utilities/notifications");

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

    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 Autocomplete(_ref) {
      var onValueUpdated = _ref.onValueUpdated,
          props = _objectWithoutProperties(_ref, ["onValueUpdated"]);

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

      var _useState3 = (0, _react.useState)(false),
          _useState4 = _slicedToArray(_useState3, 2),
          initialised = _useState4[0],
          setInitialised = _useState4[1];

      var _useState5 = (0, _react.useState)(null),
          _useState6 = _slicedToArray(_useState5, 2),
          debouncedGetItems = _useState6[0],
          updateDebouncedGetItems = _useState6[1];

      var _useState7 = (0, _react.useState)(false),
          _useState8 = _slicedToArray(_useState7, 2),
          active = _useState8[0],
          setActive = _useState8[1];

      var _useState9 = (0, _react.useState)(props.initialValue),
          _useState10 = _slicedToArray(_useState9, 2),
          selectedItem = _useState10[0],
          updateSelectedItem = _useState10[1];

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

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

      var _useState15 = (0, _react.useState)(null),
          _useState16 = _slicedToArray(_useState15, 2),
          totalCount = _useState16[0],
          updateTotalCount = _useState16[1];

      var _useState17 = (0, _react.useState)(null),
          _useState18 = _slicedToArray(_useState17, 2),
          lastPage = _useState18[0],
          updateLastPage = _useState18[1];

      var _useState19 = (0, _react.useState)(1),
          _useState20 = _slicedToArray(_useState19, 2),
          page = _useState20[0],
          updatePage = _useState20[1];

      var _useState21 = (0, _react.useState)(props.pageSize),
          _useState22 = _slicedToArray(_useState21, 2),
          pageSize = _useState22[0],
          updatePageSize = _useState22[1];

      var node = (0, _react.useRef)();
      var dropdownNode = (0, _react.useRef)();
      var inputNode = (0, _react.useRef)();
      var FetchedCustomView = (0, _modules.useLiferayModule)(props.customViewModuleUrl);
      (0, _react.useEffect)(function () {
        updateDebouncedGetItems(function () {
          return (0, _debounce.debouncePromise)(_index.getData, props.fetchDataDebounce);
        });
      }, [props.fetchDataDebounce]);
      (0, _react.useEffect)(function () {
        if (items && items.length === 1 && props.autofill) {
          var firstItem = items[0];
          updateSelectedItem(firstItem);
        }
      }, [items, props.autofill, props.itemsKey, props.itemsLabel]);
      (0, _react.useEffect)(function () {
        var value = selectedItem && (0, _index.getValueFromItem)(selectedItem, props.itemsKey);

        if (props.id) {
          Liferay.fire(_eventsDefinitions.AUTOCOMPLETE_VALUE_UPDATED, {
            id: props.id,
            itemData: selectedItem,
            value: value
          });
        }

        if (onValueUpdated) {
          onValueUpdated(value, selectedItem);
        }
      }, [selectedItem, props.id, props.itemsKey, onValueUpdated]);
      (0, _react.useEffect)(function () {
        if (query) {
          setInitialised(true);
        }
      }, [query]);
      (0, _react.useEffect)(function () {
        if (initialised) {
          setLoading(true);
          debouncedGetItems(props.apiUrl, query, page, pageSize).then(function (jsonResponse) {
            if (props.infinityScrollMode) {
              updateItems(function (prevItems) {
                return (prevItems === null || prevItems === void 0 ? void 0 : prevItems.length) && page > 1 ? [].concat(_toConsumableArray(prevItems), _toConsumableArray(jsonResponse.items)) : jsonResponse.items;
              });
            } else {
              updateItems(jsonResponse.items);
            }

            updateTotalCount(jsonResponse.totalCount);
            updateLastPage(jsonResponse.lastPage);
            setLoading(false);

            if (!query) {
              return;
            }

            var found = jsonResponse.items.find(function (item) {
              return (0, _index.getValueFromItem)(item, props.itemsLabel) === query;
            });

            if (found) {
              updateSelectedItem(found);
            }
          }).catch(function () {
            (0, _notifications.showErrorNotification)();
            setLoading(false);
          });
        }
      }, [debouncedGetItems, initialised, query, page, pageSize, props.infinityScrollMode, props.apiUrl, props.itemsLabel, props.showErrorNotification]);
      (0, _react.useEffect)(function () {
        function handleClick(e) {
          if (node.current.contains(e.target) || dropdownNode.current && dropdownNode.current.contains(e.target)) {
            return;
          }

          setActive(false);
        }

        if (active) {
          document.addEventListener('mousedown', handleClick);
        }

        return function () {
          document.removeEventListener('mousedown', handleClick);
        };
      }, [active]);
      var currentValue = selectedItem ? (0, _index.getValueFromItem)(selectedItem, props.itemsKey) : null;
      var currentLabel = selectedItem ? (0, _index.getValueFromItem)(selectedItem, props.itemsLabel) : null;
      var CustomView = props.customView || FetchedCustomView;
      return (/*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_shared.FocusScope, null, /*#__PURE__*/_react.default.createElement(_autocomplete.default, {
          ref: node
        }, /*#__PURE__*/_react.default.createElement("input", {
          id: props.inputId || props.inputName,
          name: props.inputName,
          type: "hidden",
          value: currentValue || ''
        }), /*#__PURE__*/_react.default.createElement(_autocomplete.default.Input, {
          onChange: function onChange(event) {
            updateSelectedItem(null);
            updatePage(1);
            setQuery(event.target.value);
          },
          onFocus: function onFocus(_e) {
            setActive(true);
            setInitialised(true);
          },
          onKeyUp: function onKeyUp(e) {
            if (e.keyCode === 27) {
              setActive(false);
            } else {
              setActive(true);
            }
          },
          placeholder: props.inputPlaceholder,
          ref: inputNode,
          required: props.required || false,
          value: currentLabel || query
        }), !CustomView && /*#__PURE__*/_react.default.createElement(_autocomplete.default.DropDown, {
          active: active && !loading
        }, /*#__PURE__*/_react.default.createElement("div", {
          className: "autocomplete-items",
          ref: dropdownNode
        }, /*#__PURE__*/_react.default.createElement(_dropDown.default.ItemList, {
          className: "mb-0"
        }, items && items.length === 0 && /*#__PURE__*/_react.default.createElement(_dropDown.default.Item, {
          className: "disabled"
        }, Liferay.Language.get('no-items-were-found')), items && items.length > 0 && items.map(function (item) {
          return (/*#__PURE__*/_react.default.createElement(_autocomplete.default.Item, {
              key: String(item[props.itemsKey]),
              onClick: function onClick() {
                updateSelectedItem(item);
                setActive(false);
              },
              value: String((0, _index.getValueFromItem)(item, props.itemsLabel))
            })
          );
        })))), loading && /*#__PURE__*/_react.default.createElement(_autocomplete.default.LoadingIndicator, null))), CustomView && /*#__PURE__*/_react.default.createElement(CustomView, {
          items: items,
          lastPage: lastPage,
          page: page,
          pageSize: pageSize,
          totalCount: totalCount,
          updatePage: updatePage,
          updatePageSize: updatePageSize
        }))
      );
    }

    Autocomplete.defaultProps = {
      autofill: false,
      fetchDataDebounce: 200,
      infinityScrollMode: false,
      initialLabel: '',
      initialValue: '',
      inputPlaceholder: Liferay.Language.get('type-here'),
      pageSize: 20
    };
    var _default = Autocomplete;
    exports.default = _default;
    //# sourceMappingURL=Autocomplete.js.map
  }
});
//# sourceMappingURL=Autocomplete.js.map