Liferay.Loader.define("portal-search-ranking-web@2.0.50/js/components/add_result/AddResultModal.es", ['module', 'exports', 'require', '@frontend-taglib-clay$clayui/button', '@frontend-taglib-clay$clayui/data-provider', '@frontend-taglib-clay$clayui/form', '@frontend-taglib-clay$clayui/icon', '@frontend-taglib-clay$clayui/layout', '@frontend-taglib-clay$clayui/loading-indicator', '@frontend-taglib-clay$clayui/modal', '@frontend-taglib-clay$clayui/pagination-bar', '@frontend-taglib-clay$clayui/tooltip', 'frontend-js-react-web$classnames', 'frontend-js-react-web', 'frontend-js-react-web$prop-types', 'frontend-js-react-web$react', '../../ThemeContext.es', '../../utils/constants.es', '../../utils/language.es', '../../utils/util.es', '../list/Item.es', '../shared/ClayEmptyState.es', './AddResultSearchBar.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 _button = _interopRequireDefault(require("@frontend-taglib-clay$clayui/button"));

    var _dataProvider = require("@frontend-taglib-clay$clayui/data-provider");

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

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

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

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

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

    var _paginationBar = require("@frontend-taglib-clay$clayui/pagination-bar");

    var _tooltip = require("@frontend-taglib-clay$clayui/tooltip");

    var _classnames = _interopRequireDefault(require("frontend-js-react-web$classnames"));

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

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

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

    var _ThemeContext = _interopRequireDefault(require("../../ThemeContext.es"));

    var _constants = require("../../utils/constants.es");

    var _language = require("../../utils/language.es");

    var _util = require("../../utils/util.es");

    var _Item = _interopRequireDefault(require("../list/Item.es"));

    var _ClayEmptyState = _interopRequireWildcard(require("../shared/ClayEmptyState.es"));

    var _AddResultSearchBar = _interopRequireDefault(require("./AddResultSearchBar.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 _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 _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 _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;
    }

    /**
     * A button that opens a modal to be able to search, select, and add results.
     */
    function AddResultModal(_ref) {
      var _buildUrl;

      var fetchDocumentsSearchUrl = _ref.fetchDocumentsSearchUrl,
          observer = _ref.observer,
          onAddResultSubmit = _ref.onAddResultSubmit,
          onClose = _ref.onClose;

      var _useContext = (0, _react.useContext)(_ThemeContext.default),
          companyId = _useContext.companyId,
          namespace = _useContext.namespace,
          spritemap = _useContext.spritemap;
      /**
       * State flow: resourceNotAsked -> loading -> error/success
       * Success is implicit when all are false.
       */

      var _useState = (0, _react.useState)(function () {
        return {
          error: false,
          loading: false
        };
      }),
          _useState2 = _slicedToArray(_useState, 2),
          resourceState = _useState2[0],
          setResourceState = _useState2[1];

      var error = resourceState.error,
          loading = resourceState.loading;

      var _useState3 = (0, _react.useState)(_constants.DEFAULT_DELTA.label),
          _useState4 = _slicedToArray(_useState3, 2),
          delta = _useState4[0],
          setDelta = _useState4[1];

      var _useState5 = (0, _react.useState)(true),
          _useState6 = _slicedToArray(_useState5, 2),
          resourceNotAsked = _useState6[0],
          setResourceNotAsked = _useState6[1];

      var _useState7 = (0, _react.useState)(1),
          _useState8 = _slicedToArray(_useState7, 2),
          page = _useState8[0],
          setPage = _useState8[1];

      var _useState9 = (0, _react.useState)(''),
          _useState10 = _slicedToArray(_useState9, 2),
          searchQuery = _useState10[0],
          setSearchQuery = _useState10[1];

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

      var prevDelta = (0, _frontendJsReactWeb.usePrevious)(delta);
      var prevPage = (0, _frontendJsReactWeb.usePrevious)(page);
      /**
       * Stores the full object data of selected results. This is used to
       * transform the `selectedIds` into a the list of objects to send to
       * `onAddResultSubmit`.
       */

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

      var _useResource = (0, _dataProvider.useResource)({
        fetchOptions: _constants.FETCH_OPTIONS,
        link: (0, _util.buildUrl)(fetchDocumentsSearchUrl, (_buildUrl = {}, _defineProperty(_buildUrl, "".concat(namespace, "companyId"), companyId), _defineProperty(_buildUrl, "".concat(namespace, "from"), page * delta - delta), _defineProperty(_buildUrl, "".concat(namespace, "keywords"), searchQuery), _defineProperty(_buildUrl, "".concat(namespace, "size"), delta), _buildUrl)),
        onNetworkStatusChange: function onNetworkStatusChange(status) {
          return setResourceState({
            error: status === 5,
            loading: status < 4
          });
        }
      }),
          refetch = _useResource.refetch,
          resource = _useResource.resource;
      /**
       * Fetches for new data when the delta or page change.
       */

      (0, _react.useEffect)(function () {
        if (prevDelta !== delta || prevPage !== page) {
          refetch();
        }
      }, [delta, page, prevDelta, prevPage, refetch]);
      /**
       * Deselects all items on the current page.
       */

      function _deselectAll() {
        setSelectedIds(selectedIds.filter(function (resultId) {
          return !_getCurrentResultIds().includes(resultId);
        }));
      }
      /**
       * Gets the ids of the current results displayed on the page.
       * @returns {Array} List of ids
       */

      function _getCurrentResultIds() {
        return resource.documents.map(function (result) {
          return result.id;
        });
      }
      /**
       * Gets the selected ids on the current page. Useful for displaying the
       * proper checkbox and performing the proper action when clicking on the
       * checkbox.
       * @returns {Array} List of ids
       */

      function _getCurrentResultSelectedIds() {
        return selectedIds.filter(function (resultId) {
          return _getCurrentResultIds().includes(resultId);
        });
      }
      /**
       * Gets the result data object from ids.
       * @param {Array} ids The list of ids to get.
       * @returns {Array} List of result data objects.
       */

      function _getResultData(ids) {
        return resource.documents.filter(function (_ref2) {
          var id = _ref2.id;
          return ids.includes(id);
        });
      }
      /**
       * Controls the behavior when clicking on the list header checkbox.
       * If any results on the current page are selected, the items will be
       * deselected. Otherwise, select all items.
       */

      function _handleAllCheckbox() {
        if (_getCurrentResultSelectedIds().length > 0) {
          _deselectAll();
        } else {
          _selectAll();
        }
      }
      /**
       * Removes all selected ids.
       */

      function _handleClearAllSelected() {
        setSelectedIds([]);
      }
      /**
       * Sets the new delta, resets to the first page, and fetches for the new
       * set of results.
       * @param {number} newDelta The delta selected.
       */

      function _handleDeltaChange(newDelta) {
        setDelta(newDelta);
        setPage(1);
      }
      /**
       * Sets the new page selected and fetches for the new results.
       * @param {number} newPage The page selected.
       */

      function _handlePageChange(newPage) {
        setPage(newPage);
      }
      /**
       * Wrapper around the `refetch` function to keep track if it has been
       * called to be able to show an initial display. This is a workaround
       * since there isn't currently a way to prevent an initial fetch from
       * being called when using `useResource`.
       */

      function _handleRefetch() {
        setResourceNotAsked(false);
        refetch();
      }
      /**
       * When the 'Enter' key is pressed, the page will reset back to the first
       * page, selections will be cleared, and a new search will be performed.
       * If the search query is blank, nothing will happen.
       * @param {SyntheticEvent} event
       */

      /**
       * Updates the search query input field.
       * @param {SyntheticEvent} event
       */

      /**
       * Handles when an item's checkbox is clicked on.
       * @param {String} id The id selected.
       */

      function _handleSelect(id) {
        var resultDataToSelect = _getResultData([id]);

        setDataMap((0, _util.resultsDataToMap)(resultDataToSelect, dataMap));
        setSelectedIds((0, _util.toggleListItem)(selectedIds, id));
      }
      /**
       * Primary action of the modal. Pins the selected results to the result
       * rankings form.
       * @param {SyntheticEvent} event
       */

      /**
       * Checks if there are any results to display.
       * @returns {boolean} True if there is data.
       */

      /**
       * Selects all items on the current page.
       */

      function _selectAll() {
        _deselectAll(); // Deselect all items first to avoid adding duplicates.


        var resultDataToSelect = _getResultData(_getCurrentResultIds());

        setDataMap((0, _util.resultsDataToMap)(resultDataToSelect, dataMap));
        setSelectedIds([].concat(_toConsumableArray(selectedIds), _toConsumableArray(_getCurrentResultIds())));
      }
      /**
       * Renders the empty state. Conditionally shows 3 different empty states:
       * 1) Initial message with help text.
       * 2) Empty result message when a search returns no matches.
       * 3) Error message when a search request fails to resolve.
       */

      /**
       * Displays the search results with a management and pagination bar.
       */

      return (/*#__PURE__*/_react.default.createElement(_modal.default, {
          className: "result-ranking-modal-root",
          observer: observer,
          size: "lg"
        }, /*#__PURE__*/_react.default.createElement("div", {
          className: "add-result-modal-root",
          "data-testid": "add-result-modal"
        }, /*#__PURE__*/_react.default.createElement(_modal.default.Header, null, Liferay.Language.get('add-result'), /*#__PURE__*/_react.default.createElement("span", {
          className: (0, _classnames.default)('inline-item', 'inline-item-after', 'modal-title-help-icon')
        }, /*#__PURE__*/_react.default.createElement(_tooltip.ClayTooltipProvider, null, /*#__PURE__*/_react.default.createElement(_icon.default, {
          symbol: "question-circle-full",
          title: Liferay.Language.get('add-results-help')
        })))), /*#__PURE__*/_react.default.createElement(_modal.default.Body, null, /*#__PURE__*/_react.default.createElement(_AddResultSearchBar.default, {
          onSearchKeyDown: function _handleSearchKeyDown(event) {
            if (!event.currentTarget.value.trim()) {
              return;
            }

            if (event.key === _constants.KEY_CODES.ENTER) {
              setPage(1);

              _handleRefetch();
            }
          },
          onSearchQueryChange: function _handleSearchQueryChange(event) {
            setSearchQuery(event.target.value);
          },
          onSearchSubmit: _handleRefetch,
          searchQuery: searchQuery
        }), /*#__PURE__*/_react.default.createElement("div", {
          className: "add-result-scroller"
        }, loading && /*#__PURE__*/_react.default.createElement(_layout.default.Sheet, {
          className: "add-result-sheet"
        }, /*#__PURE__*/_react.default.createElement("div", {
          className: "sheet-title"
        }, /*#__PURE__*/_react.default.createElement("div", {
          className: "load-more-container"
        }, /*#__PURE__*/_react.default.createElement(_loadingIndicator.default, null)))), !loading && (function _hasResultsToShow() {
          return !!(resource && resource.total && resource.documents);
        }() ? function _renderSearchResults() {
          var classManagementBar = (0, _classnames.default)('management-bar', selectedIds.length > 0 ? 'management-bar-primary' : 'management-bar-light', 'navbar', 'navbar-expand-md');
          var selectItemsLabel = selectedIds.length > 0 ? (0, _language.getPluralMessage)(Liferay.Language.get('x-item-selected'), Liferay.Language.get('x-items-selected'), selectedIds.length) : Liferay.Language.get('select-items');
          var checked = _getCurrentResultSelectedIds().length === resource.documents.length;
          var indeterminate = selectedIds.length > 0 && _getCurrentResultSelectedIds().length !== resource.documents.length;
          return (/*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_layout.default.Sheet, {
              className: "add-result-sheet"
            }, /*#__PURE__*/_react.default.createElement("div", {
              className: classManagementBar
            }, /*#__PURE__*/_react.default.createElement(_layout.default.ContainerFluid, null, /*#__PURE__*/_react.default.createElement("ul", {
              className: "navbar-nav navbar-nav-expand"
            }, /*#__PURE__*/_react.default.createElement("li", {
              className: "nav-item"
            }, /*#__PURE__*/_react.default.createElement(_form.ClayCheckbox, {
              "aria-label": Liferay.Language.get('select-all'),
              checked: checked,
              indeterminate: indeterminate,
              onChange: _handleAllCheckbox
            })), /*#__PURE__*/_react.default.createElement("li", {
              className: "nav-item"
            }, /*#__PURE__*/_react.default.createElement("span", {
              className: "navbar-text"
            }, selectItemsLabel)), selectedIds.length > 0 && /*#__PURE__*/_react.default.createElement("li", {
              className: "nav-item nav-item-shrink"
            }, /*#__PURE__*/_react.default.createElement(_button.default, {
              className: "btn-outline-borderless",
              displayType: "secondary",
              onClick: _handleClearAllSelected,
              small: true
            }, Liferay.Language.get('clear-all-selected')))))), /*#__PURE__*/_react.default.createElement("ul", {
              className: "list-group",
              "data-testid": "add-result-items"
            }, resource.documents.map(function (result, index) {
              return (/*#__PURE__*/_react.default.createElement(_Item.default.DecoratedComponent, {
                  author: result.author,
                  clicks: result.clicks,
                  date: result.date,
                  description: result.description,
                  hidden: result.hidden,
                  icon: result.icon,
                  id: result.id,
                  index: index,
                  key: result.id,
                  onSelect: _handleSelect,
                  selected: selectedIds.includes(result.id),
                  title: result.title,
                  type: result.type,
                  viewURL: result.viewURL
                })
              );
            }))), /*#__PURE__*/_react.default.createElement("div", {
              className: "add-result-container"
            }, /*#__PURE__*/_react.default.createElement(_paginationBar.ClayPaginationBarWithBasicItems, {
              activeDelta: delta,
              activePage: page,
              deltas: _constants.DELTAS,
              ellipsisBuffer: 1,
              labels: {
                paginationResults: Liferay.Language.get('showing-x-to-x-of-x-entries'),
                perPageItems: Liferay.Language.get('x-items'),
                selectPerPageItems: Liferay.Language.get('x-items')
              },
              onDeltaChange: _handleDeltaChange,
              onPageChange: _handlePageChange,
              spritemap: spritemap,
              totalItems: resource.total
            })))
          );
        }() : function _renderEmptyState() {
          var emptyState = /*#__PURE__*/_react.default.createElement(_ClayEmptyState.default, null);

          if (resourceNotAsked) {
            emptyState = /*#__PURE__*/_react.default.createElement(_ClayEmptyState.default, {
              description: Liferay.Language.get('search-the-engine-to-display-results'),
              displayState: _ClayEmptyState.DISPLAY_STATES.EMPTY,
              title: Liferay.Language.get('search-the-engine')
            });
          } else if (error) {
            emptyState = /*#__PURE__*/_react.default.createElement(_ClayEmptyState.default, {
              actionLabel: Liferay.Language.get('try-again'),
              description: Liferay.Language.get('an-error-has-occurred-and-we-were-unable-to-load-the-results'),
              displayState: _ClayEmptyState.DISPLAY_STATES.EMPTY,
              onClickAction: _handleRefetch,
              title: Liferay.Language.get('unable-to-load-content')
            });
          }

          return (/*#__PURE__*/_react.default.createElement(_layout.default.Sheet, {
              className: "add-result-sheet"
            }, emptyState)
          );
        }()))), /*#__PURE__*/_react.default.createElement(_modal.default.Footer, {
          last: /*#__PURE__*/_react.default.createElement(_button.default.Group, {
            spaced: true
          }, /*#__PURE__*/_react.default.createElement(_button.default, {
            className: "btn-outline-borderless",
            displayType: "secondary",
            onClick: onClose
          }, Liferay.Language.get('cancel')), /*#__PURE__*/_react.default.createElement(_button.default, {
            disabled: selectedIds.length === 0,
            onClick: function _handleSubmit(event) {
              event.preventDefault();
              onAddResultSubmit(selectedIds.map(function (id) {
                return dataMap[id];
              }));
              onClose();
            }
          }, Liferay.Language.get('add')))
        })))
      );
    }

    var _default = AddResultModal;
    exports.default = _default;
    //# sourceMappingURL=AddResultModal.es.js.map
  }
});
//# sourceMappingURL=AddResultModal.es.js.map