Liferay.Loader.define("commerce-frontend-taglib@10.1.5/search_results/SearchResults.es", ['module', 'exports', 'require', 'frontend-js-web', 'frontend-js-metal-web$metal-component', 'frontend-js-metal-web$metal-soy', './SearchResults.soy'], function (module, exports, require) {
  var define = undefined;
  var global = window;
  {
    Object.defineProperty(exports, "__esModule", {
      value: true
    });
    exports.default = exports.SearchResults = void 0;

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

    var _metalComponent = _interopRequireDefault(require("frontend-js-metal-web$metal-component"));

    var _metalSoy = _interopRequireWildcard(require("frontend-js-metal-web$metal-soy"));

    var _SearchResults = _interopRequireDefault(require("./SearchResults.soy"));

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

    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 _classCallCheck(instance, Constructor) {
      if (!(instance instanceof Constructor)) {
        throw new TypeError("Cannot call a class as a function");
      }
    }

    function _defineProperties(target, props) {
      for (var i = 0; i < props.length; i++) {
        var descriptor = props[i];descriptor.enumerable = descriptor.enumerable || false;descriptor.configurable = true;if ("value" in descriptor) descriptor.writable = true;Object.defineProperty(target, descriptor.key, descriptor);
      }
    }

    function _createClass(Constructor, protoProps, staticProps) {
      if (protoProps) _defineProperties(Constructor.prototype, protoProps);if (staticProps) _defineProperties(Constructor, staticProps);return Constructor;
    }

    function _possibleConstructorReturn(self, call) {
      if (call && (_typeof(call) === "object" || typeof call === "function")) {
        return call;
      }return _assertThisInitialized(self);
    }

    function _assertThisInitialized(self) {
      if (self === void 0) {
        throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
      }return self;
    }

    function _getPrototypeOf(o) {
      _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
        return o.__proto__ || Object.getPrototypeOf(o);
      };return _getPrototypeOf(o);
    }

    function _inherits(subClass, superClass) {
      if (typeof superClass !== "function" && superClass !== null) {
        throw new TypeError("Super expression must either be null or a function");
      }subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } });if (superClass) _setPrototypeOf(subClass, superClass);
    }

    function _setPrototypeOf(o, p) {
      _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
        o.__proto__ = p;return o;
      };return _setPrototypeOf(o, p);
    }

    var SearchResults = /*#__PURE__*/function (_Component) {
      _inherits(SearchResults, _Component);

      function SearchResults() {
        _classCallCheck(this, SearchResults);

        return _possibleConstructorReturn(this, _getPrototypeOf(SearchResults).apply(this, arguments));
      }

      _createClass(SearchResults, [{
        key: "created",
        value: function created() {
          this.search = (0, _frontendJsWeb.debounce)(this.search.bind(this), 500);
          this.handleKeyDown = this.handleKeyDown.bind(this);
          window.Liferay.on('search-term-update', this.updateQuery, this);
          window.Liferay.on('search-term-submit', this.goToSelected, this);
        }
      }, {
        key: "detached",
        value: function detached() {
          window.Liferay.detach('search-term-update', this.updateQuery, this);
          window.Liferay.detach('search-term-submit', this.goToSelected, this);
          document.removeEventListener('keydown', this.handleKeyDown);
        }
      }, {
        key: "getFirstSuggestion",
        value: function getFirstSuggestion() {
          var selectables = this.results.filter(function (i) {
            return i.type !== 'label';
          });
          return selectables.length ? selectables[0].pos : -1;
        }
      }, {
        key: "getLastSuggestion",
        value: function getLastSuggestion() {
          var selectables = this.results.filter(function (i) {
            return i.type !== 'label';
          }).reverse();
          return selectables.length ? selectables[0].pos : -1;
        }
      }, {
        key: "goToSelected",
        value: function goToSelected() {
          var selected = this.results.filter(function (i) {
            return i.selected;
          });

          if (selected.length && selected[0].url) {
            if (Liferay.SPA) {
              Liferay.SPA.app.navigate(selected[0].url);
            } else {
              window.location.href = selected[0].url;
            }
          }
        }
      }, {
        key: "handleKeyDown",
        value: function handleKeyDown(e) {
          if (e.key === 'ArrowDown') {
            this.selectNext();
          } else if (e.key === 'ArrowUp') {
            this.selectPrevious();
          }
        }
      }, {
        key: "handleMouseEnter",
        value: function handleMouseEnter(e) {
          this.selectedIndex = parseInt(e.delegateTarget.dataset.pos, 10);
        }
      }, {
        key: "handleMouseLeave",
        value: function handleMouseLeave(_e) {
          this.selectedIndex = this.getFirstSuggestion();
        }
      }, {
        key: "rendered",
        value: function rendered() {
          if (this.refs && this.refs.selected) {
            this.refs.selected.scrollIntoView({
              behavior: 'smooth',
              block: 'nearest'
            });
          }
        }
      }, {
        key: "search",
        value: function search() {
          var _this = this;

          if (this.lock) {
            return;
          }

          this.lock = true;
          (0, _frontendJsWeb.fetch)(this.searchAPI + themeDisplay.getPlid() + '?commerceAccountId=' + this.commerceAccountId + '&groupId=' + themeDisplay.getScopeGroupId() + '&q=' + this.queryString).then(function (response) {
            return response.json();
          }).then(function (results) {
            _this.loading = false;
            _this.lock = false;
            _this.queryValue = _this.queryString;
            _this.results = results;
            _this.selectedIndex = -1;

            _this.selectNext();
          });
        }
      }, {
        key: "selectNext",
        value: function selectNext() {
          var _this2 = this;

          var nexts = this.results.filter(function (i) {
            return i.pos > _this2.selectedIndex && i.type !== 'label';
          });
          this.selectedIndex = nexts.length ? nexts[0].pos : this.getFirstSuggestion();
        }
      }, {
        key: "selectPrevious",
        value: function selectPrevious() {
          var _this3 = this;

          var prevs = this.results.filter(function (i) {
            return i.pos < _this3.selectedIndex && i.type !== 'label';
          }).reverse();
          this.selectedIndex = prevs.length ? prevs[0].pos : this.getLastSuggestion();
        }
      }, {
        key: "setSelected",
        value: function setSelected(sel) {
          sel = (sel + 1 + this.results.length + 1) % (this.results.length + 1) - 1;
          this.results = this.results.map(function (item, i) {
            return _objectSpread(_objectSpread({}, item), {}, {
              pos: i,
              selected: i === sel
            });
          });
          return sel;
        }
      }, {
        key: "updateQuery",
        value: function updateQuery(event) {
          this.loading = true;
          this.queryString = event.term;
          this.visible = event.term !== '';
          this.search();
        }
      }, {
        key: "willUpdate",
        value: function willUpdate(_ref) {
          var visible = _ref.visible;

          if (visible) {
            if (visible.newVal) {
              document.addEventListener('keydown', this.handleKeyDown);
            } else {
              document.removeEventListener('keydown', this.handleKeyDown);
            }
          }
        }
      }, {
        key: "_handleClick",
        value: function _handleClick() {
          this.goToSelected();
        }
      }]);

      return SearchResults;
    }(_metalComponent.default);

    exports.SearchResults = SearchResults;

    _metalSoy.default.register(SearchResults, _SearchResults.default);

    SearchResults.STATE = {
      commerceAccountId: _metalSoy.Config.oneOfType([_metalSoy.Config.number(), _metalSoy.Config.string()]),
      loading: _metalSoy.Config.bool().value(false),
      queryString: _metalSoy.Config.string().value(''),
      queryValue: _metalSoy.Config.string().value(''),
      results: {
        value: []
      },
      searchAPI: _metalSoy.Config.string().required(),
      selectedIndex: {
        setter: 'setSelected',
        value: -1
      },
      spritemap: _metalSoy.Config.string().required(),
      visible: _metalSoy.Config.bool().value(false)
    };
    var _default = SearchResults;
    exports.default = _default;
    //# sourceMappingURL=SearchResults.es.js.map
  }
});
//# sourceMappingURL=SearchResults.es.js.map