Liferay.Loader.define("app-builder-web@1.0.58/js/pages/custom-object/ListCustomObjects.es", ['module', 'exports', 'require', 'frontend-js-web', 'frontend-js-react-web$react', '../../AppContext.es', '../../components/button/Button.es', '../../hooks/index.es', '../../hooks/useQuery.es', '../../utils/clickOutside.es', '../../utils/client.es', '../../utils/toast.es', '../../utils/utils.es', '../object/ListObjects.es', './CustomObjectPopover.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 _frontendJsWeb = require("frontend-js-web");

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

    var _AppContext = require("../../AppContext.es");

    var _Button = _interopRequireDefault(require("../../components/button/Button.es"));

    var _index = require("../../hooks/index.es");

    var _useQuery3 = _interopRequireDefault(require("../../hooks/useQuery.es"));

    var _clickOutside = _interopRequireDefault(require("../../utils/clickOutside.es"));

    var _client = require("../../utils/client.es");

    var _toast = require("../../utils/toast.es");

    var _utils = require("../../utils/utils.es");

    var _ListObjects = _interopRequireDefault(require("../object/ListObjects.es"));

    var _CustomObjectPopover = _interopRequireDefault(require("./CustomObjectPopover.es"));

    function _interopRequireDefault(obj) {
      return obj && obj.__esModule ? obj : { "default": obj };
    }

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

    var _default = function _default(_ref) {
      var history = _ref.history;

      var _useContext = (0, _react.useContext)(_AppContext.AppContext),
          basePortletURL = _useContext.basePortletURL,
          baseResourceURL = _useContext.baseResourceURL,
          namespace = _useContext.namespace;

      var _useState = (0, _react.useState)(null),
          _useState2 = _slicedToArray(_useState, 2),
          editMode = _useState2[0],
          setEditMode = _useState2[1];

      var addButtonRef = (0, _react.useRef)();
      var defaultLanguageId = Liferay.ThemeDisplay.getDefaultLanguageId();
      var emptyStateButtonRef = (0, _react.useRef)();
      var popoverRef = (0, _react.useRef)();

      var _useState3 = (0, _react.useState)(addButtonRef.current),
          _useState4 = _slicedToArray(_useState3, 2),
          alignElement = _useState4[0],
          setAlignElement = _useState4[1];

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

      var _useQuery = (0, _useQuery3["default"])(history),
          _useQuery2 = _slicedToArray(_useQuery, 1),
          showCustomObjectPopover = _useQuery2[0].showCustomObjectPopover;

      var onCancelRenameAction = function onCancelRenameAction() {
        return Promise.resolve(setEditMode(null));
      };

      var onRenameAction = function onRenameAction(_ref4, value, refetch) {
        var originalItem = _ref4.originalItem;
        (0, _client.updateItem)({
          endpoint: "/o/data-engine/v2.0/data-definitions/".concat(originalItem.id),
          item: _objectSpread({}, originalItem, {
            name: _defineProperty({}, originalItem.defaultLanguageId, (0, _utils.getValidName)(Liferay.Language.get('untitled-custom-object'), value))
          })
        }).then(refetch).then(onCancelRenameAction).then(function () {
          return (0, _toast.successToast)(Liferay.Language.get('the-object-was-renamed-successfully'));
        })["catch"](function (_ref5) {
          var errorMessage = _ref5.errorMessage;
          (0, _toast.errorToast)(errorMessage);
        });
      };

      var onClickAddButton = function onClickAddButton(_ref6) {
        var currentTarget = _ref6.currentTarget;
        setAlignElement(currentTarget);

        if (isPopoverVisible && alignElement !== currentTarget) {
          return;
        }

        setPopoverVisible(!isPopoverVisible);
      };

      (0, _react.useEffect)(function () {
        var handler = function handler(_ref9) {
          var target = _ref9.target;
          var isOutside = (0, _clickOutside["default"])(target, addButtonRef.current, emptyStateButtonRef.current, popoverRef.current);

          if (isOutside) {
            setPopoverVisible(false);
          }
        };

        window.addEventListener('click', handler);
        return function () {
          return window.removeEventListener('click', handler);
        };
      }, [addButtonRef, emptyStateButtonRef, popoverRef]);
      (0, _react.useEffect)(function () {
        if (addButtonRef.current && showCustomObjectPopover) {
          setAlignElement(addButtonRef.current);
          setPopoverVisible(true);
        }
      }, [addButtonRef, showCustomObjectPopover]);
      (0, _index.useKeyDown)(function () {
        if (isPopoverVisible) {
          setPopoverVisible(false);
        }
      }, 27);
      return _react["default"].createElement(_react["default"].Fragment, null, _react["default"].createElement(_ListObjects["default"], {
        history: history,
        listViewProps: {
          actions: [{
            name: 'divider'
          }, {
            action: function renameAction(item, refetch) {
              var id = item.id;
              return new Promise(function (resolve) {
                return resolve(setEditMode({
                  id: id,
                  onCancel: onCancelRenameAction,
                  onSave: function onSave(value) {
                    return onRenameAction(item, value, refetch);
                  }
                }));
              });
            },
            name: Liferay.Language.get('rename')
          }, {
            action: function confirmDelete(_ref2) {
              var dataDefinitionId = _ref2.id;
              return new Promise(function (resolve, reject) {
                var confirmed = confirm(Liferay.Language.get('are-you-sure-you-want-to-delete-this'));

                if (confirmed) {
                  (0, _frontendJsWeb.fetch)((0, _frontendJsWeb.createResourceURL)(baseResourceURL, {
                    p_p_resource_id: '/objects/delete_data_definition'
                  }), {
                    body: new URLSearchParams(Liferay.Util.ns(namespace, {
                      dataDefinitionId: dataDefinitionId
                    })),
                    method: 'POST'
                  }).then(_client.parseResponse).then(function () {
                    return resolve(true);
                  }).then(function () {
                    return (0, _toast.successToast)(Liferay.Language.get('the-item-was-deleted-successfully'));
                  })["catch"](function (_ref3) {
                    var errorMessage = _ref3.errorMessage;
                    (0, _toast.errorToast)(errorMessage);
                    reject(true);
                  });
                } else {
                  resolve(false);
                }
              });
            },
            name: Liferay.Language.get('delete')
          }],
          addButton: function addButton() {
            return _react["default"].createElement("div", {
              ref: addButtonRef
            }, _react["default"].createElement(_Button["default"], {
              className: "nav-btn nav-btn-monospaced",
              onClick: onClickAddButton,
              symbol: "plus",
              tooltip: Liferay.Language.get('new-custom-object')
            }));
          },
          editMode: editMode,
          emptyState: {
            button: function button() {
              return _react["default"].createElement(_Button["default"], {
                displayType: "secondary",
                onClick: onClickAddButton,
                ref: emptyStateButtonRef
              }, Liferay.Language.get('new-custom-object'));
            },
            description: Liferay.Language.get('custom-objects-define-the-types-of-data-your-business-application-needs'),
            title: Liferay.Language.get('there-are-no-custom-objects-yet')
          },
          endpoint: "/o/data-engine/v2.0/data-definitions/by-content-type/app-builder"
        },
        objectType: "custom-object"
      }), _react["default"].createElement(_CustomObjectPopover["default"], {
        alignElement: alignElement,
        onCancel: function onCancel() {
          return setPopoverVisible(false);
        },
        onSubmit: function onSubmit(_ref7) {
          var isAddFormView = _ref7.isAddFormView,
              name = _ref7.name;

          return (0, _client.addItem)("/o/data-engine/v2.0/data-definitions/by-content-type/app-builder", {
            availableLanguageIds: [defaultLanguageId],
            dataDefinitionFields: [],
            defaultLanguageId: defaultLanguageId,
            name: _defineProperty({}, defaultLanguageId, (0, _utils.getValidName)(Liferay.Language.get('untitled-custom-object'), name))
          }).then(function (_ref8) {
            var id = _ref8.id;

            if (isAddFormView) {
              Liferay.Util.navigate(Liferay.Util.PortletURL.createRenderURL(basePortletURL, {
                dataDefinitionId: id,
                mvcRenderCommandName: '/edit_form_view',
                newCustomObject: true
              }));
            } else {
              (0, _toast.successToast)(Liferay.Language.get('the-object-was-created-successfully'));
              history.push("/custom-object/".concat(id, "/form-views/"));
            }
          })["catch"](function (error) {
            (0, _toast.errorToast)(error.message);
            return Promise.reject();
          });
        },
        ref: popoverRef,
        visible: isPopoverVisible
      }));
    };

    exports["default"] = _default;
    //# sourceMappingURL=ListCustomObjects.es.js.map
  }
});
//# sourceMappingURL=ListCustomObjects.es.js.map