Liferay.Loader.define("dynamic-data-mapping-form-web@3.0.78/admin/js/util/StateSyncronizer.es", ['module', 'exports', 'require', 'dynamic-data-mapping-form-renderer', 'frontend-js-metal-web$metal-jsx', 'frontend-js-metal-web$metal-state'], function (module, exports, require) {
  var define = undefined;
  var global = window;
  {
    Object.defineProperty(exports, "__esModule", {
      value: true
    });
    exports.default = void 0;

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

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

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

    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 _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 _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 StateSyncronizer = /*#__PURE__*/function (_Component) {
      _inherits(StateSyncronizer, _Component);

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

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

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

          var _this$props = this.props,
              descriptionEditor = _this$props.descriptionEditor,
              nameEditor = _this$props.nameEditor,
              translationManager = _this$props.translationManager;
          descriptionEditor.addEventListener('input', this._handleDescriptionEditorChanged.bind(this));
          nameEditor.addEventListener('input', this._handleNameEditorChanged.bind(this));

          if (translationManager) {
            this._translationManagerHandles = [translationManager.on('availableLocales', this.onRemoveAvailableLocales.bind(this)), translationManager.on('editingLocale', function (_ref) {
              var newValue = _ref.newValue;

              _this.syncEditors(newValue);
            })];
          }
        }
      }, {
        key: "deleteLanguageId",
        value: function deleteLanguageId(languageId) {
          var _this$props2 = this.props,
              localizedDescription = _this$props2.localizedDescription,
              localizedName = _this$props2.localizedName;
          delete localizedDescription[languageId];
          delete localizedName[languageId];
          this.syncEditors();
        }
      }, {
        key: "disposed",
        value: function disposed() {
          var _this$props3 = this.props,
              descriptionEditor = _this$props3.descriptionEditor,
              nameEditor = _this$props3.nameEditor;
          nameEditor.removeEventListener('input', this._handleNameEditorChanged.bind(this));
          descriptionEditor.removeEventListener('input', this._handleDescriptionEditorChanged.bind(this));

          if (this._translationManagerHandles) {
            this._translationManagerHandles.forEach(function (handle) {
              return handle.detach();
            });
          }
        }
      }, {
        key: "getAvailableLanguageIds",
        value: function getAvailableLanguageIds() {
          var translationManager = this.props.translationManager;
          var availableLanguageIds = [{
            id: this.getDefaultLanguageId()
          }];

          if (translationManager) {
            var availableLocalesMap = translationManager.get('availableLocales');
            availableLanguageIds = _toConsumableArray(availableLocalesMap.keys());
          }

          return availableLanguageIds;
        }
      }, {
        key: "getDefaultLanguageId",
        value: function getDefaultLanguageId() {
          var translationManager = this.props.translationManager;
          var defaultLanguageId = themeDisplay.getDefaultLanguageId();

          if (translationManager) {
            defaultLanguageId = translationManager.get('defaultLocale');
          }

          return defaultLanguageId;
        }
      }, {
        key: "getEditingLanguageId",
        value: function getEditingLanguageId() {
          var translationManager = this.props.translationManager;
          var editingLanguageId = this.getDefaultLanguageId();

          if (translationManager) {
            editingLanguageId = translationManager.get('editingLocale');
          }

          return editingLanguageId;
        }
      }, {
        key: "getState",
        value: function getState() {
          var _this$props4 = this.props,
              localizedDescription = _this$props4.localizedDescription,
              localizedName = _this$props4.localizedName,
              store = _this$props4.store;
          var state = {
            availableLanguageIds: this.getAvailableLanguageIds(),
            defaultLanguageId: this.getDefaultLanguageId(),
            description: localizedDescription,
            name: localizedName,
            pages: store.state.pages,
            paginationMode: store.state.paginationMode,
            rules: store.getRules(),
            successPageSettings: store.state.successPageSettings
          };
          return state;
        }
      }, {
        key: "isEmpty",
        value: function isEmpty() {
          var store = this.props.store;
          return _dynamicDataMappingFormRenderer.FormSupport.isEmpty(store.state.pages);
        }
      }, {
        key: "onRemoveAvailableLocales",
        value: function onRemoveAvailableLocales(_ref2) {
          var newValue = _ref2.newValue,
              previousValue = _ref2.previousValue;
          var removedItems = new Map();
          previousValue.forEach(function (value, key) {
            if (!newValue.has(key)) {
              removedItems.set(key, value);
            }
          });

          if (removedItems.length > 0) {
            this.deleteLanguageId(removedItems.keys().next().value);
          }
        }
      }, {
        key: "syncEditors",
        value: function syncEditors() {
          var editingLanguageId = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.getDefaultLanguageId();
          var _this$props5 = this.props,
              descriptionEditor = _this$props5.descriptionEditor,
              localizedDescription = _this$props5.localizedDescription,
              localizedName = _this$props5.localizedName,
              nameEditor = _this$props5.nameEditor;
          var description = localizedDescription[editingLanguageId];

          if (!description) {
            description = localizedDescription[this.getDefaultLanguageId()];
          }

          descriptionEditor.value = description;
          var name = localizedName[editingLanguageId];

          if (!name) {
            name = localizedName[this.getDefaultLanguageId()];
          }

          nameEditor.value = name;
        }
      }, {
        key: "syncInputs",
        value: function syncInputs() {
          var _this$props6 = this.props,
              namespace = _this$props6.namespace,
              settingsDDMForm = _this$props6.settingsDDMForm;
          var state = this.getState();
          var description = state.description,
              name = state.name;
          Object.keys(state.name).forEach(function (key) {
            state.name[key] = Liferay.Util.unescape(state.name[key]);
          });
          Object.keys(state.description).forEach(function (key) {
            state.description[key] = Liferay.Util.unescape(state.description[key]);
          });

          if (settingsDDMForm && settingsDDMForm.reactComponentRef.current) {
            document.querySelector("#".concat(namespace, "serializedSettingsContext")).value = JSON.stringify({
              pages: settingsDDMForm.reactComponentRef.current.get('pages')
            });
          }

          document.querySelector("#".concat(namespace, "name")).value = JSON.stringify(name);
          document.querySelector("#".concat(namespace, "description")).value = JSON.stringify(description);
          document.querySelector("#".concat(namespace, "serializedFormBuilderContext")).value = this._getSerializedFormBuilderContext();
        }
      }, {
        key: "_getSerializedFormBuilderContext",
        value: function _getSerializedFormBuilderContext() {
          var _this2 = this;

          var state = this.getState();
          var visitor = new _dynamicDataMappingFormRenderer.PagesVisitor(state.pages);
          var pages = visitor.mapPages(function (page) {
            return _objectSpread(_objectSpread({}, page), {}, {
              description: page.localizedDescription,
              title: page.localizedTitle
            });
          });
          visitor.setPages(pages);
          return JSON.stringify(_objectSpread(_objectSpread({}, state), {}, {
            pages: visitor.mapFields(function (field) {
              return _objectSpread(_objectSpread({}, field), {}, {
                settingsContext: _objectSpread(_objectSpread({}, field.settingsContext), {}, {
                  availableLanguageIds: _this2.getAvailableLanguageIds(),
                  defaultLanguageId: _this2.getDefaultLanguageId(),
                  pages: _this2._getSerializedSettingsContextPages(field.settingsContext.pages)
                })
              });
            })
          }));
        }
      }, {
        key: "_getSerializedSettingsContextPages",
        value: function _getSerializedSettingsContextPages(pages) {
          var defaultLanguageId = this.getDefaultLanguageId();
          var visitor = new _dynamicDataMappingFormRenderer.PagesVisitor(pages);
          return visitor.mapFields(function (field) {
            if (field.type === 'options') {
              var _field = field,
                  value = _field.value;
              var newValue = {};
              Object.keys(value).forEach(function (locale) {
                newValue[locale] = value[locale].filter(function (_ref3) {
                  var value = _ref3.value;
                  return value !== '';
                });
              });

              if (!newValue[defaultLanguageId]) {
                newValue[defaultLanguageId] = [];
              }

              field = _objectSpread(_objectSpread({}, field), {}, {
                value: newValue
              });
            }

            return field;
          });
        }
      }, {
        key: "_handleDescriptionEditorChanged",
        value: function _handleDescriptionEditorChanged() {
          var _this$props7 = this.props,
              descriptionEditor = _this$props7.descriptionEditor,
              localizedDescription = _this$props7.localizedDescription;
          localizedDescription[this.getEditingLanguageId()] = descriptionEditor.value;
        }
      }, {
        key: "_handleNameEditorChanged",
        value: function _handleNameEditorChanged() {
          var _this$props8 = this.props,
              localizedName = _this$props8.localizedName,
              nameEditor = _this$props8.nameEditor;
          localizedName[this.getEditingLanguageId()] = nameEditor.value;
        }
      }]);

      return StateSyncronizer;
    }(_metalJsx.default);

    StateSyncronizer.PROPS = {
      descriptionEditor: _metalState.Config.any(),
      localizedDescription: _metalState.Config.object().value({}),
      localizedName: _metalState.Config.object().value({}),
      nameEditor: _metalState.Config.any(),
      namespace: _metalState.Config.string().required(),
      published: _metalState.Config.bool(),
      settingsDDMForm: _metalState.Config.any(),
      store: _metalState.Config.any(),
      translationManager: _metalState.Config.any()
    };
    var _default = StateSyncronizer;
    exports.default = _default;
    //# sourceMappingURL=StateSyncronizer.es.js.map
  }
});
//# sourceMappingURL=StateSyncronizer.es.js.map