Liferay.Loader.define("dynamic-data-mapping-form-web@3.0.87/admin/js/main.es", ['module', 'exports', 'require', 'frontend-taglib-clay$clay-modal', 'dynamic-data-mapping-form-builder/js/components/FormBuilder/FormBuilder.es', 'dynamic-data-mapping-form-builder/js/components/FormBuilder/withActionableFields.es', 'dynamic-data-mapping-form-builder/js/components/FormBuilder/withClickableFields.es', 'dynamic-data-mapping-form-builder/js/components/FormBuilder/withEditablePageHeader.es', 'dynamic-data-mapping-form-builder/js/components/FormBuilder/withMoveableFields.es', 'dynamic-data-mapping-form-builder/js/components/FormBuilder/withMultiplePages.es', 'dynamic-data-mapping-form-builder/js/components/FormBuilder/withResizeableColumns.es', 'dynamic-data-mapping-form-builder/js/components/LayoutProvider/LayoutProvider.es', 'dynamic-data-mapping-form-builder/js/components/RuleBuilder/RuleBuilder.es', 'dynamic-data-mapping-form-builder/js/components/Sidebar/Sidebar.es', 'dynamic-data-mapping-form-builder/js/util/config.es', 'dynamic-data-mapping-form-builder/js/util/dom.es', 'dynamic-data-mapping-form-builder/js/util/strings.es', 'dynamic-data-mapping-form-renderer', 'frontend-js-metal-web$metal', 'frontend-js-metal-web$metal-dom', 'frontend-js-metal-web$metal-events', 'frontend-js-metal-web$metal-jsx', 'frontend-js-metal-web$metal-state', './components/ShareFormModal/ShareFormModal.es', './util/AutoSave.es', './util/FormURL.es', './util/Notifications.es', './util/StateSyncronizer.es'], function (module, exports, require) {
  var define = undefined;
  var global = window;
  {
    Object.defineProperty(exports, "__esModule", {
      value: true
    });
    exports.Form = exports.default = void 0;

    var _clayModal = _interopRequireDefault(require("frontend-taglib-clay$clay-modal"));

    var _FormBuilder = require("dynamic-data-mapping-form-builder/js/components/FormBuilder/FormBuilder.es");

    var _withActionableFields = _interopRequireDefault(require("dynamic-data-mapping-form-builder/js/components/FormBuilder/withActionableFields.es"));

    var _withClickableFields = _interopRequireDefault(require("dynamic-data-mapping-form-builder/js/components/FormBuilder/withClickableFields.es"));

    var _withEditablePageHeader = _interopRequireDefault(require("dynamic-data-mapping-form-builder/js/components/FormBuilder/withEditablePageHeader.es"));

    var _withMoveableFields = _interopRequireDefault(require("dynamic-data-mapping-form-builder/js/components/FormBuilder/withMoveableFields.es"));

    var _withMultiplePages = _interopRequireDefault(require("dynamic-data-mapping-form-builder/js/components/FormBuilder/withMultiplePages.es"));

    var _withResizeableColumns = _interopRequireDefault(require("dynamic-data-mapping-form-builder/js/components/FormBuilder/withResizeableColumns.es"));

    var _LayoutProvider = _interopRequireDefault(require("dynamic-data-mapping-form-builder/js/components/LayoutProvider/LayoutProvider.es"));

    var _RuleBuilder = _interopRequireDefault(require("dynamic-data-mapping-form-builder/js/components/RuleBuilder/RuleBuilder.es"));

    var _Sidebar = _interopRequireDefault(require("dynamic-data-mapping-form-builder/js/components/Sidebar/Sidebar.es"));

    var _config = require("dynamic-data-mapping-form-builder/js/util/config.es");

    var _dom = require("dynamic-data-mapping-form-builder/js/util/dom.es");

    var _strings = require("dynamic-data-mapping-form-builder/js/util/strings.es");

    var _dynamicDataMappingFormRenderer = require("dynamic-data-mapping-form-renderer");

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

    var _metalDom = _interopRequireDefault(require("frontend-js-metal-web$metal-dom"));

    var _metalEvents = require("frontend-js-metal-web$metal-events");

    var _metalJsx = _interopRequireDefault(require("frontend-js-metal-web$metal-jsx"));

    var _metalState = require("frontend-js-metal-web$metal-state");

    var _ShareFormModal = _interopRequireDefault(require("./components/ShareFormModal/ShareFormModal.es"));

    var _AutoSave = _interopRequireDefault(require("./util/AutoSave.es"));

    var _FormURL = _interopRequireDefault(require("./util/FormURL.es"));

    var _Notifications = _interopRequireDefault(require("./util/Notifications.es"));

    var _StateSyncronizer = _interopRequireDefault(require("./util/StateSyncronizer.es"));

    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 _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 _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 NAV_ITEMS = {
      FORM: 0,
      REPORT: 2,
      RULES: 1
    };
    /**
     * Form.
     * @extends Component
     */

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

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

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

      _createClass(Form, [{
        key: "attached",
        value: function attached() {
          var _this = this;

          var store = this.refs.store;
          var _this$props = this.props,
              localizedDescription = _this$props.localizedDescription,
              localizedName = _this$props.localizedName,
              namespace = _this$props.namespace,
              published = _this$props.published,
              showPublishAlert = _this$props.showPublishAlert;
          var _this$state = this.state,
              activeNavItem = _this$state.activeNavItem,
              paginationMode = _this$state.paginationMode;
          this._eventHandler = new _metalEvents.EventHandler();
          var nameEditor = document.getElementById("".concat(namespace, "nameEditor"));
          nameEditor.addEventListener('keydown', this._handleNameEditorKeydown);
          nameEditor.addEventListener('keyup', this._handleNameEditorCopyAndPaste);
          nameEditor.addEventListener('keypress', this._handleNameEditorCopyAndPaste);
          var descriptionEditor = document.getElementById("".concat(namespace, "descriptionEditor"));
          var dependencies = [Liferay.componentReady('translationManager')];

          if (this.isFormBuilderView()) {
            dependencies.push(this._getSettingsDDMForm());
            this.syncActiveNavItem(activeNavItem);
          }

          Promise.all(dependencies).then(function (_ref) {
            var _ref2 = _slicedToArray(_ref, 2),
                translationManager = _ref2[0],
                settingsDDMForm = _ref2[1];

            nameEditor.classList.remove('hidden');
            descriptionEditor.classList.remove('hidden');

            if (translationManager) {
              _this.props.defaultLanguageId = translationManager.get('defaultLocale');
              _this.props.editingLanguageId = translationManager.get('editingLocale');
              _this._translationManagerHandles = [translationManager.on('editingLocale', function (_ref3) {
                var newValue = _ref3.newValue;
                _this.props.editingLanguageId = newValue;
              }), translationManager.on('availableLocales', _this.onAvailableLocalesRemoved.bind(_this))];
            }

            _this._stateSyncronizer = new _StateSyncronizer.default({
              descriptionEditor: descriptionEditor,
              localizedDescription: localizedDescription,
              localizedName: localizedName,
              nameEditor: nameEditor,
              namespace: namespace,
              paginationMode: paginationMode,
              published: published,
              settingsDDMForm: settingsDDMForm,
              store: store,
              translationManager: translationManager
            }, _this.element);
            _this._autoSave = new _AutoSave.default({
              form: document.querySelector("#".concat(namespace, "editForm")),
              interval: Liferay.DDM.FormSettings.autosaveInterval,
              namespace: namespace,
              stateSyncronizer: _this._stateSyncronizer,
              url: Liferay.DDM.FormSettings.autosaveURL
            }, _this.element);

            _this._eventHandler.add(_this._autoSave.on('autosaved', _this._updateAutoSaveMessage));
          });

          this._eventHandler.add(_metalDom.default.on("#addFieldButton", 'click', this._handleAddFieldButtonClicked.bind(this)), _metalDom.default.on("#".concat(namespace, "controlMenu .sites-control-group span.lfr-portal-tooltip"), 'click', this._handleBackButtonClicked), _metalDom.default.on('.forms-navigation-bar li', 'click', this._handleFormNavClicked), _metalDom.default.on('.lfr-ddm-preview-button', 'click', this._handlePreviewButtonClicked.bind(this)), _metalDom.default.on('.lfr-ddm-save-button', 'click', this._handleSaveButtonClicked.bind(this)), _metalDom.default.on('.lfr-ddm-publish-button', 'click', this._handlePublishButtonClicked.bind(this)));

          var shareURLButton = document.querySelector('.lfr-ddm-share-url-button');

          if (showPublishAlert) {
            if (published) {
              this._showPublishedAlert(this._createFormURL());

              shareURLButton.removeAttribute('title');
            } else {
              this._showUnpublishedAlert();
            }
          }

          if (activeNavItem === NAV_ITEMS.FORM && !this._pageHasFields(store.getPages(), store.state.activePage)) {
            this.openSidebar();
          }

          store.on('fieldDuplicated', function () {
            return _this.openSidebar();
          });
          store.on('focusedFieldChanged', function (_ref4) {
            var newVal = _ref4.newVal;

            if (newVal && Object.keys(newVal).length > 0) {
              _this.openSidebar();
            }
          });
          store.on('activePageChanged', function () {
            var _store$state = store.state,
                activePage = _store$state.activePage,
                pages = _store$state.pages;

            if (activePage > -1 && pages[activePage] && !pages[activePage].successPageSettings) {
              if (!_this._pageHasFields(pages, activePage)) {
                _this.openSidebar();
              }
            }
          });
          store.on('pagesChanged', function (_ref5) {
            var newVal = _ref5.newVal,
                prevVal = _ref5.prevVal;

            if (newVal && prevVal && newVal.length !== prevVal.length && !_this._pageHasFields(newVal, store.state.activePage)) {
              _this.openSidebar();
            }
          });
          store.on('paginationModeChanged', this._handlePaginationModeChanded.bind(this));
          store.on('ruleCancelled', this.showAddButton.bind(this));
          store.on('rulesModified', this._handleRulesModified.bind(this));
        }
      }, {
        key: "checkEditorLimit",
        value: function checkEditorLimit(event, limit) {
          var charCode = event.which ? event.which : event.keyCode;

          if (this.isForbiddenKey(event, limit) && charCode != 91) {
            event.preventDefault();
          }
        }
      }, {
        key: "created",
        value: function created() {
          this._createFormURL = this._createFormURL.bind(this);
          this._handleBackButtonClicked = this._handleBackButtonClicked.bind(this);
          this._handleFormNavClicked = this._handleFormNavClicked.bind(this);
          this._handleNameEditorCopyAndPaste = this._handleNameEditorCopyAndPaste.bind(this);
          this._handleNameEditorKeydown = this._handleNameEditorKeydown.bind(this);
          this._handlePaginationModeChanded = this._handlePaginationModeChanded.bind(this);
          this._resolvePreviewURL = this._resolvePreviewURL.bind(this);
          this._updateAutoSaveMessage = this._updateAutoSaveMessage.bind(this);
          this.ComposedFormBuilder = this._createFormBuilder();
          this.submitForm = this.submitForm.bind(this);
        }
      }, {
        key: "disposed",
        value: function disposed() {
          if (this._autoSave) {
            this._autoSave.dispose();
          }

          if (this._stateSyncronizer) {
            this._stateSyncronizer.dispose();
          }

          _Notifications.default.closeAlert();

          this._eventHandler.removeAllListeners();

          if (this._translationManagerHandles) {
            this._translationManagerHandles.forEach(function (handle) {
              return handle.detach();
            });
          }

          var namespace = this.props.namespace;
          var nameEditor = document.getElementById("".concat(namespace, "nameEditor"));
          nameEditor.removeEventListener('keydown', this._handleNameEditorKeydown);
          nameEditor.removeEventListener('keyup', this._handleNameEditorCopyAndPaste);
          nameEditor.removeEventListener('keypress', this._handleNameEditorCopyAndPaste);
        }
      }, {
        key: "hideAddButton",
        value: function hideAddButton() {
          var addButton = document.querySelector('#addFieldButton');
          addButton.classList.add('hide');
        }
      }, {
        key: "isForbiddenKey",
        value: function isForbiddenKey(event, limit) {
          var charCode = event.which ? event.which : event.keyCode;
          var forbidden = false;

          if (event.target.innerText.length >= limit && (0, _dom.isModifyingKey)(charCode) && !(0, _dom.isKeyInSet)(charCode, ['BACKSPACE', 'DELETE', 'ESC', 'ENTER'])) {
            forbidden = true;
          }

          return forbidden;
        }
      }, {
        key: "isFormBuilderView",
        value: function isFormBuilderView() {
          var view = this.props.view;
          return view !== 'fieldSets';
        }
      }, {
        key: "isShowRuleBuilder",
        value: function isShowRuleBuilder() {
          var activeNavItem = this.state.activeNavItem;
          return activeNavItem === NAV_ITEMS.RULES && this.isFormBuilderView();
        }
      }, {
        key: "isShowReport",
        value: function isShowReport() {
          var activeNavItem = this.state.activeNavItem;
          return activeNavItem === NAV_ITEMS.REPORT && this.isFormBuilderView();
        }
      }, {
        key: "onAvailableLocalesRemoved",
        value: function onAvailableLocalesRemoved(_ref6) {
          var newValue = _ref6.newValue,
              previousValue = _ref6.previousValue;
          var store = this.refs.store;
          var removedItems = new Map();
          previousValue.forEach(function (value, key) {
            if (!newValue.has(key)) {
              removedItems.set(key, value);
            }
          });

          if (removedItems.size > 0) {
            store.emit('languageIdDeleted', {
              locale: removedItems.keys().next().value
            });
          }
        }
      }, {
        key: "openSidebar",
        value: function openSidebar() {
          this.refs.sidebar.open();
        }
      }, {
        key: "preventCopyAndPaste",
        value: function preventCopyAndPaste(event, limit) {
          var target = event.target;

          if (this.isForbiddenKey(event, limit)) {
            target.innerText = target.innerText.substr(0, limit);
            var range = document.createRange();
            var sel = window.getSelection();
            range.setStart(target.childNodes[0], target.textContent.length);
            range.collapse(true);
            sel.removeAllRanges();
            sel.addRange(range);
          }
        }
      }, {
        key: "publish",
        value: function publish(event) {
          this.props.published = true;
          return this._savePublished(event, true);
        }
      }, {
        key: "render",
        value: function render() {
          var ComposedFormBuilder = this.ComposedFormBuilder;
          var _this$props2 = this.props,
              autocompleteUserURL = _this$props2.autocompleteUserURL,
              context = _this$props2.context,
              dataProviderInstanceParameterSettingsURL = _this$props2.dataProviderInstanceParameterSettingsURL,
              dataProviderInstancesURL = _this$props2.dataProviderInstancesURL,
              defaultLanguageId = _this$props2.defaultLanguageId,
              editingLanguageId = _this$props2.editingLanguageId,
              fieldSetDefinitionURL = _this$props2.fieldSetDefinitionURL,
              fieldSets = _this$props2.fieldSets,
              fieldTypes = _this$props2.fieldTypes,
              functionsMetadata = _this$props2.functionsMetadata,
              functionsURL = _this$props2.functionsURL,
              groupId = _this$props2.groupId,
              localizedName = _this$props2.localizedName,
              namespace = _this$props2.namespace,
              published = _this$props2.published,
              redirectURL = _this$props2.redirectURL,
              rolesURL = _this$props2.rolesURL,
              rules = _this$props2.rules,
              shareFormInstanceURL = _this$props2.shareFormInstanceURL,
              spritemap = _this$props2.spritemap,
              view = _this$props2.view;
          var saveButtonLabel = this.state.saveButtonLabel;

          var storeProps = _objectSpread(_objectSpread({}, this.props), {}, {
            defaultLanguageId: defaultLanguageId,
            editingLanguageId: editingLanguageId,
            initialPages: context.pages,
            initialPaginationMode: context.paginationMode,
            initialSuccessPageSettings: context.successPageSettings,
            ref: 'store'
          });

          var LayoutProviderTag = _LayoutProvider.default;
          IncrementalDOM.elementOpen("div", null, null, "class", 'ddm-form-builder');
          IncrementalDOM.elementOpenStart(LayoutProviderTag);
          iDOMHelpers.forOwn(storeProps, iDOMHelpers.attr);
          IncrementalDOM.elementOpenEnd(LayoutProviderTag);
          iDOMHelpers.renderArbitrary(this.isFormBuilderView() && IncrementalDOM.elementVoid(_RuleBuilder.default, null, null, "dataProviderInstanceParameterSettingsURL", dataProviderInstanceParameterSettingsURL, "dataProviderInstancesURL", dataProviderInstancesURL, "fieldTypes", fieldTypes, "functionsMetadata", functionsMetadata, "functionsURL", functionsURL, "groupId", groupId, "portletNamespace", namespace, "rolesURL", rolesURL, "rules", rules, "spritemap", spritemap, "visible", this.isShowRuleBuilder(), "ref", "ruleBuilder"));
          IncrementalDOM.elementVoid(ComposedFormBuilder, null, null, "fieldSets", fieldSets, "fieldTypes", fieldTypes, "groupId", groupId, "portletNamespace", namespace, "rules", rules, "spritemap", spritemap, "view", view, "visible", !this.isShowRuleBuilder() && !this.isShowReport(), "ref", "formBuilder");
          IncrementalDOM.elementVoid(_Sidebar.default, null, null, "defaultLanguageId", defaultLanguageId, "editingLanguageId", editingLanguageId, "fieldSetDefinitionURL", fieldSetDefinitionURL, "fieldSets", fieldSets, "fieldTypes", fieldTypes, "portletNamespace", namespace, "spritemap", spritemap, "visible", !this.isShowRuleBuilder() && !this.isShowReport(), "ref", "sidebar");
          IncrementalDOM.elementClose(LayoutProviderTag);
          IncrementalDOM.elementOpen("div", null, null, "class", "container-fluid-1280");
          iDOMHelpers.renderArbitrary(!this.isFormBuilderView() && (IncrementalDOM.elementOpen("div", null, null, "class", "button-holder ddm-form-builder-buttons"), (IncrementalDOM.elementOpen("button", null, null, "class", "btn btn-primary ddm-button", "data-onclick", "_handleSaveButtonClicked", "ref", "saveFieldSetButton"), iDOMHelpers.renderArbitrary(saveButtonLabel), IncrementalDOM.elementClose("button")), (IncrementalDOM.elementOpen("a", null, null, "href", redirectURL, "class", "btn btn-cancel btn-link", "data-onclick", "_handleCancelButtonClicked", "ref", "cancelFieldSetButton"), iDOMHelpers.renderArbitrary(Liferay.Language.get('cancel')), IncrementalDOM.elementClose("a")), IncrementalDOM.elementClose("div")));
          IncrementalDOM.elementVoid(_clayModal.default, null, null, "body", Liferay.Language.get('any-unsaved-changes-will-be-lost-are-you-sure-you-want-to-leave'), "footerButtons", [{
            alignment: 'right',
            label: Liferay.Language.get('leave'),
            style: 'secondary',
            type: 'close'
          }, {
            alignment: 'right',
            label: Liferay.Language.get('stay'),
            style: 'primary',
            type: 'button'
          }], "spritemap", spritemap, "title", Liferay.Language.get('leave-form'), "ref", 'discardChangesModal', "size", 'sm');
          iDOMHelpers.renderArbitrary(published && IncrementalDOM.elementVoid(_ShareFormModal.default, null, null, "autocompleteUserURL", autocompleteUserURL, "localizedName", localizedName, "portletNamespace", namespace, "shareFormInstanceURL", shareFormInstanceURL, "spritemap", spritemap, "url", this._createFormURL()));
          IncrementalDOM.elementClose("div");
          return IncrementalDOM.elementClose("div");
        }
      }, {
        key: "showAddButton",
        value: function showAddButton() {
          var addButton = document.querySelector('#addFieldButton');
          addButton.classList.remove('hide');
        }
      }, {
        key: "submitForm",
        value: function (_submitForm) {
          function submitForm() {
            return _submitForm.apply(this, arguments);
          }

          submitForm.toString = function () {
            return _submitForm.toString();
          };

          return submitForm;
        }(function () {
          var namespace = this.props.namespace;

          this._stateSyncronizer.syncInputs();

          submitForm(document.querySelector("#".concat(namespace, "editForm")));
        })
      }, {
        key: "syncActiveNavItem",
        value: function syncActiveNavItem(activeNavItem) {
          switch (activeNavItem) {
            case NAV_ITEMS.FORM:
              this._toggleRulesBuilder(false);

              this._toggleReport(false);

              this._toggleFormBuilder(true);

              break;

            case NAV_ITEMS.RULES:
              this._toggleFormBuilder(false);

              this._toggleReport(false);

              this._toggleRulesBuilder(true);

              break;

            case NAV_ITEMS.REPORT:
              this._toggleFormBuilder(false);

              this._toggleRulesBuilder(false);

              this._toggleReport(true);

              break;

            default:
              break;
          }
        }
      }, {
        key: "unpublish",
        value: function unpublish(event) {
          this.props.published = false;
          return this._savePublished(event, false);
        }
      }, {
        key: "_activeNavItemValueFn",
        value: function _activeNavItemValueFn() {
          var context = this.props.context;
          return context.activeNavItem || NAV_ITEMS.FORM;
        }
      }, {
        key: "_handleAddFieldButtonClicked",
        value: function _handleAddFieldButtonClicked() {
          if (this.isShowRuleBuilder()) {
            this.refs.ruleBuilder.showRuleCreation();
            this.hideAddButton();
          } else {
            this.openSidebar();
          }
        }
      }, {
        key: "_createEditor",
        value: function _createEditor(name) {
          var namespace = this.props.namespace;
          var editorName = "".concat(namespace).concat(name);
          var editor = window[editorName];
          var promise;

          if (editor) {
            editor.create();
            promise = Promise.resolve(CKEDITOR.instances[editorName]);
          } else {
            promise = new Promise(function (resolve) {
              Liferay.on('editorAPIReady', function (event) {
                if (event.editorName === editorName) {
                  event.editor.create();
                  resolve(CKEDITOR.instances[editorName]);
                }
              });
            });
          }

          return promise;
        }
      }, {
        key: "_createFormBuilder",
        value: function _createFormBuilder() {
          var composeList = [_withActionableFields.default, _withClickableFields.default, _withMoveableFields.default, _withMultiplePages.default, _withResizeableColumns.default];

          if (this.isFormBuilderView()) {
            composeList.push(_withEditablePageHeader.default);
          }

          return _dynamicDataMappingFormRenderer.compose.apply(void 0, composeList)(_FormBuilder.FormBuilderBase);
        }
      }, {
        key: "_createFormURL",
        value: function _createFormURL() {
          var settingsDDMForm = Liferay.component('settingsDDMForm');
          var requireAuthentication = false;

          if (settingsDDMForm && settingsDDMForm.reactComponentRef.current) {
            var settingsPageVisitor = new _dynamicDataMappingFormRenderer.PagesVisitor(settingsDDMForm.reactComponentRef.current.get('pages'));
            settingsPageVisitor.mapFields(function (field) {
              if (field.fieldName === 'requireAuthentication') {
                requireAuthentication = field.value;
              }
            });
          }

          var formURL = new _FormURL.default(this._getFormInstanceId(), this.props.published, requireAuthentication);
          return formURL.create();
        }
      }, {
        key: "_getFormInstanceId",
        value: function _getFormInstanceId() {
          var namespace = this.props.namespace;
          return document.querySelector("#".concat(namespace, "formInstanceId")).value;
        }
      }, {
        key: "_getSettingsDDMForm",
        value: function _getSettingsDDMForm() {
          var promise;
          var settingsDDMForm = Liferay.component('settingsDDMForm');

          if (settingsDDMForm) {
            promise = Promise.resolve(settingsDDMForm);
          } else {
            promise = Liferay.componentReady('settingsDDMForm');
          }

          return promise;
        }
      }, {
        key: "_handleBackButtonClicked",
        value: function _handleBackButtonClicked(event) {
          var _this2 = this;

          if (this._autoSave.hasUnsavedChanges()) {
            event.preventDefault();
            event.stopPropagation();
            var href = event.delegateTarget.firstElementChild.href;
            this.refs.discardChangesModal.visible = true;
            var listener = this.refs.discardChangesModal.addListener('clickButton', function (_ref7) {
              var target = _ref7.target;

              if (target.classList.contains('close-modal')) {
                window.location.href = href;
              }

              listener.dispose();

              _this2.refs.discardChangesModal.emit('hide');
            });
          }
        }
      }, {
        key: "_handleCancelButtonClicked",
        value: function _handleCancelButtonClicked(event) {
          var href = event.delegateTarget.href;
          event.preventDefault();
          event.stopPropagation();
          window.location.href = href;
        }
      }, {
        key: "_handleFormNavClicked",
        value: function _handleFormNavClicked(event) {
          var delegateTarget = event.delegateTarget;

          var navItem = _metalDom.default.closest(delegateTarget, '.nav-item');

          var navItemIndex = Number(navItem.dataset.navItemIndex);
          var navLink = navItem.querySelector('.nav-link');
          document.querySelector('.forms-navigation-bar li > .active').classList.remove('active');
          navLink.classList.add('active');
          this.setState({
            activeNavItem: navItemIndex
          });
          this.syncActiveNavItem(this.state.activeNavItem);
        }
      }, {
        key: "_handleNameEditorCopyAndPaste",
        value: function _handleNameEditorCopyAndPaste(event) {
          return this.preventCopyAndPaste(event, 120);
        }
      }, {
        key: "_handleNameEditorKeydown",
        value: function _handleNameEditorKeydown(event) {
          return this.checkEditorLimit(event, 120);
        }
      }, {
        key: "_handlePaginationModeChanded",
        value: function _handlePaginationModeChanded(_ref8) {
          var newVal = _ref8.newVal;
          this.setState({
            paginationMode: newVal
          });
        }
      }, {
        key: "_handlePreviewButtonClicked",
        value: function _handlePreviewButtonClicked() {
          return this._resolvePreviewURL().then(function (previewURL) {
            window.open(previewURL, '_blank');
            return previewURL;
          }).catch(function () {
            _Notifications.default.showError(Liferay.Language.get('your-request-failed-to-complete'));
          });
        }
      }, {
        key: "_handlePublishButtonClicked",
        value: function _handlePublishButtonClicked(event) {
          var published = this.props.published;
          var promise;

          if (published) {
            promise = this.unpublish(event);
          } else {
            promise = this.publish(event);
          }

          return promise;
        }
      }, {
        key: "_handleRulesModified",
        value: function _handleRulesModified() {
          this._autoSave.save(true);

          this.showAddButton();
        }
      }, {
        key: "_handleSaveButtonClicked",
        value: function _handleSaveButtonClicked(event) {
          event.preventDefault();
          this.setState({
            saveButtonLabel: Liferay.Language.get('saving')
          });
          this.submitForm();
        }
      }, {
        key: "_pageHasFields",
        value: function _pageHasFields(pages, pageIndex) {
          var visitor = new _dynamicDataMappingFormRenderer.PagesVisitor([pages[pageIndex]]);
          var hasFields = false;
          visitor.mapFields(function () {
            hasFields = true;
          });
          return hasFields;
        }
      }, {
        key: "_pagesValueFn",
        value: function _pagesValueFn() {
          var context = this.props.context;
          return context.pages;
        }
      }, {
        key: "_paginationModeValueFn",
        value: function _paginationModeValueFn() {
          var context = this.props.context;
          return context.paginationMode;
        }
      }, {
        key: "_resolvePreviewURL",
        value: function _resolvePreviewURL() {
          var _this3 = this;

          return this._autoSave.save(true).then(function () {
            return "".concat(_this3._createFormURL(), "/preview");
          });
        }
      }, {
        key: "_saveButtonLabelValueFn",
        value: function _saveButtonLabelValueFn() {
          var label = Liferay.Language.get('save');

          if (this.isFormBuilderView()) {
            label = Liferay.Language.get('save-form');
          }

          return label;
        }
      }, {
        key: "_savePublished",
        value: function _savePublished(event) {
          var namespace = this.props.namespace;
          var url = Liferay.DDM.FormSettings.publishFormInstanceURL;
          event.preventDefault();
          var form = document.querySelector("#".concat(namespace, "editForm"));

          if (form) {
            form.setAttribute('action', url);
          }

          return Promise.resolve(this.submitForm());
        }
      }, {
        key: "_setContext",
        value: function _setContext(context) {
          var _context = context,
              successPageSettings = _context.successPageSettings;
          var defaultLanguageId = this.props.defaultLanguageId;
          var _context2 = context,
              successPage = _context2.successPage;

          if (!successPageSettings && this.isFormBuilderView()) {
            successPageSettings = successPage;
            successPageSettings.enabled = true;
          }

          if (successPageSettings && _metal.default.isString(successPageSettings.title)) {
            successPageSettings.title = {};
            successPageSettings.title[defaultLanguageId] = '';
          }

          if (successPageSettings && _metal.default.isString(successPageSettings.body)) {
            successPageSettings.body = {};
            successPageSettings.body[defaultLanguageId] = '';
          }

          var emptyLocalizableValue = _defineProperty({}, themeDisplay.getLanguageId(), '');

          if (!context.pages.length) {
            context = _objectSpread(_objectSpread({}, context), {}, {
              pages: [{
                description: '',
                localizedDescription: emptyLocalizableValue,
                localizedTitle: emptyLocalizableValue,
                rows: [{
                  columns: [{
                    fields: [],
                    size: 12
                  }]
                }],
                title: ''
              }],
              paginationMode: 'wizard',
              successPageSettings: successPageSettings
            });
          }

          return _objectSpread(_objectSpread({}, context), {}, {
            pages: context.pages.map(function (page) {
              var description = page.description,
                  localizedDescription = page.localizedDescription,
                  localizedTitle = page.localizedTitle,
                  title = page.title;

              if (!_metal.default.isString(description)) {
                description = description[themeDisplay.getLanguageId()];
                localizedDescription = _defineProperty({}, themeDisplay.getLanguageId(), description);
              }

              if (!_metal.default.isString(title)) {
                title = title[themeDisplay.getLanguageId()];
                localizedTitle = _defineProperty({}, themeDisplay.getLanguageId(), title);
              }

              return _objectSpread(_objectSpread({}, page), {}, {
                description: description,
                localizedDescription: localizedDescription,
                localizedTitle: localizedTitle,
                title: title
              });
            })
          });
        }
      }, {
        key: "_setSearchParamsWithoutPageReload",
        value: function _setSearchParamsWithoutPageReload(name, value) {
          var url = new URL(location.toString());
          url.searchParams.set(name, value);
          window.history.replaceState({
            path: url.toString()
          }, '', url.toString());
        }
      }, {
        key: "_showPublishedAlert",
        value: function _showPublishedAlert(publishURL) {
          var message = Liferay.Language.get('the-form-was-published-successfully-access-it-with-this-url-x');

          _Notifications.default.showAlert(message.replace(/\{0\}/gim, "<span style=\"font-weight: 500\"><a href=".concat(publishURL, " target=\"_blank\">").concat(publishURL, "</a></span>")));
        }
      }, {
        key: "_showUnpublishedAlert",
        value: function _showUnpublishedAlert() {
          _Notifications.default.showAlert(Liferay.Language.get('the-form-was-unpublished-successfully'));
        }
      }, {
        key: "_toggleFormBuilder",
        value: function _toggleFormBuilder(show) {
          var namespace = this.props.namespace;
          var managementToolbar = document.querySelector("#".concat(namespace, "managementToolbar"));
          var formBasicInfo = document.querySelector('.ddm-form-basic-info');
          var formBuilderButtons = document.querySelectorAll('.toolbar-group-field .nav-item .lfr-ddm-button');
          var publishIcon = document.querySelector('.publish-icon');
          var translationManager = document.querySelector('.ddm-translation-manager');

          if (show) {
            this._setSearchParamsWithoutPageReload("".concat(namespace, "activeNavItem"), NAV_ITEMS.FORM);

            managementToolbar.classList.remove('hide');
            formBasicInfo.classList.remove('hide');
            formBuilderButtons.forEach(function (formBuilderButton) {
              formBuilderButton.classList.remove('hide');
            });

            if (publishIcon) {
              publishIcon.classList.remove('hide');
            }

            if (translationManager) {
              translationManager.classList.remove('hide');
            }

            this.showAddButton();
          } else {
            managementToolbar.classList.add('hide');
            formBasicInfo.classList.add('hide');
            formBuilderButtons.forEach(function (formBuilderButton) {
              formBuilderButton.classList.add('hide');
            });

            if (publishIcon) {
              publishIcon.classList.add('hide');
            }

            if (translationManager) {
              translationManager.classList.add('hide');
            }

            this.hideAddButton();
          }
        }
      }, {
        key: "_toggleReport",
        value: function _toggleReport(show) {
          var formReport = document.querySelector('#container-portlet-ddm-form-report');

          if (!formReport) {
            return;
          }

          if (show) {
            var namespace = this.props.namespace;

            this._setSearchParamsWithoutPageReload("".concat(namespace, "activeNavItem"), NAV_ITEMS.REPORT);

            formReport.classList.remove('hide');
          } else {
            formReport.classList.add('hide');
          }
        }
      }, {
        key: "_toggleRulesBuilder",
        value: function _toggleRulesBuilder(show) {
          var namespace = this.props.namespace;
          var managementToolbar = document.querySelector("#".concat(namespace, "managementToolbar"));

          if (show) {
            this._setSearchParamsWithoutPageReload("".concat(namespace, "activeNavItem"), NAV_ITEMS.RULES);

            managementToolbar.classList.remove('hide');
          } else {
            managementToolbar.classList.add('hide');
          }

          if (this.refs.ruleBuilder.isViewMode()) {
            this.showAddButton();
          } else {
            this.hideAddButton();
          }
        }
      }, {
        key: "_updateAutoSaveMessage",
        value: function _updateAutoSaveMessage(_ref9) {
          var modifiedDate = _ref9.modifiedDate;
          var namespace = this.props.namespace;
          var autoSaveMessageNode = document.querySelector("#".concat(namespace, "autosaveMessage"));
          autoSaveMessageNode.innerHTML = (0, _strings.sub)(Liferay.Language.get('draft-x'), [modifiedDate]);
        }
      }]);

      return Form;
    }(_metalJsx.default);

    exports.Form = Form;
    Form.PROPS = {
      /**
       * @default undefined
       * @instance
       * @memberof Form
       * @type {!string}
       */
      autocompleteUserURL: _metalState.Config.string(),

      /**
       * The context for rendering a layout that represents a form.
       * @default undefined
       * @instance
       * @memberof Form
       * @type {!array}
       */
      context: _metalState.Config.shapeOf({
        pages: _metalState.Config.arrayOf(_metalState.Config.object()),
        paginationMode: _metalState.Config.string(),
        rules: _metalState.Config.array(),
        successPageSettings: _metalState.Config.object()
      }).required().setter('_setContext'),

      /**
       * The rules of a form.
       * @default undefined
       * @instance
       * @memberof Form
       * @type {!array}
       */
      dataProviderInstanceParameterSettingsURL: _metalState.Config.string().required(),

      /**
       * The rules of a form.
       * @default undefined
       * @instance
       * @memberof Form
       * @type {!array}
       */
      dataProviderInstancesURL: _metalState.Config.string().required(),

      /**
       * The default language id of the form.
       * @default undefined
       * @instance
       * @memberof Form
       * @type {!array}
       */
      defaultLanguageId: _metalState.Config.string().value(themeDisplay.getDefaultLanguageId()),

      /**
       * The default language id of the form.
       * @default undefined
       * @instance
       * @memberof Form
       * @type {!array}
       */
      editingLanguageId: _metalState.Config.string().value(themeDisplay.getDefaultLanguageId()),

      /**
       * @default undefined
       * @instance
       * @memberof Form
       * @type {?string}
       */
      fieldSetDefinitionURL: _metalState.Config.string(),

      /**
       * @default []
       * @instance
       * @memberof Form
       * @type {?(array|undefined)}
       */
      fieldSets: _metalState.Config.array().value([]),

      /**
       * @default []
       * @instance
       * @memberof Form
       * @type {?(array|undefined)}
       */
      fieldTypes: _metalState.Config.array().value([]),

      /**
       * A map with all translated values available as the form description.
       * @default 0
       * @instance
       * @memberof Form
       * @type {!array}
       */
      formInstanceId: _metalState.Config.number().value(0),

      /**
       * A map with all translated values available as the form name.
       * @default undefined
       * @instance
       * @memberof Form
       * @type {!array}
       */
      functionsMetadata: _metalState.Config.object().value({}),

      /**
       * A map with all translated values available as the form name.
       * @default undefined
       * @instance
       * @memberof Form
       * @type {!array}
       */
      functionsURL: _metalState.Config.string(),

      /**
       * A map with all translated values available as the form description.
       * @default undefined
       * @instance
       * @memberof Form
       * @type {!array}
       */
      localizedDescription: _metalState.Config.object().value({}),

      /**
       * The context for rendering a layout that represents a form.
       * @default undefined
       * @instance
       * @memberof Form
       * @type {!array}
       */
      localizedName: _metalState.Config.object().value({}),

      /**
       * The namespace of the portlet.
       * @default undefined
       * @instance
       * @memberof Form
       * @type {!string}
       */
      namespace: _metalState.Config.string().required(),

      /**
       * Whether the form is published or not
       * @default false
       * @instance
       * @memberof Form
       * @type {!boolean}
       */
      published: _metalState.Config.bool().value(false),

      /**
       * The url to be redirected when canceling the Element Set edition.
       * @default undefined
       * @instance
       * @memberof Form
       * @type {!string}
       */
      redirectURL: _metalState.Config.string(),

      /**
       * The rules of a form.
       * @default undefined
       * @instance
       * @memberof Form
       * @type {!array}
       */
      rolesURL: _metalState.Config.string(),

      /**
       * The rules of a form.
       * @default undefined
       * @instance
       * @memberof Form
       * @type {!array}
       */
      rules: _metalState.Config.array().value([]),

      /**
       * The path to the SVG spritemap file containing the icons.
       * @default undefined
       * @instance
       * @memberof Form
       * @type {!boolean}
       */
      saved: _metalState.Config.bool(),

      /**
       * @default undefined
       * @instance
       * @memberof Form
       * @type {!string}
       */
      shareFormInstanceURL: _metalState.Config.string(),

      /**
       * Whether to show an alert telling the user about the result of the
       * "Publish" operation.
       * @default false
       * @instance
       * @memberof Form
       * @type {!boolean}
       */
      showPublishAlert: _metalState.Config.bool().value(false),

      /**
       * The path to the SVG spritemap file containing the icons.
       * @default undefined
       * @instance
       * @memberof Form
       * @type {!string}
       */
      spritemap: _metalState.Config.string().required(),
      view: _metalState.Config.string()
    };
    Form.STATE = {
      /**
       * Current active tab index.
       * @default _activeNavItemValueFn
       * @instance
       * @memberof Form
       * @type {!number}
       */
      activeNavItem: _metalState.Config.number().valueFn('_activeNavItemValueFn'),

      /**
       * Internal mirror of the pages state
       * @default _pagesValueFn
       * @instance
       * @memberof Form
       * @type {!array}
       */
      pages: _metalState.Config.arrayOf(_config.pageStructure).valueFn('_pagesValueFn'),

      /**
       * @default _paginationModeValueFn
       * @instance
       * @memberof Form
       * @type {!array}
       */
      paginationMode: _metalState.Config.string().valueFn('_paginationModeValueFn'),

      /**
       * The label of the save button
       * @default 'save-form'
       * @instance
       * @memberof Form
       * @type {!string}
       */
      saveButtonLabel: _metalState.Config.string().valueFn('_saveButtonLabelValueFn')
    };
    var _default = Form;
    exports.default = _default;
    //# sourceMappingURL=main.es.js.map
  }
});
//# sourceMappingURL=main.es.js.map