Liferay.Loader.define("commerce-frontend-js@3.0.43/components/dataset_display/DatasetDisplay", ['module', 'exports', 'require', '@frontend-taglib-clay$clayui/icon', '@frontend-taglib-clay$clayui/pagination-bar', 'frontend-js-react-web$prop-types', 'frontend-js-react-web$react', '../../utilities/actionItems/bulkActions', '../../utilities/closest', '../../utilities/eventsDefinitions', '../../utilities/index', '../../utilities/modules', '../../utilities/notifications', '../modal/Modal', '../side_panel/SidePanel', './DatasetDisplayContext', './EmptyResultMessage', './management_bar/index', './views/index'], 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 _icon = require("@frontend-taglib-clay$clayui/icon");

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

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

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

    var _bulkActions = require("../../utilities/actionItems/bulkActions");

    var _closest = require("../../utilities/closest");

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

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

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

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

    var _Modal = _interopRequireDefault(require("../modal/Modal"));

    var _SidePanel = _interopRequireDefault(require("../side_panel/SidePanel"));

    var _DatasetDisplayContext = _interopRequireDefault(require("./DatasetDisplayContext"));

    var _EmptyResultMessage = _interopRequireDefault(require("./EmptyResultMessage"));

    var _index2 = _interopRequireDefault(require("./management_bar/index"));

    var _index3 = require("./views/index");

    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 _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 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 _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 DatasetDisplay(props) {
      var wrapperRef = (0, _react.useRef)(null);

      var _useState = (0, _react.useState)(props.views),
          _useState2 = _slicedToArray(_useState, 2),
          views = _useState2[0],
          updateViews = _useState2[1];

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

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

      var _useState7 = (0, _react.useState)(props.sidePanelId || 'support-side-panel-' + (0, _index.getRandomId)()),
          _useState8 = _slicedToArray(_useState7, 1),
          datasetDisplaySupportSidePanelId = _useState8[0];

      var _useState9 = (0, _react.useState)('support-modal-' + (0, _index.getRandomId)()),
          _useState10 = _slicedToArray(_useState9, 1),
          datasetDisplaySupportModalId = _useState10[0];

      var _useState11 = (0, _react.useState)(props.selectedItems || []),
          _useState12 = _slicedToArray(_useState11, 2),
          selectedItemsValue = _useState12[0],
          setSelectedItemsValue = _useState12[1];

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

      var _useState15 = (0, _react.useState)(props.filters),
          _useState16 = _slicedToArray(_useState15, 2),
          filters = _useState16[0],
          updateFilters = _useState16[1];

      var _useState17 = (0, _react.useState)(''),
          _useState18 = _slicedToArray(_useState17, 2),
          searchParam = _useState18[0],
          updateSearchParam = _useState18[1];

      var _useState19 = (0, _react.useState)(props.sorting),
          _useState20 = _slicedToArray(_useState19, 2),
          sorting = _useState20[0],
          updateSorting = _useState20[1];

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

      var _useState23 = (0, _react.useState)(1),
          _useState24 = _slicedToArray(_useState23, 2),
          pageNumber = _useState24[0],
          setPageNumber = _useState24[1];

      var _useState25 = (0, _react.useState)(props.pagination.initialDelta || props.pagination.deltas[0].label),
          _useState26 = _slicedToArray(_useState25, 2),
          delta = _useState26[0],
          setDelta = _useState26[1];

      var _useState27 = (0, _react.useState)(0),
          _useState28 = _slicedToArray(_useState27, 2),
          totalItems = _useState28[0],
          setTotalItems = _useState28[1];

      var _useState29 = (0, _react.useState)(props.activeView || 0),
          _useState30 = _slicedToArray(_useState29, 2),
          activeView = _useState30[0],
          setActiveView = _useState30[1];

      var _views$activeView = views[activeView],
          CurrentViewComponent = _views$activeView.component,
          contentRenderer = _views$activeView.contentRenderer,
          currentViewModuleUrl = _views$activeView.contentRendererModuleUrl,
          currentViewProps = _objectWithoutProperties(_views$activeView, ["component", "contentRenderer", "contentRendererModuleUrl"]);

      var selectable = props.bulkActions && !!props.bulkActions.length && props.selectedItemsKey;
      (0, _react.useEffect)(function () {
        if (!CurrentViewComponent && (currentViewModuleUrl || contentRenderer)) {
          setLoading(true);
          (contentRenderer ? (0, _index3.getViewById)(contentRenderer) : (0, _modules.getJsModule)(currentViewModuleUrl)).then(function (component) {
            updateViews(function (views) {
              return views.map(function (view, i) {
                return i === activeView ? _objectSpread(_objectSpread({}, view), {}, {
                  component: component
                }) : view;
              });
            });
            setLoading(false);
          }).catch(function (err) {
            (0, _notifications.showNotification)(Liferay.Language.get('unexpected-error'), 'danger');
            setLoading(false);
            throw new Error("Requested module: ".concat(currentViewModuleUrl, " not available"), err);
          });
        }
      }, [activeView, contentRenderer, views, currentViewModuleUrl, CurrentViewComponent, setLoading]);
      var formRef = (0, _react.useRef)(null);

      function updateDatasetItems(dataSetData) {
        setTotalItems(dataSetData.totalItems || dataSetData.totalCount || 0);
        updateItems(dataSetData.items);
      }

      function getData(apiUrl, currentUrl, delta, filters, pageNumber, searchParam, sorting) {
        var successNotification = arguments.length > 7 && arguments[7] !== undefined ? arguments[7] : {};
        setLoading(true);
        return (0, _index.loadData)(apiUrl, currentUrl, delta, filters, pageNumber, searchParam, sorting).then(updateDatasetItems).then(function () {
          var message = successNotification.message,
              showSuccessNotification = successNotification.showSuccessNotification;

          if (showSuccessNotification) {
            var notificationMessage = message || Liferay.Language.get('table-data-updated');
            (0, _notifications.showNotification)(notificationMessage, 'success');
          }

          setLoading(false);
          Liferay.fire(_eventsDefinitions.DATASET_DISPLAY_UPDATED, {
            id: props.id
          });
        }).catch(function (e) {
          console.error(e);
          setLoading(false);
          (0, _notifications.showNotification)(Liferay.Language.get('unexpected-error'), 'danger');
        });
      } // eslint-disable-next-line react-hooks/exhaustive-deps


      var refreshData = function refreshData(successNotification) {
        return getData(props.apiUrl, props.currentUrl, delta, filters.filter(function (e) {
          return !!e.value;
        }), pageNumber, searchParam, sorting, successNotification);
      };

      (0, _react.useEffect)(function () {
        if (props.apiUrl) {
          getData(props.apiUrl, props.currentUrl, delta, filters.filter(function (e) {
            return !!e.value;
          }), pageNumber, searchParam, sorting, false);
        } // eslint-disable-next-line react-hooks/exhaustive-deps
      }, [props.apiUrl, props.currentUrl, filters, searchParam, delta, pageNumber, sorting, refreshData]);
      (0, _react.useEffect)(function () {
        var apiUrl = props.apiUrl,
            _props$items = props.items,
            injectedItems = _props$items === void 0 ? [] : _props$items,
            itemsAreInjected = !apiUrl && !!injectedItems && injectedItems.length !== items.length;

        if (itemsAreInjected) {
          updateDatasetItems({
            items: props.items
          });
        }
      }, [items, props, props.apiUrl, props.items]);

      function selectItems(val) {
        if (Array.isArray(val)) {
          return setSelectedItemsValue(val);
        }

        if (props.selectionType === 'single') {
          return setSelectedItemsValue([val]);
        }

        var itemAdded = selectedItemsValue.find(function (item) {
          return item === val;
        });

        if (itemAdded) {
          setSelectedItemsValue(selectedItemsValue.filter(function (el) {
            return el !== val;
          }));
        } else {
          setSelectedItemsValue(selectedItemsValue.concat(val));
        }
      }

      (0, _react.useEffect)(function () {
        if (wrapperRef.current) {
          var form = (0, _closest.closest)(wrapperRef.current, 'form');

          if (form && form.getAttribute('data-senna-off') === null) {
            form.setAttribute('data-senna-off', true);
          }
        }
      }, [wrapperRef]);
      (0, _react.useEffect)(function () {
        function handleRefreshFromTheOutside(e) {
          if (e.id === props.id) {
            refreshData();
          }
        }

        function handleCloseSidePanel(_e) {
          setHighlightedItemsValue([]);
        }

        if (props.nestedItemsReferenceKey && !props.nestedItemsKey || !props.nestedItemsReferenceKey && props.nestedItemsKey) {
          throw new Error('"nestedItemsKey" and "nestedItemsReferenceKey" params are both mandatory to manage nested items');
        }

        Liferay.on(_eventsDefinitions.SIDE_PANEL_CLOSED, handleCloseSidePanel);
        Liferay.on(_eventsDefinitions.UPDATE_DATASET_DISPLAY, handleRefreshFromTheOutside);
        return function () {
          Liferay.detach(_eventsDefinitions.SIDE_PANEL_CLOSED, handleCloseSidePanel);
          Liferay.detach(_eventsDefinitions.UPDATE_DATASET_DISPLAY, handleRefreshFromTheOutside);
        }; // eslint-disable-next-line react-hooks/exhaustive-deps
      }, [props.id]);
      var managementBar = props.showManagementBar ? /*#__PURE__*/_react.default.createElement("div", {
        className: "dataset-display-management-bar-wrapper"
      }, /*#__PURE__*/_react.default.createElement(_index2.default, {
        activeView: activeView,
        bulkActions: props.bulkActions,
        creationMenuItems: props.creationMenuItems,
        filters: filters,
        fluid: props.style === 'fluid',
        onFiltersChange: updateFilters,
        selectAllItems: function selectAllItems() {
          return selectItems(items.map(function (item) {
            return item[props.selectedItemsKey];
          }));
        },
        selectable: selectable,
        selectedItemsKey: props.selectedItemsKey,
        selectedItemsValue: selectedItemsValue,
        selectionType: props.selectionType,
        setActiveView: setActiveView,
        showSearch: props.showSearch,
        sidePanelId: datasetDisplaySupportSidePanelId,
        totalItemsCount: items ? items.length : 0,
        views: props.views
      })) : null;
      var view = !loading && CurrentViewComponent ? /*#__PURE__*/_react.default.createElement("div", {
        className: "dataset-display-content-wrapper"
      }, /*#__PURE__*/_react.default.createElement("input", {
        hidden: true,
        name: "".concat(props.namespace || props.id + '_').concat(props.selectedItemsKey),
        readOnly: true,
        value: selectedItemsValue.join(',')
      }), items && items.length || props.overrideEmptyResultView ? /*#__PURE__*/_react.default.createElement(CurrentViewComponent, _extends({
        datasetDisplayContext: _DatasetDisplayContext.default,
        items: items,
        itemsActions: props.itemsActions,
        style: props.style
      }, currentViewProps)) : null, items && items.length === 0 && /*#__PURE__*/_react.default.createElement(_EmptyResultMessage.default, null)) : /*#__PURE__*/_react.default.createElement("span", {
        "aria-hidden": "true",
        className: "loading-animation my-7"
      });
      var wrappedView = props.formId ? view : /*#__PURE__*/_react.default.createElement("form", {
        ref: formRef
      }, view);
      var pagination = props.showPagination && props.pagination && items && items.length ? /*#__PURE__*/_react.default.createElement("div", {
        className: "dataset-display-pagination-wrapper"
      }, /*#__PURE__*/_react.default.createElement(_paginationBar.ClayPaginationBarWithBasicItems, {
        activeDelta: delta,
        activePage: pageNumber,
        className: "mb-2",
        deltas: props.pagination.deltas,
        ellipsisBuffer: 3,
        labels: {
          paginationResults: Liferay.Language.get('showing-x-to-x-of-x-entries'),
          perPageItems: Liferay.Language.get('x-items-per-page'),
          selectPerPageItems: Liferay.Language.get('x-items-per-page')
        },
        onDeltaChange: function onDeltaChange(deltaVal) {
          setPageNumber(1);
          setDelta(deltaVal);
        },
        onPageChange: setPageNumber,
        spritemap: props.spritemap,
        totalItems: totalItems
      })) : null;

      function handleCompletedAction() {
        var e = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
        refreshData();
        Liferay.fire(_eventsDefinitions.DATASET_ACTION_PERFORMED, {
          id: props.id
        });
        setActionLoading(false);

        if (e) {
          (0, _notifications.showNotification)(e);
        }
      }

      function handleFailedAction(e) {
        (0, _notifications.showErrorNotification)(Liferay.Language.get('unexpected-error'));
        setActionLoading(false);
        throw new Error(e);
      }

      return (/*#__PURE__*/_react.default.createElement(_DatasetDisplayContext.default.Provider, {
          value: {
            actionLoading: actionLoading,
            executeAsyncBulkAction: function executeAsyncBulkAction(url, method, bodyKeys) {
              var bodyContent = items.reduce(function (foundData, item) {
                if (selectedItemsValue.includes(item[props.selectedItemsKey])) {
                  return [].concat(_toConsumableArray(foundData), [bodyKeys.reduce(function (keys, key) {
                    return _objectSpread(_objectSpread({}, keys), {}, _defineProperty({}, key, item[key]));
                  }, {})]);
                }

                return foundData;
              }, []);
              setActionLoading(true);
              return (0, _index.executeAsyncAction)(url, method, JSON.stringify(bodyContent)).then(function (response) {
                return response.json();
              }).then(function (jsonResponse) {
                return (0, _bulkActions.listenToBulkActionStatus)(jsonResponse.id, props.batchTasksStatusApiUrl);
              }).then(handleCompletedAction).catch(handleFailedAction);
            },
            executeAsyncItemAction: function executeAsyncItemAction(url, method) {
              setActionLoading(true);
              return (0, _index.executeAsyncAction)(url, method).then(function (_) {
                return handleCompletedAction();
              }).catch(handleFailedAction);
            },
            formId: props.formId,
            formRef: formRef,
            highlightItems: function highlightItems() {
              var val = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];

              if (Array.isArray(val)) {
                return setHighlightedItemsValue(val);
              }

              var itemAdded = highlightedItemsValue.find(function (item) {
                return item === val;
              });

              if (!itemAdded) {
                setHighlightedItemsValue(highlightedItemsValue.concat(val));
              }
            },
            highlightedItemsValue: highlightedItemsValue,
            itemsActions: props.itemsActions,
            loadData: refreshData,
            modalId: datasetDisplaySupportModalId,
            namespace: props.namespace,
            nestedItemsKey: props.nestedItemsKey,
            nestedItemsReferenceKey: props.nestedItemsReferenceKey,
            openModal: function openModal(config) {
              return Liferay.fire(_eventsDefinitions.OPEN_MODAL, _objectSpread({
                id: datasetDisplaySupportModalId,
                onSubmit: refreshData
              }, config));
            },
            openSidePanel: function openSidePanel(config) {
              return Liferay.fire(_eventsDefinitions.OPEN_SIDE_PANEL, _objectSpread({
                id: datasetDisplaySupportSidePanelId,
                onSubmit: refreshData
              }, config));
            },
            searchParam: searchParam,
            selectItems: selectItems,
            selectable: selectable,
            selectedItemsKey: props.selectedItemsKey,
            selectedItemsValue: selectedItemsValue,
            selectionType: props.selectionType,
            setPageNumber: setPageNumber,
            sidePanelId: datasetDisplaySupportSidePanelId,
            sorting: sorting,
            style: props.style,
            updateDatasetItems: updateDatasetItems,
            updateSearchParam: updateSearchParam,
            updateSorting: updateSorting
          }
        }, /*#__PURE__*/_react.default.createElement(_icon.ClayIconSpriteContext.Provider, {
          value: props.spritemap
        }, /*#__PURE__*/_react.default.createElement(_Modal.default, {
          id: datasetDisplaySupportModalId,
          onClose: refreshData
        }), !props.sidePanelId && /*#__PURE__*/_react.default.createElement(_SidePanel.default, {
          id: datasetDisplaySupportSidePanelId,
          onAfterSubmit: refreshData
        }), /*#__PURE__*/_react.default.createElement("div", {
          className: "dataset-display-wrapper",
          ref: wrapperRef
        }, props.style === 'default' && /*#__PURE__*/_react.default.createElement("div", {
          className: "dataset-display dataset-display-inline"
        }, managementBar, wrappedView, pagination), props.style === 'stacked' && /*#__PURE__*/_react.default.createElement("div", {
          className: "dataset-display dataset-display-stacked"
        }, managementBar, wrappedView, pagination), props.style === 'fluid' && /*#__PURE__*/_react.default.createElement("div", {
          className: "dataset-display dataset-display-fluid"
        }, managementBar, /*#__PURE__*/_react.default.createElement("div", {
          className: "container mt-3"
        }, wrappedView, pagination)))))
      );
    }

    DatasetDisplay.defaultProps = {
      bulkActions: [],
      filters: [],
      items: null,
      itemsActions: null,
      pagination: {
        initialDelta: 10
      },
      selectedItemsKey: 'id',
      selectionType: 'multiple',
      showManagementBar: true,
      showPagination: true,
      showSearch: true,
      sorting: [],
      style: 'default'
    };
    var _default = DatasetDisplay;
    exports.default = _default;
    //# sourceMappingURL=DatasetDisplay.js.map
  }
});
//# sourceMappingURL=DatasetDisplay.js.map