Liferay.Loader.define("frontend-taglib-clay@6.6.20/data_set_display/DataSetDisplay", ['module', 'exports', 'require', '@frontend-taglib-clay$clayui/pagination-bar', 'frontend-js-react-web', 'frontend-js-web', 'frontend-taglib-clay$prop-types', 'frontend-js-react-web$react', './AppContext', './DataSetDisplayContext', './EmptyResultMessage', './actions/updateViewComponent', './management_bar/index', './modal/Modal', './side_panel/SidePanel', './utilities/eventsDefinitions', './utilities/index', './utilities/logError', './utilities/modules', './views/ViewsContext', './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 _paginationBar = require("@frontend-taglib-clay$clayui/pagination-bar");

    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 _AppContext = require("./AppContext");

    var _DataSetDisplayContext = _interopRequireDefault(require("./DataSetDisplayContext"));

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

    var _updateViewComponent = require("./actions/updateViewComponent");

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

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

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

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

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

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

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

    var _ViewsContext = _interopRequireDefault(require("./views/ViewsContext"));

    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 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 _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 _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 _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(_ref) {
      var _items$length, _items$length2;

      var actionParameterName = _ref.actionParameterName,
          bulkActions = _ref.bulkActions,
          creationMenu = _ref.creationMenu,
          currentURL = _ref.currentURL,
          filtersProp = _ref.filters,
          formId = _ref.formId,
          id = _ref.id,
          itemsProp = _ref.items,
          itemsActions = _ref.itemsActions,
          namespace = _ref.namespace,
          nestedItemsKey = _ref.nestedItemsKey,
          nestedItemsReferenceKey = _ref.nestedItemsReferenceKey,
          overrideEmptyResultView = _ref.overrideEmptyResultView,
          pagination = _ref.pagination,
          selectedItems = _ref.selectedItems,
          selectedItemsKey = _ref.selectedItemsKey,
          selectionType = _ref.selectionType,
          showManagementBar = _ref.showManagementBar,
          showPagination = _ref.showPagination,
          showSearch = _ref.showSearch,
          sidePanelId = _ref.sidePanelId,
          sortingProp = _ref.sorting,
          style = _ref.style;
      var wrapperRef = (0, _react.useRef)(null);

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

      var _useState3 = (0, _react.useState)(sidePanelId || 'support-side-panel-' + (0, _index2.getRandomId)()),
          _useState4 = _slicedToArray(_useState3, 1),
          dataSetDisplaySupportSidePanelId = _useState4[0];

      var _useState5 = (0, _react.useState)('support-modal-' + (0, _index2.getRandomId)()),
          _useState6 = _slicedToArray(_useState5, 1),
          dataSetDisplaySupportModalId = _useState6[0];

      var _useState7 = (0, _react.useState)(selectedItems || []),
          _useState8 = _slicedToArray(_useState7, 2),
          selectedItemsValue = _useState8[0],
          setSelectedItemsValue = _useState8[1];

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

      var _useState11 = (0, _react.useState)(filtersProp),
          _useState12 = _slicedToArray(_useState11, 2),
          filters = _useState12[0],
          updateFilters = _useState12[1];

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

      var _useState15 = (0, _react.useState)(sortingProp),
          _useState16 = _slicedToArray(_useState15, 2),
          sorting = _useState16[0],
          updateSorting = _useState16[1];

      var _useState17 = (0, _react.useState)(itemsProp),
          _useState18 = _slicedToArray(_useState17, 2),
          items = _useState18[0],
          updateItems = _useState18[1];

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

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

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

      var _useContext = (0, _react.useContext)(_ViewsContext.default),
          _useContext2 = _slicedToArray(_useContext, 2),
          _useContext2$ = _useContext2[0],
          activeView = _useContext2$.activeView,
          views = _useContext2$.views,
          dispatch = _useContext2[1];

      var CurrentViewComponent = activeView.component,
          contentRenderer = activeView.contentRenderer,
          contentRendererModuleURL = activeView.contentRendererModuleURL,
          activeViewName = activeView.name,
          currentViewProps = _objectWithoutProperties(activeView, ["component", "contentRenderer", "contentRendererModuleURL", "name"]);

      var selectable = !!((bulkActions === null || bulkActions === void 0 ? void 0 : bulkActions.length) && selectedItemsKey);

      var _useContext3 = (0, _react.useContext)(_AppContext.AppContext),
          apiURL = _useContext3.apiURL;

      var requestData = (0, _react.useCallback)(function () {
        var activeFiltersOdataStrings = filters.reduce(function (activeFilters, filter) {
          return filter.odataFilterString ? [].concat(_toConsumableArray(activeFilters), [filter.odataFilterString]) : activeFilters;
        }, []);
        return (0, _index2.loadData)(apiURL, currentURL, activeFiltersOdataStrings, searchParam, delta, pageNumber, sorting).catch(function (error) {
          (0, _logError.logError)(error);
          (0, _frontendJsWeb.openToast)({
            message: Liferay.Language.get('unexpected-error'),
            type: 'danger'
          });
          throw error;
        });
      }, [apiURL, currentURL, delta, filters, pageNumber, searchParam, sorting]);
      var requestComponent = (0, _react.useCallback)(function () {
        if (!CurrentViewComponent && (contentRendererModuleURL || contentRenderer)) {
          return (contentRenderer ? (0, _index3.getViewContentRenderer)(contentRenderer) : (0, _modules.getJsModule)(contentRendererModuleURL)).catch(function (error) {
            (0, _logError.logError)("Requested module: ".concat(contentRendererModuleURL, " not available"), error);
            (0, _frontendJsWeb.openToast)({
              message: Liferay.Language.get('unexpected-error'),
              type: 'danger'
            });
            throw error;
          });
        }

        return Promise.resolve(CurrentViewComponent);
      }, [contentRenderer, contentRendererModuleURL, CurrentViewComponent]);
      var isMounted = (0, _frontendJsReactWeb.useIsMounted)();

      function updateDataSetItems(dataSetData) {
        setTotal(dataSetData.totalCount);
        updateItems(dataSetData.items);
      }

      var pendingPromise = (0, _react.useRef)(null);
      (0, _react.useEffect)(function () {
        var promise = Promise.race([(0, _index2.delay)(200).then(function () {
          if (isMounted() && pendingPromise.current === promise) {
            setLoading(true);
          }
        }), Promise.all([requestComponent(), requestData()]).then(function (_ref2) {
          var _ref3 = _slicedToArray(_ref2, 2),
              component = _ref3[0],
              data = _ref3[1];

          if (isMounted() && pendingPromise.current === promise) {
            pendingPromise.current = null;
            dispatch((0, _updateViewComponent.updateViewComponent)(activeViewName, component));
            setLoading(false);
            updateDataSetItems(data);
          }
        })]);
        pendingPromise.current = promise;
      }, [activeViewName, dispatch, isMounted, requestComponent, requestData, setLoading]);
      (0, _react.useEffect)(function () {
        var itemsAreInjected = !apiURL && (itemsProp === null || itemsProp === void 0 ? void 0 : itemsProp.length) !== items.length;

        if (itemsAreInjected) {
          updateDataSetItems({
            items: itemsProp
          });
        }
      }, [items, apiURL, itemsProp]);

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

        if (selectionType === 'single') {
          return setSelectedItemsValue([value]);
        }

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

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

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

          if ((form === null || form === void 0 ? void 0 : form.getAttribute('data-senna-off')) === null) {
            form.setAttribute('data-senna-off', true);
          }
        }
      }, [wrapperRef]);

      function refreshData(successNotification) {
        setLoading(true);
        return requestData().then(function (data) {
          if (successNotification === null || successNotification === void 0 ? void 0 : successNotification.showSuccessNotification) {
            (0, _frontendJsWeb.openToast)({
              message: successNotification.message || Liferay.Language.get('table-data-updated'),
              type: 'success'
            });
          }

          if (isMounted()) {
            setLoading(false);
            updateDataSetItems(data);
            Liferay.fire(_eventsDefinitions.DATASET_DISPLAY_UPDATED, {
              id: id
            });
          }

          return data;
        }).catch(function (error) {
          (0, _logError.logError)(error);
          setLoading(false);
          throw error;
        });
      }

      (0, _react.useEffect)(function () {
        function handleRefreshFromTheOutside(event) {
          if (event.id === id) {
            refreshData();
          }
        }

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

        if (nestedItemsReferenceKey && !nestedItemsKey || !nestedItemsReferenceKey && nestedItemsKey) {
          (0, _logError.logError)('"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
      }, [id]);
      var managementBar = showManagementBar ? /*#__PURE__*/_react.default.createElement("div", {
        className: "data-set-display-management-bar-wrapper"
      }, /*#__PURE__*/_react.default.createElement(_index.default, {
        bulkActions: bulkActions,
        creationMenu: creationMenu,
        filters: filters,
        fluid: style === 'fluid',
        onFiltersChange: updateFilters,
        selectAllItems: function selectAllItems() {
          return selectItems(items.map(function (item) {
            return item[selectedItemsKey];
          }));
        },
        selectedItemsKey: selectedItemsKey,
        selectedItemsValue: selectedItemsValue,
        selectionType: selectionType,
        showSearch: showSearch,
        sidePanelId: dataSetDisplaySupportSidePanelId,
        total: (_items$length = items === null || items === void 0 ? void 0 : items.length) !== null && _items$length !== void 0 ? _items$length : 0,
        views: views
      })) : null;
      var view = !loading && CurrentViewComponent ? /*#__PURE__*/_react.default.createElement("div", {
        className: "data-set-display-content-wrapper"
      }, /*#__PURE__*/_react.default.createElement("input", {
        hidden: true,
        name: "".concat(namespace || id + '_').concat(actionParameterName || selectedItemsKey),
        readOnly: true,
        value: selectedItemsValue.join(',')
      }), ((_items$length2 = items === null || items === void 0 ? void 0 : items.length) !== null && _items$length2 !== void 0 ? _items$length2 : 0) || overrideEmptyResultView ? /*#__PURE__*/_react.default.createElement(CurrentViewComponent, _extends({
        dataSetDisplayContext: _DataSetDisplayContext.default,
        items: items,
        itemsActions: itemsActions,
        style: style
      }, currentViewProps)) : /*#__PURE__*/_react.default.createElement(_EmptyResultMessage.default, null)) : /*#__PURE__*/_react.default.createElement("span", {
        "aria-hidden": "true",
        className: "loading-animation my-7"
      });
      var formRef = (0, _react.useRef)(null);
      var wrappedView = formId ? view : /*#__PURE__*/_react.default.createElement("form", {
        ref: formRef
      }, view);
      var paginationComponent = showPagination && pagination && (items === null || items === void 0 ? void 0 : items.length) ? /*#__PURE__*/_react.default.createElement("div", {
        className: "data-set-display-pagination-wrapper"
      }, /*#__PURE__*/_react.default.createElement(_paginationBar.ClayPaginationBarWithBasicItems, {
        activeDelta: delta,
        activePage: pageNumber,
        deltas: pagination.deltas,
        ellipsisBuffer: 3,
        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: function onDeltaChange(deltaVal) {
          setPageNumber(1);
          setDelta(deltaVal);
        },
        onPageChange: setPageNumber,
        totalItems: total
      })) : null;

      return (/*#__PURE__*/_react.default.createElement(_DataSetDisplayContext.default.Provider, {
          value: {
            actionParameterName: actionParameterName,
            executeAsyncItemAction: function executeAsyncItemAction(url, method) {
              return (0, _index2.executeAsyncAction)(url, method).then(function (_) {
                return (0, _index2.delay)(500).then(function () {
                  if (isMounted()) {
                    Liferay.fire(_eventsDefinitions.DATASET_ACTION_PERFORMED, {
                      id: id
                    });
                    return refreshData();
                  }
                });
              }).catch(function (error) {
                (0, _logError.logError)(error);
                (0, _frontendJsWeb.openToast)({
                  message: Liferay.Language.get('unexpected-error'),
                  type: 'danger'
                });
              });
            },
            formId: formId,
            formRef: formRef,
            highlightItems: function highlightItems() {
              var value = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];

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

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

              if (!itemAdded) {
                setHighlightedItemsValue(highlightedItemsValue.concat(value));
              }
            },
            highlightedItemsValue: highlightedItemsValue,
            id: id,
            itemsActions: itemsActions,
            loadData: refreshData,
            modalId: dataSetDisplaySupportModalId,
            namespace: namespace,
            nestedItemsKey: nestedItemsKey,
            nestedItemsReferenceKey: 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: selectedItemsKey,
            selectedItemsValue: selectedItemsValue,
            selectionType: selectionType,
            sidePanelId: dataSetDisplaySupportSidePanelId,
            sorting: sorting,
            style: style,
            updateDataSetItems: updateDataSetItems,
            updateSearchParam: updateSearchParam,
            updateSorting: updateSorting
          }
        }, /*#__PURE__*/_react.default.createElement(_Modal.default, {
          id: dataSetDisplaySupportModalId,
          onClose: refreshData
        }), !sidePanelId && /*#__PURE__*/_react.default.createElement(_SidePanel.default, {
          id: dataSetDisplaySupportSidePanelId,
          onAfterSubmit: refreshData
        }), /*#__PURE__*/_react.default.createElement("div", {
          className: "data-set-display-wrapper",
          ref: wrapperRef
        }, style === 'default' && /*#__PURE__*/_react.default.createElement("div", {
          className: "data-set-display data-set-display-inline"
        }, managementBar, wrappedView, paginationComponent), style === 'stacked' && /*#__PURE__*/_react.default.createElement("div", {
          className: "data-set-display data-set-display-stacked"
        }, managementBar, wrappedView, paginationComponent), style === 'fluid' && /*#__PURE__*/_react.default.createElement("div", {
          className: "data-set-display data-set-display-fluid"
        }, managementBar, /*#__PURE__*/_react.default.createElement("div", {
          className: "container-fluid container-xl mt-3"
        }, wrappedView, paginationComponent))))
      );
    }

    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