Liferay.Loader.define("layout-content-page-editor-web@2.0.157/page_editor/app/components/UnsafeHTML", ['module', 'exports', 'require', 'frontend-js-react-web$prop-types', 'frontend-js-react-web$react', 'frontend-js-react-web$react-dom', '../../common/components/RawDOM'], function (module, exports, require) {
  var define = undefined;
  var global = window;
  {
    Object.defineProperty(exports, "__esModule", {
      value: true
    });
    exports.default = void 0;

    var _propTypes = _interopRequireDefault(require("frontend-js-react-web$prop-types"));

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

    var _reactDom = _interopRequireDefault(require("frontend-js-react-web$react-dom"));

    var _RawDOM = _interopRequireDefault(require("../../common/components/RawDOM"));

    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 _getPrototypeOf(o) {
      _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
        return o.__proto__ || Object.getPrototypeOf(o);
      };return _getPrototypeOf(o);
    }

    function _assertThisInitialized(self) {
      if (self === void 0) {
        throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
      }return self;
    }

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

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

    /**
     * DOM node which will be manually updated and injects
     * React.portals into it.
     */
    var UnsafeHTML = /*#__PURE__*/function (_React$PureComponent) {
      _inherits(UnsafeHTML, _React$PureComponent);

      function UnsafeHTML(props) {
        var _this;

        _classCallCheck(this, UnsafeHTML);

        _this = _possibleConstructorReturn(this, _getPrototypeOf(UnsafeHTML).call(this, props));

        _defineProperty(_assertThisInitialized(_this), "_updateRef", function (nextRef) {
          if (typeof _this.props.contentRef === 'function') {
            _this.props.contentRef(nextRef);
          } else if (_this.props.contentRef) {
            _this.props.contentRef.current = nextRef;
          }

          _this.setState(function (_ref) {
            var prevRef = _ref.ref;

            if (prevRef !== nextRef) {
              return {
                portals: [],
                ref: nextRef
              };
            }

            return null;
          });
        });

        _this.state = {
          portals: [],
          ref: null
        };
        return _this;
      }

      _createClass(UnsafeHTML, [{
        key: "componentDidUpdate",
        value: function componentDidUpdate(prevProps) {
          if (this.state.ref) {
            this._syncRefProps();

            if (!this.state.ref.childNodes.length && this.props.markup || prevProps.markup !== this.props.markup) {
              this._syncRefContent();
            }
          }
        }
        /**
         * Looks for script tags inside ref and executes
         * them inside this.props.globalContext.
         */

      }, {
        key: "_runRefScripts",
        value: function _runRefScripts() {
          var doc = this.props.globalContext.document;
          var scriptElements = Array.from(this.state.ref.querySelectorAll('script')).filter(function (script) {
            return !script.type || script.type === 'module' || script.type === 'text/javascript';
          });

          (function runNextScript() {
            if (scriptElements.length) {
              var nextScriptElement = doc.createElement('script');
              var prevScriptElement = scriptElements.shift();
              nextScriptElement.type = prevScriptElement.type;

              if (prevScriptElement.src) {
                nextScriptElement.src = prevScriptElement.src;
              } else {
                nextScriptElement.appendChild(doc.createTextNode(prevScriptElement.innerHTML));
              }

              prevScriptElement.parentNode.replaceChild(nextScriptElement, prevScriptElement);
              requestAnimationFrame(runNextScript);
            }
          })();
        }
        /**
         * Syncs ref innerHTML and recreates portals.
         *
         * Everytime that markup property is updated ref innerHTML
         * needs to be updated and portals need to be recreated because
         * DOM nodes references will change.
         */

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

          var ref = this.state.ref;
          ref.innerHTML = this.props.markup;
          var portals = this.props.getPortals(ref);

          if (portals.length || portals.length !== this.state.portals.length) {
            this.setState({
              portals: portals
            }, function () {
              _this2._runRefScripts();

              _this2.props.onRender(ref);
            });
          } else {
            this._runRefScripts();

            this.props.onRender(ref);
          }
        }
        /**
         * Syncs non-critical properties to ref.
         *
         * If there is some property change we can safely update
         * ref DOM properties without making more changes.
         */

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

          var ref = this.state.ref;

          if (this.props.className) {
            ref.className = this.props.className;
          } else {
            ref.removeAttribute('class');
          }

          if (this.props.data) {
            Object.entries(this.props.data).forEach(function (_ref2) {
              var _ref3 = _slicedToArray(_ref2, 2),
                  key = _ref3[0],
                  value = _ref3[1];

              ref.dataset[key] = value;
            });
          }

          if (this.props.id) {
            ref.id = this.props.id;
          } else {
            ref.removeAttribute('id');
          }

          ref.removeAttribute('style');
          Object.keys(this.props.style).forEach(function (key) {
            ref.style[key] = _this3.props.style[key];
          });
        }
        /**
         * Updates internal state.ref and reset state.portals.
         *
         * If the ref changes for any reason we need to remove all our
         * portals to prevent them from failing because their DOM nodes
         * are not linked to the document anymore.
         */

      }, {
        key: "render",
        value: function render() {
          return (/*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_RawDOM.default, {
              TagName: this.props.TagName,
              elementRef: this._updateRef
            }), this.state.portals.map(function (_ref4) {
              var Component = _ref4.Component,
                  element = _ref4.element;
              return (/*#__PURE__*/_reactDom.default.createPortal( /*#__PURE__*/_react.default.createElement(Component, null), element)
              );
            }))
          );
        }
      }]);

      return UnsafeHTML;
    }(_react.default.PureComponent);

    exports.default = UnsafeHTML;
    UnsafeHTML.defaultProps = {
      TagName: 'div',
      className: '',
      contentRef: null,
      getPortals: function getPortals() {
        return [];
      },
      globalContext: {
        document: document,
        window: window
      },
      markup: '',
      onRender: function onRender() {},
      style: {}
    };
    //# sourceMappingURL=UnsafeHTML.js.map
  }
});
//# sourceMappingURL=UnsafeHTML.js.map