Liferay.Loader.define("users-admin-web@5.0.99/js/UserNameFields.es", ['module', 'exports', 'require', 'frontend-js-web', 'frontend-js-metal-web$metal-dom', 'frontend-js-metal-web$metal-events', '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 _frontendJsWeb = require("frontend-js-web");

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

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

    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 _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 _get(target, property, receiver) {
      if (typeof Reflect !== "undefined" && Reflect.get) {
        _get = Reflect.get;
      } else {
        _get = function _get(target, property, receiver) {
          var base = _superPropBase(target, property);if (!base) return;var desc = Object.getOwnPropertyDescriptor(base, property);if (desc.get) {
            return desc.get.call(receiver);
          }return desc.value;
        };
      }return _get(target, property, receiver || target);
    }

    function _superPropBase(object, property) {
      while (!Object.prototype.hasOwnProperty.call(object, property)) {
        object = _getPrototypeOf(object);if (object === null) break;
      }return object;
    }

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

    /**
     * Handles actions to display user name field for a given locale.
     */
    var UserNameFields = /*#__PURE__*/function (_PortletBase) {
      _inherits(UserNameFields, _PortletBase);

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

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

      _createClass(UserNameFields, [{
        key: "attached",

        /**
         * @inheritDoc
         */
        value: function attached() {
          this._eventHandler.add(_metalDom.default.on(this.languageIdSelectNode, 'change', this._handleSelectChange.bind(this)));
        }
        /**
         * @inheritDoc
         */

      }, {
        key: "created",
        value: function created() {
          this._eventHandler = new _metalEvents.EventHandler();
          this._formDataCache = {};
          this._maxLengthsCache = {};
          this._loadingAnimationMarkupText = "<div class=\"loading-animation\" id=\"".concat(this.portletNamespace, "loadingUserNameFields\"></div>");
        }
        /**
         * @inheritDoc
         */

      }, {
        key: "detached",
        value: function detached() {
          _get(_getPrototypeOf(UserNameFields.prototype), "detached", this).call(this);

          this._eventHandler.removeAllListeners();
        }
        /**
         * Updates the user name fields to display the appropriate fields for the
         * given locale.
         *
         * @param {string} languageId The language id used when retrieving the user
         * name fields.
         */

      }, {
        key: "updateUserNameFields",
        value: function updateUserNameFields(languageId) {
          this._setUp();

          this._getURL(languageId).then(fetch).then(function (response) {
            return response.text();
          }).then(this._insertUserNameFields.bind(this)).then(this._cleanUp.bind(this)).catch(this._handleError.bind(this));
        }
        /**
         * Caches the values and maxLength attribute values from the current
         * user name fields.
         *
         * @protected
         */

      }, {
        key: "_cacheData",
        value: function _cacheData() {
          var _this = this;

          var formData = new FormData(this.formNode);

          if (!formData.forEach) {
            return;
          }

          formData.forEach(function (value, name) {
            var field = _this.userNameFieldsNode.querySelector('#' + name);

            if (field) {
              _this._formDataCache[name] = value;

              if (field.hasAttribute('maxLength')) {
                _this._maxLengthsCache[name] = field.getAttribute('maxLength');
              }
            }
          });
        }
        /**
         * Inserts a loading indicator before the user name fields and hide
         * the user name fields.
         *
         * @protected
         */

      }, {
        key: "_createLoadingIndicator",
        value: function _createLoadingIndicator() {
          this.userNameFieldsNode.insertAdjacentHTML('beforebegin', this._loadingAnimationMarkupText);

          _metalDom.default.addClasses(this.userNameFieldsNode, 'hide');
        }
      }, {
        key: "_cleanUp",
        value: function _cleanUp() {
          this._removeLoadingIndicator();

          this._populateData();
        }
        /**
         * Returns a promise containing the URL to be used to retrieve the user
         * name fields.
         *
         * @param {string} languageId The language id to be set on the URL.
         * @protected
         * @return {Promise} A promise to be resolved with the constructed URL
         */

      }, {
        key: "_getURL",
        value: function _getURL(languageId) {
          var _this2 = this;

          return new Promise(function (resolve) {
            var url = (0, _frontendJsWeb.createPortletURL)(_this2.baseURL, {
              languageId: languageId
            });
            resolve(url);
          });
        }
        /**
         * Logs any error in the promise chain and removes the loading indicator.
         *
         * @param {Error} error The error object
         * @protected
         */

      }, {
        key: "_handleError",
        value: function _handleError(error) {
          console.error(error);

          this._removeLoadingIndicator();
        }
        /**
         * Handles the change event when selecting a new language.
         *
         * @param {Event} event The event object.
         * @protected
         */

      }, {
        key: "_handleSelectChange",
        value: function _handleSelectChange(event) {
          this.updateUserNameFields(event.currentTarget.value);
        }
        /**
         * Replaces the HTML of the user name fields with the given HTML.
         *
         * @param {string} markupText The markup text used to create and insert the
         * new user name fields.
         * @protected
         */

      }, {
        key: "_insertUserNameFields",
        value: function _insertUserNameFields(markupText) {
          var temp = document.implementation.createHTMLDocument('');
          temp.body.innerHTML = markupText;
          var newUserNameFields = temp.getElementById("".concat(this.portletNamespace, "userNameFields"));

          if (newUserNameFields) {
            this.userNameFieldsNode.innerHTML = newUserNameFields.innerHTML;
          }
        }
        /**
         * Sets the values and maxLength attributes of the current user name fields
         * with the data cached in this._cacheData.
         *
         * @protected
         */

      }, {
        key: "_populateData",
        value: function _populateData() {
          var _this3 = this;

          var entries = Object.entries(this._formDataCache);
          entries.forEach(function (_ref) {
            var _ref2 = _slicedToArray(_ref, 2),
                name = _ref2[0],
                value = _ref2[1];

            var newField = _this3.userNameFieldsNode.querySelector('#' + name);

            if (newField) {
              newField.value = value;

              if (Object.hasOwnProperty.call(_this3._maxLengthsCache, name)) {
                newField.setAttribute('maxLength', _this3._maxLengthsCache[name]);
              }
            }
          });
        }
        /**
         * Removes the loading indicator and shows the user name
         * fields.
         *
         * @protected
         */

      }, {
        key: "_removeLoadingIndicator",
        value: function _removeLoadingIndicator() {
          _metalDom.default.exitDocument(this.one('#loadingUserNameFields'));

          _metalDom.default.removeClasses(this.userNameFieldsNode, 'hide');
        }
        /**
         * Stores the current user name fields data and creates the loading
         * indicator
         *
         * @protected
         */

      }, {
        key: "_setUp",
        value: function _setUp() {
          this._cacheData();

          this._createLoadingIndicator();
        }
      }]);

      return UserNameFields;
    }(_frontendJsWeb.PortletBase);

    UserNameFields.STATE = {
      /**
       * Uri to return the user name data.
       * @instance
       * @memberof UserNameFields
       * @type {String}
       */
      baseURL: _metalState.Config.required().string().writeOnce(),

      /**
       * Form node.
       * @instance
       * @memberof UserNameFields
       * @type {String}
       */
      formNode: _metalState.Config.required().setter(_metalDom.default.toElement).writeOnce(),

      /**
       * Language id select field.
       * @instance
       * @memberof UserNameFields
       * @type {String}
       */
      languageIdSelectNode: _metalState.Config.required().setter(_metalDom.default.toElement).writeOnce(),

      /**
       * HTML element containing the user name fields.
       * @instance
       * @memberof UserNameFields
       * @type {String}
       */
      userNameFieldsNode: _metalState.Config.required().setter(_metalDom.default.toElement).writeOnce()
    };
    var _default = UserNameFields;
    exports.default = _default;
    //# sourceMappingURL=UserNameFields.es.js.map
  }
});
//# sourceMappingURL=UserNameFields.es.js.map