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

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

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

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

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

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

    var _Observer = _interopRequireDefault(require("./Observer.es"));

    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 _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 _extends() {
      _extends = Object.assign || function (target) {
        for (var i = 1; i < arguments.length; i++) {
          var source = arguments[i];for (var key in source) {
            if (Object.prototype.hasOwnProperty.call(source, key)) {
              target[key] = source[key];
            }
          }
        }return target;
      };return _extends.apply(this, arguments);
    }

    function _objectWithoutProperties(source, excluded) {
      if (source == null) return {};var target = _objectWithoutPropertiesLoose(source, excluded);var key, i;if (Object.getOwnPropertySymbols) {
        var sourceSymbolKeys = Object.getOwnPropertySymbols(source);for (i = 0; i < sourceSymbolKeys.length; i++) {
          key = sourceSymbolKeys[i];if (excluded.indexOf(key) >= 0) continue;if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;target[key] = source[key];
        }
      }return target;
    }

    function _objectWithoutPropertiesLoose(source, excluded) {
      if (source == null) return {};var target = {};var sourceKeys = Object.keys(source);var key, i;for (i = 0; i < sourceKeys.length; i++) {
        key = sourceKeys[i];if (excluded.indexOf(key) >= 0) continue;target[key] = source[key];
      }return target;
    }

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

    var CONFIG_BLACKLIST = ['children', 'events', 'ref', 'visible'];
    var CONFIG_DEFAULT = ['displayErrors'];
    /**
     * The Adapter creates a communication bridge between the Metal and React components.
     * The Adapter when it is rendered for the first time uses `ReactDOM.render` to assemble
     * the component and subsequent renderings are done by React. We created a tunnel with
     * an Observer that updates the internal state of the component in React that makes a
     * wrapper over the main component to force React to render at the best time, we also
     * ignore the rendering of Metal.
     *
     * @example
     * // import getConnectedReactComponentAdapter from '/path/ReactComponentAdapter.es';
     * //
     * // const ReactComponent = ({children, className}) => <div className={className}>{children}</div>;
     * // const ReactComponentAdapter = getConnectedReactComponentAdapter(
     * //   ReactComponent
     * // );
     * //
     * // In the rendering of Metal
     * // render() {
     * //	return (
     * //		<ReactComponentAdapter className="h1-title">
     * //			<h1>{'Title'}</h1>
     * //		</ReactComponentAdapter>
     * //	);
     * // }
     *
     * To call the React component in the context of Metal + soy, where varient is not an option,
     * you can use Metal's `Soy.register` to create a fake component so that you can call the React
     * component in Soy. The use of children from Soy components for React does not work.
     *
     * @example
     * // import Soy from 'metal-soy';
     * // import getConnectedReactComponentAdapter from '/path/ReactComponentAdapter.es';
     * // import templates from './FakeAdapter.soy';
     * //
     * // const ReactComponent = ({className}) => <div className={className} />;
     * // const ReactComponentAdapter = getConnectedReactComponentAdapter(
     * //   ReactComponent
     * // );
     * // Soy.register(ReactComponentAdapter, templates);
     * //
     * // In soy
     * // {call FakeAdapter.render}
     * //	{param className: 'test' /}
     * // {/call}
     *
     * @param {React.createElement} ReactComponent
     */

    function getConnectedReactComponentAdapter(ReactComponent) {
      var ReactComponentAdapter = /*#__PURE__*/function (_JSXComponent) {
        _inherits(ReactComponentAdapter, _JSXComponent);

        /**
         * For Metal to track config changes, we need to config the state so
         * that willReceiveProps is called as expected.
         */
        function ReactComponentAdapter(config, parentElement) {
          var _this;

          _classCallCheck(this, ReactComponentAdapter);

          var props = {};
          Object.keys(config).concat(CONFIG_DEFAULT).forEach(function (key) {
            if (!CONFIG_BLACKLIST.includes(key)) {
              props[key] = _metalState.Config.any().value(config[key]);
            }
          });
          _this = _possibleConstructorReturn(this, _getPrototypeOf(ReactComponentAdapter).call(this, config, parentElement));

          var data = _metalJsx.default.DATA_MANAGER.getManagerData(_assertThisInitialized(_this));

          data.props_.configState(_objectSpread(_objectSpread({}, _metalJsx.default.DATA), props));
          return _this;
        }

        _createClass(ReactComponentAdapter, [{
          key: "created",
          value: function created() {
            this.observer = new _Observer.default();
            this.reactComponentRef = /*#__PURE__*/_react.default.createRef();
          }
        }, {
          key: "disposed",
          value: function disposed() {
            if (this.instance_) {
              _reactDom.default.unmountComponentAtNode(this.instance_);

              this.instance_ = null;
            }
          }
        }, {
          key: "willReceiveProps",
          value: function willReceiveProps(changes) {
            // Delete the events and children properties to make it easier to
            // check which values have been changed, events and children are
            // properties that are changing all the time when new renderings
            // happen, a new reference is created all the time.
            delete changes.events;
            delete changes.children;

            if (changes && Object.keys(changes).length > 0) {
              var newValues = {};
              var keys = Object.keys(changes);
              keys.forEach(function (key) {
                if (!CONFIG_BLACKLIST.includes(key)) {
                  newValues[key] = changes[key].newVal;
                }
              });
              this.observer.dispatch(newValues);
            }
          }
          /**
           * Disable Metal rendering and let React render in the best
           * possible way.
           */

        }, {
          key: "shouldUpdate",
          value: function shouldUpdate() {
            return false;
          }
        }, {
          key: "syncVisible",
          value: function syncVisible(value) {
            this.observer.dispatch({
              visible: value
            });
          }
        }, {
          key: "render",
          value: function render() {
            var _this$props = this.props,
                events = _this$props.events,
                ref = _this$props.ref,
                store = _this$props.store,
                otherProps = _objectWithoutProperties(_this$props, ["events", "ref", "store"]);
            /* eslint-disable no-undef */

            IncrementalDOM.elementOpen('div', ref, [], 'class', 'react-component-adapter');
            var element = IncrementalDOM.currentElement();
            IncrementalDOM.skip();
            IncrementalDOM.elementClose('div');
            /* eslint-enable no-undef */
            // eslint-disable-next-line @liferay/portal/no-react-dom-render

            _reactDom.default.render( /*#__PURE__*/_react.default.createElement(ObserverSubscribe, {
              observer: this.observer
            }, /*#__PURE__*/_react.default.createElement(ReactComponent, _extends({}, otherProps, events, store, {
              instance: this,
              ref: this.reactComponentRef
            }))), element);

            this.instance_ = element;
          }
        }]);

        return ReactComponentAdapter;
      }(_metalJsx.default);

      ReactComponentAdapter.RENDERER = _metalIncrementalDom.default;
      return ReactComponentAdapter;
    }
    /**
     * Adds a sub observer to maintain the updated state of the
     * component.
     */

    var ObserverSubscribe = function ObserverSubscribe(_ref) {
      var children = _ref.children,
          observer = _ref.observer;

      var _useState = (0, _react.useState)({}),
          _useState2 = _slicedToArray(_useState, 2),
          state = _useState2[0],
          setState = _useState2[1];

      (0, _react.useEffect)(function () {
        var change = function change(value) {
          return setState(_objectSpread(_objectSpread({}, state), value));
        };

        observer.subscribe(change);
        return function () {
          observer.unsubscribe(change);
        };
      }, [state, setState, observer]);
      return (/*#__PURE__*/_react.default.cloneElement(children, _objectSpread(_objectSpread({}, children.props), state))
      );
    };

    var _default = getConnectedReactComponentAdapter;
    exports.default = _default;
    //# sourceMappingURL=ReactComponentAdapter.es.js.map
  }
});
//# sourceMappingURL=ReactComponentAdapter.es.js.map