Liferay.Loader.define("dynamic-data-mapping-form-field-type@5.0.95/Options/Options.es", ['module', 'exports', 'require', '@frontend-taglib-clay$clayui/icon', 'frontend-js-react-web$classnames', 'dynamic-data-mapping-form-builder', 'dynamic-data-mapping-form-renderer', 'frontend-js-web', 'frontend-js-react-web$react', 'frontend-js-react-web$react-dnd', 'frontend-js-react-web$react-dnd-html5-backend', '../FieldBase/ReactFieldBase.es', '../KeyValue/KeyValue.es', './DnD.es', './DragPreview.es', './util.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.default = void 0;

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

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

    var _dynamicDataMappingFormBuilder = require("dynamic-data-mapping-form-builder");

    var _dynamicDataMappingFormRenderer = require("dynamic-data-mapping-form-renderer");

    var _frontendJsWeb = require("frontend-js-web");

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

    var _reactDnd = require("frontend-js-react-web$react-dnd");

    var _reactDndHtml5Backend = require("frontend-js-react-web$react-dnd-html5-backend");

    var _ReactFieldBase = require("../FieldBase/ReactFieldBase.es");

    var _KeyValue = _interopRequireDefault(require("../KeyValue/KeyValue.es"));

    var _DnD = _interopRequireDefault(require("./DnD.es"));

    var _DragPreview = _interopRequireDefault(require("./DragPreview.es"));

    var _util = require("./util.es");

    var _this = void 0;

    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 _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 _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 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 _toConsumableArray(arr) {
      return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread();
    }

    function _nonIterableSpread() {
      throw new TypeError("Invalid attempt to spread non-iterable instance");
    }

    function _iterableToArray(iter) {
      if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter);
    }

    function _arrayWithoutHoles(arr) {
      if (Array.isArray(arr)) {
        for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) {
          arr2[i] = arr[i];
        }return arr2;
      }
    }

    var Option = /*#__PURE__*/_react.default.forwardRef(function (_ref, ref) {
      var children = _ref.children,
          className = _ref.className,
          disabled = _ref.disabled,
          onClick = _ref.onClick,
          showCloseButton = _ref.showCloseButton,
          style = _ref.style;
      return (/*#__PURE__*/_react.default.createElement("div", {
          className: (0, _classnames.default)('ddm-field-options', className),
          style: style
        }, /*#__PURE__*/_react.default.createElement("span", {
          className: (0, _classnames.default)('ddm-options-drag', {
            disabled: disabled
          }),
          ref: disabled ? null : ref
        }, /*#__PURE__*/_react.default.createElement(_icon.default, {
          symbol: "drag"
        })), /*#__PURE__*/_react.default.createElement("div", {
          className: "ddm-option-entry"
        }, children, showCloseButton && /*#__PURE__*/_react.default.createElement("button", {
          className: "close close-modal",
          onClick: onClick,
          type: "button"
        }, /*#__PURE__*/_react.default.createElement(_icon.default, {
          symbol: "times"
        }))))
      );
    });

    var getInitialOption = function getInitialOption(generateOptionValueUsingOptionLabel) {
      var optionValue = (0, _util.getDefaultOptionValue)(generateOptionValueUsingOptionLabel, '');
      var initalOption = {
        id: (0, _util.random)(),
        label: '',
        reference: optionValue,
        value: ''
      };

      if (!generateOptionValueUsingOptionLabel) {
        initalOption.value = optionValue;
      }

      return initalOption;
    };

    var refreshFields = function refreshFields(defaultLanguageId, editingLanguageId, generateOptionValueUsingOptionLabel, initialOption, options) {
      var refreshedFields = [].concat(_toConsumableArray(options.map(function (option) {
        return _objectSpread(_objectSpread({
          generateKeyword: generateOptionValueUsingOptionLabel ? (0, _util.isOptionValueGenerated)(defaultLanguageId, editingLanguageId, options, option) : false
        }, option), {}, {
          value: option.value ? option.value : (0, _util.getDefaultOptionValue)(generateOptionValueUsingOptionLabel, option.label)
        });
      })), [_objectSpread({
        generateKeyword: generateOptionValueUsingOptionLabel
      }, initialOption)]).filter(function (field) {
        return field && Object.keys(field).length > 0;
      });
      return (0, _util.normalizeFields)(refreshedFields, generateOptionValueUsingOptionLabel);
    };

    var Options = function Options(_ref2) {
      var children = _ref2.children,
          defaultLanguageId = _ref2.defaultLanguageId,
          disabled = _ref2.disabled,
          editingLanguageId = _ref2.editingLanguageId,
          generateOptionValueUsingOptionLabel = _ref2.generateOptionValueUsingOptionLabel,
          onChange = _ref2.onChange,
          _ref2$value = _ref2.value,
          value = _ref2$value === void 0 ? {} : _ref2$value;

      var _usePage = (0, _dynamicDataMappingFormRenderer.usePage)(),
          builderRules = _usePage.builderRules;

      var initialOptionRef = (0, _react.useRef)(getInitialOption(generateOptionValueUsingOptionLabel));

      var _useState = (0, _react.useState)(function () {
        var formattedValue = _objectSpread({}, value);

        Object.keys(value).forEach(function (languageId) {
          if (defaultLanguageId !== languageId) {
            formattedValue[languageId] = formattedValue[languageId].filter(function (_ref3) {
              var value = _ref3.value;
              return !!value;
            });
          }

          formattedValue[languageId] = formattedValue[languageId].map(function (option) {
            var newOption = _objectSpread({
              id: (0, _util.random)()
            }, option);

            if (!option.value && option.label.toLowerCase() === Liferay.Language.get('option').toLowerCase()) {
              var optionValue = (0, _util.getDefaultOptionValue)(generateOptionValueUsingOptionLabel, option.label);
              newOption = _objectSpread(_objectSpread({}, newOption), {}, {
                reference: optionValue,
                value: optionValue
              });
            }

            return newOption;
          });
        });
        return formattedValue;
      }),
          _useState2 = _slicedToArray(_useState, 1),
          normalizedValue = _useState2[0];

      var _useState3 = (0, _react.useState)(null),
          _useState4 = _slicedToArray(_useState3, 2),
          fieldError = _useState4[0],
          setFieldError = _useState4[1];

      var _useState5 = (0, _react.useState)(function () {
        var options = normalizedValue[editingLanguageId] || normalizedValue[defaultLanguageId] || [];
        return refreshFields(defaultLanguageId, editingLanguageId, generateOptionValueUsingOptionLabel, initialOptionRef.current, options);
      }),
          _useState6 = _slicedToArray(_useState5, 2),
          fields = _useState6[0],
          setFields = _useState6[1];

      (0, _react.useEffect)(function () {
        var options = normalizedValue[editingLanguageId] || normalizedValue[defaultLanguageId] || [];
        setFields(refreshFields(defaultLanguageId, editingLanguageId, generateOptionValueUsingOptionLabel, initialOptionRef.current, options));
      }, [defaultLanguageId, editingLanguageId, generateOptionValueUsingOptionLabel, normalizedValue]);
      var defaultOptionRef = (0, _react.useRef)(fields.length === 2 && fields[0].label.toLowerCase() === Liferay.Language.get('option').toLowerCase());

      var synchronizeValue = function synchronizeValue(fields, languageId) {
        if (editingLanguageId === languageId) {
          return _toConsumableArray(fields);
        }

        return _toConsumableArray(fields).map(function (field) {
          var existingValue = normalizedValue[languageId].find(function (_ref4) {
            var value = _ref4.value;
            return value === field.value;
          });

          if (existingValue) {
            var copyFrom = existingValue.copyFrom;

            if (copyFrom && copyFrom === editingLanguageId) {
              return _objectSpread(_objectSpread({}, existingValue), {}, {
                label: field.label
              });
            }

            return existingValue;
          }

          return _objectSpread(_objectSpread({}, field), {}, {
            copyFrom: editingLanguageId,
            label: field.label
          });
        });
      };

      var getSynchronizedValue = function getSynchronizedValue(fields) {
        var _fields = _toConsumableArray(fields);

        _fields.pop();

        var availableLanguageIds = Object.getOwnPropertyNames(normalizedValue);
        return availableLanguageIds.reduce(function (value, languageId) {
          return _objectSpread(_objectSpread({}, value), {}, _defineProperty({}, languageId, synchronizeValue(_fields, languageId)));
        }, _defineProperty({}, editingLanguageId, _toConsumableArray(_fields)));
      };

      var clone = function clone() {
        for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
          args[_key] = arguments[_key];
        }

        return [_toConsumableArray(fields)].concat(args);
      };

      var clearError = function clearError() {
        setFieldError(null);
      };

      var checkValidReference = function checkValidReference(fields, value, fieldName) {
        var field = fields.filter(function (_ref5) {
          var value = _ref5.value;
          return value !== fieldName;
        }).find(function (_ref6) {
          var reference = _ref6.reference;
          return (reference === null || reference === void 0 ? void 0 : reference.toLowerCase()) === (value === null || value === void 0 ? void 0 : value.toLowerCase());
        });
        return field ? fieldName : null;
      };

      var dedup = function dedup(fields, index, property, value) {
        var _fields$index = fields[index],
            generateKeyword = _fields$index.generateKeyword,
            id = _fields$index.id;

        if (property === 'value' && generateKeyword) {
          value = (0, _util.dedupValue)(fields, value ? value : Liferay.Language.get('option'), id, generateOptionValueUsingOptionLabel);
        } else if (property == 'reference') {
          setFieldError(checkValidReference(fields, value, fields[index].value));
        }

        return [fields, index, property, value];
      };

      var set = function set(fields) {
        setFields(fields);
        var synchronizedNormalizedValue = getSynchronizedValue(fields);
        onChange(synchronizedNormalizedValue);
      };

      var composedAdd = (0, _util.compose)(clone, dedup, function add(fields, index, property, value) {
        fields[index][property] = value;
        var initialOption = getInitialOption(generateOptionValueUsingOptionLabel);
        fields.push(_objectSpread({
          generateKeyword: generateOptionValueUsingOptionLabel
        }, initialOption));
        initialOptionRef.current = initialOption;
        return [fields, index, property, value];
      }, set);
      var composedBlur = (0, _util.compose)(clone, function normalize(fields, index) {
        clearError();
        fields[index]['reference'] = (0, _util.normalizeReference)(fields, fields[index], index);
        return [(0, _util.normalizeFields)(fields, generateOptionValueUsingOptionLabel)];
      }, set);
      var composedChange = (0, _util.compose)(clone, dedup, function change(fields, index, property, value) {
        var _fields$index2 = fields[index],
            edited = _fields$index2.edited,
            label = _fields$index2.label;
        fields[index][property] = value;
        fields[index]['edited'] = edited || value && value !== label && property === 'value';

        if (property === 'label') {
          fields[index]['copyFrom'] = undefined;
        }

        return [fields, index, property, value];
      }, set);
      var composedDelete = (0, _util.compose)(clone, function handleDelete(fields, index) {
        fields.splice(index, 1);
        return [fields];
      }, set);
      var composedMove = (0, _util.compose)(clone, function move(fields, data) {
        var itemPosition = data.itemPosition,
            targetPosition = data.targetPosition;

        if (itemPosition === fields.length - 1) {
          return [fields];
        }

        var item = _objectSpread({}, fields[itemPosition]);

        var newTargetPosition = targetPosition > itemPosition ? targetPosition - 1 : targetPosition;
        fields.splice(itemPosition, 1);
        fields.splice(newTargetPosition, 0, item);
        return [fields];
      }, set);

      var handleConfirmDelete = function handleConfirmDelete(index, option) {
        if (builderRules && _dynamicDataMappingFormBuilder.RulesSupport.findRuleByFieldName(option, null, builderRules)) {
          (0, _frontendJsWeb.openModal)({
            bodyHTML: Liferay.Language.get('a-rule-is-applied-to-this-field'),
            buttons: [{
              displayType: 'secondary',
              label: Liferay.Language.get('cancel'),
              type: 'cancel'
            }, {
              displayType: 'danger',
              label: Liferay.Language.get('confirm'),
              onClick: function onClick() {
                composedDelete(index);
              },
              type: 'cancel'
            }],
            size: 'md',
            title: Liferay.Language.get('delete-field-with-rule-applied')
          });
        } else {
          composedDelete(index);
        }
      };

      return (/*#__PURE__*/_react.default.createElement("div", {
          className: "ddm-field-options-container"
        }, /*#__PURE__*/_react.default.createElement(_DragPreview.default, {
          component: Option
        }, children), fields.map(function (option, index) {
          return (/*#__PURE__*/_react.default.createElement(_DnD.default, {
              index: index,
              key: option.id,
              onDragEnd: composedMove,
              option: option
            }, /*#__PURE__*/_react.default.createElement(Option, {
              disabled: disabled,
              onClick: function onClick() {
                return handleConfirmDelete(index, option.value);
              },
              showCloseButton: !(fields.length - 1 === index) && !disabled
            }, children({
              defaultOptionRef: defaultOptionRef,
              fieldError: fieldError,
              handleBlur: composedBlur.bind(_this, index),
              handleField: !(fields.length - 1 === index) ? composedChange.bind(_this, index) : composedAdd.bind(_this, index),
              index: index,
              option: option
            })))
          );
        }))
      );
    };

    var Main = function Main(_ref7) {
      var _ref7$defaultLanguage = _ref7.defaultLanguageId,
          defaultLanguageId = _ref7$defaultLanguage === void 0 ? themeDisplay.getLanguageId() : _ref7$defaultLanguage,
          _ref7$editingLanguage = _ref7.editingLanguageId,
          editingLanguageId = _ref7$editingLanguage === void 0 ? themeDisplay.getLanguageId() : _ref7$editingLanguage,
          _ref7$generateOptionV = _ref7.generateOptionValueUsingOptionLabel,
          generateOptionValueUsingOptionLabel = _ref7$generateOptionV === void 0 ? false : _ref7$generateOptionV,
          _onChange = _ref7.onChange,
          keywordReadOnly = _ref7.keywordReadOnly,
          _ref7$placeholder = _ref7.placeholder,
          placeholder = _ref7$placeholder === void 0 ? Liferay.Language.get('enter-an-option') : _ref7$placeholder,
          readOnly = _ref7.readOnly,
          required = _ref7.required,
          showKeyword = _ref7.showKeyword,
          _ref7$value = _ref7.value,
          value = _ref7$value === void 0 ? {} : _ref7$value,
          visible = _ref7.visible,
          otherProps = _objectWithoutProperties(_ref7, ["defaultLanguageId", "editingLanguageId", "generateOptionValueUsingOptionLabel", "onChange", "keywordReadOnly", "placeholder", "readOnly", "required", "showKeyword", "value", "visible"]);

      return (/*#__PURE__*/_react.default.createElement(_reactDnd.DndProvider, {
          backend: _reactDndHtml5Backend.HTML5Backend,
          context: window
        }, /*#__PURE__*/_react.default.createElement(_ReactFieldBase.FieldBase, _extends({}, otherProps, {
          readOnly: readOnly,
          visible: visible
        }), /*#__PURE__*/_react.default.createElement(Options, {
          defaultLanguageId: defaultLanguageId,
          disabled: readOnly,
          editingLanguageId: editingLanguageId,
          generateOptionValueUsingOptionLabel: generateOptionValueUsingOptionLabel,
          onChange: function onChange(value) {
            return _onChange({}, value);
          },
          value: value
        }, function (_ref8) {
          var defaultOptionRef = _ref8.defaultOptionRef,
              fieldError = _ref8.fieldError,
              handleBlur = _ref8.handleBlur,
              handleField = _ref8.handleField,
              index = _ref8.index,
              option = _ref8.option;
          return option && /*#__PURE__*/_react.default.createElement(_KeyValue.default, {
            displayErrors: fieldError && fieldError === option.value,
            errorMessage: Liferay.Language.get('this-reference-is-already-being-used'),
            generateKeyword: option.generateKeyword,
            keyword: option.value,
            keywordReadOnly: keywordReadOnly,
            name: "option".concat(index),
            onBlur: handleBlur,
            onChange: function onChange(event) {
              return handleField('label', event.target.value);
            },
            onFocus: function onFocus() {
              if (defaultOptionRef.current) {
                handleField('label', '');
                defaultOptionRef.current = false;
              }
            },
            onKeywordBlur: handleBlur,
            onKeywordChange: function onKeywordChange(event, value, generate) {
              handleField('generateKeyword', generate);
              handleField('value', value);
            },
            onReferenceBlur: handleBlur,
            onReferenceChange: function onReferenceChange(event) {
              handleField('reference', event.target.value);
            },
            placeholder: placeholder,
            readOnly: option.disabled,
            reference: option.reference,
            required: required,
            showKeyword: showKeyword,
            showLabel: false,
            value: option.label,
            visible: visible
          });
        })))
      );
    };

    Main.displayName = 'Options';
    var _default = Main;
    exports.default = _default;
    //# sourceMappingURL=Options.es.js.map
  }
});
//# sourceMappingURL=Options.es.js.map