Liferay.Loader.define("layout-content-page-editor-web@2.0.75/page_editor/common/components/MappingSelector", ['module', 'exports', 'require', '@frontend-taglib-clay$clayui/form', 'frontend-js-react-web$classnames', 'frontend-js-react-web$prop-types', 'frontend-js-react-web$react', '../../app/actions/index', '../../app/components/CollectionItemContext', '../../app/config/constants/editableTypes', '../../app/config/constants/layoutTypes', '../../app/config/index', '../../app/services/CollectionService', '../../app/services/InfoItemService', '../../app/store/index', '../../app/utils/isMapped', '../../app/utils/useId', './ItemSelector'], 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["default"] = _default;

    var _form = _interopRequireWildcard(require("@frontend-taglib-clay$clayui/form"));

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

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

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

    var _index = require("../../app/actions/index");

    var _CollectionItemContext = require("../../app/components/CollectionItemContext");

    var _editableTypes = require("../../app/config/constants/editableTypes");

    var _layoutTypes = require("../../app/config/constants/layoutTypes");

    var _index2 = require("../../app/config/index");

    var _CollectionService = _interopRequireDefault(require("../../app/services/CollectionService"));

    var _InfoItemService = _interopRequireDefault(require("../../app/services/InfoItemService"));

    var _index3 = require("../../app/store/index");

    var _isMapped = _interopRequireDefault(require("../../app/utils/isMapped"));

    var _useId = require("../../app/utils/useId");

    var _ItemSelector = _interopRequireDefault(require("./ItemSelector"));

    function _interopRequireDefault(obj) {
      return obj && obj.__esModule ? obj : { "default": obj };
    }

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

    var MAPPING_SOURCE_TYPE_IDS = {
      content: 'content',
      structure: 'structure'
    };
    var UNMAPPED_OPTION = {
      label: "-- ".concat(Liferay.Language.get('unmapped'), " --"),
      value: 'unmapped'
    };

    function loadFields(_ref) {
      var dispatch = _ref.dispatch,
          fieldType = _ref.fieldType,
          selectedItem = _ref.selectedItem,
          selectedMappingTypes = _ref.selectedMappingTypes,
          selectedSourceTypeId = _ref.selectedSourceTypeId;
      var promise;

      if (selectedSourceTypeId === MAPPING_SOURCE_TYPE_IDS.structure) {
        promise = _InfoItemService["default"].getAvailableStructureMappingFields({
          classNameId: selectedMappingTypes.type.id,
          classTypeId: selectedMappingTypes.subtype.id,
          fieldType: fieldType,
          onNetworkStatus: dispatch
        });
      } else if (selectedSourceTypeId === MAPPING_SOURCE_TYPE_IDS.content && selectedItem.classNameId && selectedItem.classPK) {
        promise = _InfoItemService["default"].getAvailableInfoItemMappingFields({
          classNameId: selectedItem.classNameId,
          classPK: selectedItem.classPK,
          fieldType: fieldType,
          onNetworkStatus: dispatch
        });
      }

      if (promise) {
        return promise.then(function (response) {
          if (Array.isArray(response)) {
            return response;
          }

          return [];
        });
      }

      return Promise.resolve(null);
    }

    function _default(_ref2) {
      var fieldType = _ref2.fieldType,
          mappedItem = _ref2.mappedItem,
          onMappingSelect = _ref2.onMappingSelect;
      var collectionConfig = (0, _CollectionItemContext.useCollectionConfig)();

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

      var _useState3 = (0, _react.useState)(''),
          _useState4 = _slicedToArray(_useState3, 2),
          collectionItemSubtypeLabel = _useState4[0],
          setCollectionItemSubtypeLabel = _useState4[1];

      var _useState5 = (0, _react.useState)(''),
          _useState6 = _slicedToArray(_useState5, 2),
          collectionItemTypeLabel = _useState6[0],
          setCollectionItemTypeLabel = _useState6[1];

      (0, _react.useEffect)(function () {
        if (!collectionConfig) {
          setCollectionFieldSets([]);
          return;
        }

        _CollectionService["default"].getCollectionMappingFields({
          fieldType: fieldType,
          itemSubtype: collectionConfig.collection.itemSubtype || '',
          itemType: collectionConfig.collection.itemType,
          onNetworkStatus: function onNetworkStatus() {}
        }).then(function (response) {
          setCollectionFieldSets(response.mappingFields);
          setCollectionItemSubtypeLabel(response.itemSubtypeLabel);
          setCollectionItemTypeLabel(response.itemTypeLabel);
        })["catch"](function (error) {});
      }, [collectionConfig, fieldType]);
      return collectionConfig ? _react["default"].createElement(_react["default"].Fragment, null, collectionItemTypeLabel && _react["default"].createElement("p", {
        className: "mb-2 page-editor__mapping-panel__type-label"
      }, _react["default"].createElement("span", {
        className: "mr-1"
      }, Liferay.Language.get('item-type'), ":"), collectionItemTypeLabel), collectionItemSubtypeLabel && _react["default"].createElement("p", {
        className: "mb-2 page-editor__mapping-panel__type-label"
      }, _react["default"].createElement("span", {
        className: "mr-1"
      }, Liferay.Language.get('item-subtype'), ":"), collectionItemSubtypeLabel), _react["default"].createElement(MappingFieldSelect, {
        fieldSets: collectionFieldSets,
        fieldType: fieldType,
        onValueSelect: function onValueSelect(event) {
          if (event.target.value === UNMAPPED_OPTION.value) {
            onMappingSelect({
              collectionFieldId: ''
            });
          } else {
            onMappingSelect({
              collectionFieldId: event.target.value
            });
          }
        },
        value: mappedItem.collectionFieldId
      })) : _react["default"].createElement(MappingSelector, {
        fieldType: fieldType,
        mappedItem: mappedItem,
        onMappingSelect: onMappingSelect
      });
    }

    function MappingSelector(_ref3) {
      var fieldType = _ref3.fieldType,
          mappedItem = _ref3.mappedItem,
          onMappingSelect = _ref3.onMappingSelect;
      var dispatch = (0, _index3.useDispatch)();
      var mappedInfoItems = (0, _index3.useSelector)(function (state) {
        return state.mappedInfoItems;
      });
      var mappingSelectorSourceSelectId = (0, _useId.useId)();
      var selectedMappingTypes = _index2.config.selectedMappingTypes;

      var _useState7 = (0, _react.useState)(null),
          _useState8 = _slicedToArray(_useState7, 2),
          fieldSets = _useState8[0],
          setFieldSets = _useState8[1];

      var _useState9 = (0, _react.useState)(mappedItem),
          _useState10 = _slicedToArray(_useState9, 2),
          selectedItem = _useState10[0],
          setSelectedItem = _useState10[1];

      var _useState11 = (0, _react.useState)(mappedItem.mappedField || _index2.config.layoutType === _layoutTypes.LAYOUT_TYPES.display ? MAPPING_SOURCE_TYPE_IDS.structure : MAPPING_SOURCE_TYPE_IDS.content),
          _useState12 = _slicedToArray(_useState11, 2),
          selectedSourceTypeId = _useState12[0],
          setSelectedSourceTypeId = _useState12[1];

      (0, _react.useEffect)(function () {
        var infoItem = mappedInfoItems.find(function (infoItem) {
          return infoItem.classNameId === mappedItem.classNameId && infoItem.classPK === mappedItem.classPK;
        });
        setSelectedItem(function (selectedItem) {
          return _objectSpread({}, infoItem, {}, mappedItem, {}, selectedItem);
        });
      }, [mappedItem, mappedInfoItems, setSelectedItem]);
      (0, _react.useEffect)(function () {
        var data = selectedSourceTypeId === MAPPING_SOURCE_TYPE_IDS.structure ? {
          dispatch: dispatch,
          fieldType: fieldType,
          selectedMappingTypes: selectedMappingTypes,
          selectedSourceTypeId: selectedSourceTypeId
        } : {
          dispatch: dispatch,
          fieldType: fieldType,
          selectedItem: selectedItem,
          selectedSourceTypeId: selectedSourceTypeId
        };
        loadFields(data).then(function (newFieldSets) {
          setFieldSets(newFieldSets);
        });
      }, [dispatch, fieldType, selectedItem, selectedMappingTypes, selectedSourceTypeId]);
      return _react["default"].createElement(_react["default"].Fragment, null, _index2.config.layoutType === _layoutTypes.LAYOUT_TYPES.display && _react["default"].createElement(_form["default"].Group, {
        small: true
      }, _react["default"].createElement("label", {
        htmlFor: "mappingSelectorSourceSelect"
      }, Liferay.Language.get('source')), _react["default"].createElement(_form.ClaySelectWithOption, {
        "aria-label": Liferay.Language.get('source'),
        className: "pr-4 text-truncate",
        id: mappingSelectorSourceSelectId,
        onChange: function onChange(event) {
          setSelectedSourceTypeId(event.target.value);
          setSelectedItem({});

          if ((0, _isMapped["default"])(mappedItem)) {
            onMappingSelect({
              classNameId: '',
              classPK: '',
              fieldId: '',
              mappedField: ''
            });
          }
        },
        options: [{
          label: Liferay.Util.sub(Liferay.Language.get('x-default'), selectedMappingTypes.subtype ? selectedMappingTypes.subtype.label : selectedMappingTypes.type.label),
          value: MAPPING_SOURCE_TYPE_IDS.structure
        }, {
          label: Liferay.Language.get('specific-content'),
          value: MAPPING_SOURCE_TYPE_IDS.content
        }],
        value: selectedSourceTypeId
      })), selectedSourceTypeId === MAPPING_SOURCE_TYPE_IDS.content && _react["default"].createElement(_form["default"].Group, {
        small: true
      }, _react["default"].createElement(_ItemSelector["default"], {
        label: Liferay.Language.get('content'),
        onItemSelect: function onInfoItemSelect(selectedInfoItem) {
          setSelectedItem(selectedInfoItem);

          if ((0, _isMapped["default"])(mappedItem)) {
            onMappingSelect({
              className: '',
              classNameId: '',
              classPK: '',
              fieldId: '',
              mappedField: ''
            });
          }
        },
        selectedItemTitle: selectedItem.title
      })), _react["default"].createElement(_form["default"].Group, {
        small: true
      }, _react["default"].createElement(MappingFieldSelect, {
        fieldSets: fieldSets,
        fieldType: fieldType,
        onValueSelect: function onFieldSelect(event) {
          var fieldValue = event.target.value;
          var data = fieldValue === UNMAPPED_OPTION.value ? {
            className: '',
            classNameId: '',
            classPK: '',
            fieldId: '',
            mappedField: ''
          } : selectedSourceTypeId === MAPPING_SOURCE_TYPE_IDS.content ? {
            className: selectedItem.className,
            classNameId: selectedItem.classNameId,
            classPK: selectedItem.classPK,
            fieldId: fieldValue
          } : {
            mappedField: fieldValue
          };

          if (selectedSourceTypeId === MAPPING_SOURCE_TYPE_IDS.content) {
            var mappedInfoItem = mappedInfoItems.find(function (item) {
              return item.classNameId === selectedItem.classNameId && item.classPK === selectedItem.classPK;
            });

            if (!mappedInfoItem) {
              dispatch((0, _index.addMappedInfoItem)(_objectSpread({
                title: selectedItem.title
              }, data)));
            }

            setSelectedItem(function (selectedItem) {
              return _objectSpread({}, selectedItem, {
                fieldId: fieldValue
              });
            });
          } else {
            setSelectedItem(function (selectedItem) {
              return _objectSpread({}, selectedItem, {
                mappedField: fieldValue
              });
            });
          }

          onMappingSelect(data);
        },
        value: selectedItem.mappedField || selectedItem.fieldId
      })));
    }

    function MappingFieldSelect(_ref4) {
      var fieldSets = _ref4.fieldSets,
          fieldType = _ref4.fieldType,
          onValueSelect = _ref4.onValueSelect,
          value = _ref4.value;
      var mappingSelectorFieldSelectId = (0, _useId.useId)();
      var hasWarnings = fieldSets && fieldSets.length === 0;
      return _react["default"].createElement(_form["default"].Group, {
        className: (0, _classnames["default"])({
          'has-warning': hasWarnings
        }),
        small: true
      }, _react["default"].createElement("label", {
        htmlFor: "mappingSelectorFieldSelect"
      }, Liferay.Language.get('field')), _react["default"].createElement(_form.ClaySelect, {
        "aria-label": Liferay.Language.get('field'),
        disabled: !(fieldSets && fieldSets.length),
        id: mappingSelectorFieldSelectId,
        onChange: onValueSelect,
        value: value
      }, fieldSets && fieldSets.length && _react["default"].createElement(_react["default"].Fragment, null, _react["default"].createElement(_form.ClaySelect.Option, {
        label: UNMAPPED_OPTION.label,
        value: UNMAPPED_OPTION.value
      }), fieldSets.map(function (fieldSet, index) {
        var key = "".concat(fieldSet.label || '').concat(index);

        return _react["default"].createElement(function Wrapper(_ref5) {
          var children = _ref5.children,
              props = _objectWithoutProperties(_ref5, ["children"]);

          return fieldSet.label ? _react["default"].createElement(_form.ClaySelect.OptGroup, props, children) : _react["default"].createElement(_react["default"].Fragment, {
            key: key
          }, children);
        }, {
          key: key,
          label: fieldSet.label
        }, fieldSet.fields.map(function (field) {
          return _react["default"].createElement(_form.ClaySelect.Option, {
            key: field.key,
            label: field.label,
            value: field.key
          });
        }));
      }))), hasWarnings && _react["default"].createElement(_form["default"].FeedbackGroup, null, _react["default"].createElement(_form["default"].FeedbackItem, null, Liferay.Util.sub(Liferay.Language.get('no-fields-are-available-for-x-editable'), [_editableTypes.EDITABLE_TYPES.backgroundImage, _editableTypes.EDITABLE_TYPES.image].includes(fieldType) ? Liferay.Language.get('image') : Liferay.Language.get('text')))));
    }
    //# sourceMappingURL=MappingSelector.js.map
  }
});
//# sourceMappingURL=MappingSelector.js.map