Liferay.Loader.define("dynamic-data-mapping-form-renderer@5.0.66/js/components/Field/Field.es", ['module', 'exports', 'require', './Field.scss', '@frontend-taglib-clay$clayui/button', '@frontend-taglib-clay$clayui/loading-indicator', 'dynamic-data-mapping-form-field-type/util/strings.es', 'frontend-js-metal-web$metal-component', 'frontend-js-react-web$react', '../../hooks/usePage.es', '../../hooks/useStorage.es', '../AutoFocus.es', '../ErrorBoundary.es', './MetalComponentAdapter.es', './ParentFieldContext.es'], function (module, exports, require) {
  var define = undefined;
  var global = window;
  {
    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);
    }

    Object.defineProperty(exports, "__esModule", {
      value: true
    });
    exports.Field = void 0;

    require("./Field.scss");

    var _button = _interopRequireDefault(require("@frontend-taglib-clay$clayui/button"));

    var _loadingIndicator = _interopRequireDefault(require("@frontend-taglib-clay$clayui/loading-indicator"));

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

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

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

    var _usePage2 = require("../../hooks/usePage.es");

    var _useStorage2 = require("../../hooks/useStorage.es");

    var _AutoFocus = require("../AutoFocus.es");

    var _ErrorBoundary = require("../ErrorBoundary.es");

    var _MetalComponentAdapter = require("./MetalComponentAdapter.es");

    var _ParentFieldContext = require("./ParentFieldContext.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 _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");
      }
    }

    var getModule = function getModule(fieldTypes, fieldType) {
      var field = fieldTypes.find(function (field) {
        return field.name === fieldType;
      });
      return field;
    };

    var load = function load(fieldModule) {
      return new Promise(function (resolve, reject) {
        Liferay.Loader.require([fieldModule], function (Field) {
          return resolve(Field);
        }, function (error) {
          return reject({
            error: error,
            network: true
          });
        });
      });
    };

    var useLazy = function useLazy() {
      var _useStorage = (0, _useStorage2.useStorage)(),
          components = _useStorage.components;

      return (0, _react.useCallback)(function (fieldModule) {
        if (!components.has(fieldModule)) {
          var Component = /*#__PURE__*/(0, _react.lazy)(function () {
            return load(fieldModule).then(function (instance) {
              if (!(instance && instance.default)) {
                return null;
              } // To maintain compatibility with fields in Metal+Soy,
              // we call the bridge component to handle this component.


              if (_metalComponent.default.isComponentCtor(instance.default)) {
                return {
                  default: _MetalComponentAdapter.MetalComponentAdapter
                };
              }

              return instance;
            }).catch(function (error) {
              components.delete(fieldModule);
              throw error;
            });
          });
          components.set(fieldModule, Component);
        }

        return components.get(fieldModule);
      }, [components]);
    };

    var FieldEventStruct = function FieldEventStruct(event, field) {
      var _event$target;

      var value = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;

      _classCallCheck(this, FieldEventStruct);

      this.fieldInstance = _objectSpread(_objectSpread({}, field), {}, {
        // This is a fake function that maintains compatibility with the use
        // of Metal+Soy fields.
        isDisposed: function isDisposed() {
          return false;
        }
      });
      this.originalEvent = event;
      this.value = value !== null ? value : event === null || event === void 0 ? void 0 : (_event$target = event.target) === null || _event$target === void 0 ? void 0 : _event$target.value;
    };
    /**
     * This only assembles the expected structure of the Forms field
     * event, creates a makeup to maintain compatibility with the
     * mechanism, the fields in React do not need to assemble this
     * structure, they must only provide a native event or value in
     * the case of an onChange
     */

    var mountStruct = function mountStruct(event, field, value) {
      // A field event struct may have been declared before, for cases of nested
      // fields with the FieldSet field.
      if (event instanceof FieldEventStruct) {
        return event;
      }

      return new FieldEventStruct(event, field, value);
    };

    var FieldLazy = function FieldLazy(_ref) {
      var field = _ref.field,
          fieldTypes = _ref.fieldTypes,
          _onBlur = _ref.onBlur,
          _onChange = _ref.onChange,
          _onFocus = _ref.onFocus,
          otherProps = _objectWithoutProperties(_ref, ["field", "fieldTypes", "onBlur", "onChange", "onFocus"]);

      var focusDurationRef = (0, _react.useRef)({
        end: null,
        start: null
      });

      var _getModule = getModule(fieldTypes, field.type),
          _getModule$configurat = _getModule.configuration,
          configuration = _getModule$configurat === void 0 ? {} : _getModule$configurat,
          javaScriptModule = _getModule.javaScriptModule;

      var ComponentLazy = useLazy()(javaScriptModule);
      return (/*#__PURE__*/_react.default.createElement(ComponentLazy, _extends({
          onBlur: function onBlur(event) {
            focusDurationRef.current.end = new Date();

            _onBlur(mountStruct(event, field), focusDurationRef.current);
          },
          onChange: function onChange(event, value) {
            return _onChange(mountStruct(event, field, value));
          },
          onFocus: function onFocus(event) {
            focusDurationRef.current.start = new Date();

            _onFocus(mountStruct(event, field));
          },
          visible: true
        }, field, otherProps, configuration))
      );
    };

    var getRootParentField = function getRootParentField(field, _ref2) {
      var root = _ref2.root;

      if (root) {
        return _objectSpread(_objectSpread({}, field), {}, {
          root: root
        });
      }

      return _objectSpread(_objectSpread({}, field), {}, {
        root: field
      });
    };

    var Field = function Field(_ref3) {
      var field = _ref3.field,
          otherProps = _objectWithoutProperties(_ref3, ["field"]);

      var parentField = (0, _react.useContext)(_ParentFieldContext.ParentFieldContext);

      var _usePage = (0, _usePage2.usePage)(),
          fieldTypes = _usePage.fieldTypes;

      var _useState = (0, _react.useState)(),
          _useState2 = _slicedToArray(_useState, 2),
          hasError = _useState2[0],
          setHasError = _useState2[1];

      if (!fieldTypes) {
        return (/*#__PURE__*/_react.default.createElement(_loadingIndicator.default, null)
        );
      }

      if (hasError) {
        return (/*#__PURE__*/_react.default.createElement("div", {
            className: "ddm-field-renderer--error"
          }, /*#__PURE__*/_react.default.createElement("p", {
            className: "ddm-field-renderer--title"
          }, (0, _strings.sub)(Liferay.Language.get('there-was-an-error-when-loading-the-x-field'), [field.type])), hasError.network && /*#__PURE__*/_react.default.createElement(_button.default, {
            className: "ddm-field-renderer--button",
            displayType: "secondary",
            onClick: function onClick() {
              return setHasError(false);
            },
            small: true
          }, Liferay.Language.get('refresh')))
        );
      }

      return (/*#__PURE__*/_react.default.createElement(_ErrorBoundary.ErrorBoundary, {
          onError: setHasError
        }, /*#__PURE__*/_react.default.createElement(_AutoFocus.AutoFocus, null, /*#__PURE__*/_react.default.createElement("div", {
          className: "ddm-field",
          "data-field-name": field.fieldName
        }, /*#__PURE__*/_react.default.createElement(_react.Suspense, {
          fallback: /*#__PURE__*/_react.default.createElement(_loadingIndicator.default, null)
        }, /*#__PURE__*/_react.default.createElement(_ParentFieldContext.ParentFieldContext.Provider, {
          value: getRootParentField(field, parentField)
        }, /*#__PURE__*/_react.default.createElement(FieldLazy, _extends({
          field: field,
          fieldTypes: fieldTypes
        }, otherProps)))))))
      );
    };

    exports.Field = Field;
    //# sourceMappingURL=Field.es.js.map
  }
});
//# sourceMappingURL=Field.es.js.map