Liferay.Loader.define("segments-web@2.0.27/js/components/segment_edit/SegmentEdit.es", ['module', 'exports', 'require', '@frontend-taglib-clay$clayui/button', '@frontend-taglib-clay$clayui/layout', 'frontend-js-react-web$formik', 'frontend-js-web', 'frontend-js-react-web$prop-types', 'frontend-js-react-web$react', '../../ThemeContext.es', '../../utils/constants.es', '../../utils/contributors.es', '../../utils/types.es', '../../utils/utils.es', '../criteria_builder/ContributorInputs.es', '../criteria_builder/ContributorsBuilder.es', '../shared/ClayToggle.es', '../title_editor/LocalizedInput.es'], function (module, exports, require) {
  var define = undefined;
  var global = window;
  {
    Object.defineProperty(exports, "__esModule", {
      value: true
    });
    exports.default = void 0;

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

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

    var _formik = require("frontend-js-react-web$formik");

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

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

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

    var _ThemeContext = _interopRequireDefault(require("../../ThemeContext.es"));

    var _constants = require("../../utils/constants.es");

    var _contributors2 = require("../../utils/contributors.es");

    var _types = require("../../utils/types.es");

    var _utils = require("../../utils/utils.es");

    var _ContributorInputs = _interopRequireDefault(require("../criteria_builder/ContributorInputs.es"));

    var _ContributorsBuilder = _interopRequireDefault(require("../criteria_builder/ContributorsBuilder.es"));

    var _ClayToggle = _interopRequireDefault(require("../shared/ClayToggle.es"));

    var _LocalizedInput = _interopRequireDefault(require("../title_editor/LocalizedInput.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 _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;
    }

    var SegmentEdit = /*#__PURE__*/function (_Component) {
      _inherits(SegmentEdit, _Component);

      function SegmentEdit(props) {
        var _this;

        _classCallCheck(this, SegmentEdit);

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

        _defineProperty(_assertThisInitialized(_this), "_handleCriteriaEdit", function () {
          _this.setState({
            editing: !_this.state.editing
          });
        });

        _defineProperty(_assertThisInitialized(_this), "_handleLocalizedInputChange", function (event, newValues, invalid) {
          _this.props.setFieldValue('name', newValues);

          _this.setState({
            hasChanged: true,
            validTitle: !invalid
          });
        });

        _defineProperty(_assertThisInitialized(_this), "_fetchMembersCount", function () {
          var formElement = document.getElementById(_this.props.formId);
          var formData = new FormData(formElement);
          (0, _frontendJsWeb.fetch)(_this.props.requestMembersCountURL, {
            body: formData,
            method: 'POST'
          }).then(function (response) {
            return response.json();
          }).then(function (membersCount) {
            _this.setState({
              membersCount: membersCount,
              membersCountLoading: false
            });
          }).catch(function () {
            _this.setState({
              membersCountLoading: false
            });

            Liferay.Util.openToast({
              message: Liferay.Language.get('an-unexpected-error-occurred'),
              type: 'danger'
            });
          });
        });

        _defineProperty(_assertThisInitialized(_this), "_handleQueryChange", function (criteriaChange, index) {
          _this.setState(function (prevState) {
            var contributors = (0, _contributors2.applyCriteriaChangeToContributors)(prevState.contributors, {
              criteriaChange: criteriaChange,
              propertyKey: index
            });
            return {
              contributors: contributors,
              disabledSave: _this._isQueryEmpty(contributors),
              hasChanged: true,
              membersCountLoading: true
            };
          }, _this._debouncedFetchMembersCount);
        });

        _defineProperty(_assertThisInitialized(_this), "_handleSegmentNameBlur", function (event) {
          var handleBlur = _this.props.handleBlur;
          handleBlur(event);
        });

        _defineProperty(_assertThisInitialized(_this), "_handleConjunctionChange", function (conjunctionName) {
          _this.setState(function (prevState) {
            var contributors = (0, _contributors2.applyConjunctionChangeToContributor)(prevState.contributors, conjunctionName);
            return {
              contributors: contributors,
              hasChanged: true,
              membersCountLoading: true
            };
          }, _this._debouncedFetchMembersCount);
        });

        _defineProperty(_assertThisInitialized(_this), "_isQueryEmpty", function (contributors) {
          return contributors.every(function (contributor) {
            return !contributor.query;
          });
        });

        _defineProperty(_assertThisInitialized(_this), "_renderContributors", function () {
          var _this$props = _this.props,
              locale = _this$props.locale,
              propertyGroups = _this$props.propertyGroups,
              requestMembersCountURL = _this$props.requestMembersCountURL,
              values = _this$props.values;
          var _this$state = _this.state,
              contributors = _this$state.contributors,
              editing = _this$state.editing,
              membersCount = _this$state.membersCount,
              membersCountLoading = _this$state.membersCountLoading;

          var emptyContributors = _this._isQueryEmpty(contributors);

          var segmentName = values.name[locale];
          return propertyGroups && contributors ? /*#__PURE__*/_react.default.createElement(_ContributorsBuilder.default, {
            contributors: contributors,
            editing: editing,
            emptyContributors: emptyContributors,
            membersCount: membersCount,
            membersCountLoading: membersCountLoading,
            onConjunctionChange: _this._handleConjunctionChange,
            onPreviewMembers: _this._handlePreviewMembers,
            onQueryChange: _this._handleQueryChange,
            propertyGroups: propertyGroups,
            requestMembersCountURL: requestMembersCountURL,
            segmentName: segmentName,
            supportedConjunctions: _constants.SUPPORTED_CONJUNCTIONS,
            supportedOperators: _constants.SUPPORTED_OPERATORS,
            supportedPropertyTypes: _constants.SUPPORTED_PROPERTY_TYPES
          }) : null;
        });

        _defineProperty(_assertThisInitialized(_this), "_handleCancelButton", function () {
          var hasChanged = _this.state.hasChanged;

          if (hasChanged) {
            var confirmed = confirm(Liferay.Language.get('criteria-cancel-confirmation-message'));

            if (confirmed) {
              _this._redirect();
            }
          } else {
            _this._redirect();
          }
        });

        _defineProperty(_assertThisInitialized(_this), "_redirect", function () {
          Liferay.Util.navigate(_this.props.redirect);
        });

        _defineProperty(_assertThisInitialized(_this), "_handlePreviewMembers", function () {
          var _this$props2 = _this.props,
              locale = _this$props2.locale,
              previewMembersURL = _this$props2.previewMembersURL,
              values = _this$props2.values;
          var name = values.name;
          var segmentLocalizedName = name[locale];
          (0, _frontendJsWeb.openModal)({
            id: 'segment-members-dialog',
            size: 'full-screen',
            title: (0, _utils.sub)(Liferay.Language.get('x-members'), [Liferay.Util.escape(segmentLocalizedName)]),
            url: previewMembersURL
          });
        });

        _defineProperty(_assertThisInitialized(_this), "_handleValidate", function (event) {
          var validateForm = _this.props.validateForm;
          event.persist();
          validateForm().then(function (errors) {
            var errorMessages = Object.values(errors);

            if (errorMessages.length) {
              event.preventDefault();
              errorMessages.forEach(function (message) {
                Liferay.Util.openToast({
                  message: message,
                  type: 'danger'
                });
              });
            }
          });
        });

        _defineProperty(_assertThisInitialized(_this), "_renderLocalizedInputs", function () {
          var _this$props3 = _this.props,
              defaultLanguageId = _this$props3.defaultLanguageId,
              portletNamespace = _this$props3.portletNamespace,
              values = _this$props3.values;
          var langs = Object.keys(values.name);
          return langs.map(function (key) {
            var returnVal;
            var value = values.name[key];

            if (key === defaultLanguageId) {
              returnVal = /*#__PURE__*/_react.default.createElement(_react.default.Fragment, {
                key: key
              }, /*#__PURE__*/_react.default.createElement("input", {
                name: "".concat(portletNamespace, "name_").concat(key),
                readOnly: true,
                type: "hidden",
                value: value
              }), /*#__PURE__*/_react.default.createElement("input", {
                name: "".concat(portletNamespace, "key"),
                readOnly: true,
                type: "hidden",
                value: value
              }), /*#__PURE__*/_react.default.createElement("input", {
                name: "".concat(portletNamespace, "name"),
                readOnly: true,
                type: "hidden",
                value: value
              }));
            } else {
              returnVal = /*#__PURE__*/_react.default.createElement(_react.default.Fragment, {
                key: key
              }, /*#__PURE__*/_react.default.createElement("input", {
                name: "".concat(portletNamespace, "name_").concat(key),
                readOnly: true,
                type: "hidden",
                value: value
              }));
            }

            return returnVal;
          });
        });

        var initialContributors = props.contributors,
            initialMembersCount = props.initialMembersCount,
            _propertyGroups = props.propertyGroups,
            showInEditMode = props.showInEditMode,
            _values = props.values;

        var _contributors = (0, _contributors2.initialContributorsToContributors)(initialContributors, _propertyGroups);

        _this.state = {
          contributors: _contributors,
          disabledSave: _this._isQueryEmpty(_contributors),
          editing: showInEditMode,
          hasChanged: false,
          membersCount: initialMembersCount,
          validTitle: !!_values.name[props.defaultLanguageId]
        };
        _this._debouncedFetchMembersCount = (0, _frontendJsWeb.debounce)(_this._fetchMembersCount, 500);
        return _this;
      }

      _createClass(SegmentEdit, [{
        key: "render",
        value: function render() {
          var _this$props4 = this.props,
              availableLocales = _this$props4.availableLocales,
              defaultLanguageId = _this$props4.defaultLanguageId,
              hasUpdatePermission = _this$props4.hasUpdatePermission,
              portletNamespace = _this$props4.portletNamespace,
              source = _this$props4.source,
              values = _this$props4.values;
          var _this$state2 = this.state,
              contributors = _this$state2.contributors,
              disabledSave = _this$state2.disabledSave,
              editing = _this$state2.editing,
              validTitle = _this$state2.validTitle;
          var assetsPath = this.context.assetsPath;

          var placeholder = Liferay.Language.get('untitled-segment');
          return (/*#__PURE__*/_react.default.createElement("div", {
              className: "segment-edit-page-root"
            }, /*#__PURE__*/_react.default.createElement("input", {
              name: "".concat(portletNamespace, "active"),
              type: "hidden",
              value: values.active
            }), /*#__PURE__*/_react.default.createElement("div", {
              className: "form-header"
            }, /*#__PURE__*/_react.default.createElement(_layout.default.ContainerFluid, {
              className: "form-header-container"
            }, /*#__PURE__*/_react.default.createElement("div", {
              className: "form-header-section-left"
            }, /*#__PURE__*/_react.default.createElement(_formik.FieldArray, {
              name: "values.name",
              render: this._renderLocalizedInputs
            }), /*#__PURE__*/_react.default.createElement(_LocalizedInput.default, {
              availableLanguages: availableLocales,
              defaultLang: defaultLanguageId,
              initialLanguageId: defaultLanguageId,
              initialOpen: false,
              initialValues: values.name,
              onChange: this._handleLocalizedInputChange,
              placeholder: placeholder,
              portletNamespace: portletNamespace,
              readOnly: !editing
            }), /*#__PURE__*/_react.default.createElement("div", {
              className: "align-self-center"
            }, /*#__PURE__*/_react.default.createElement("img", {
              className: "lfr-portal-tooltip source-icon",
              "data-testid": "source-icon",
              src: source === _constants.SOURCES.ASAH_FARO_BACKEND.name ? "".concat(assetsPath).concat(_constants.SOURCES.ASAH_FARO_BACKEND.icon) : "".concat(assetsPath).concat(_constants.SOURCES.DEFAULT.icon),
              title: source === _constants.SOURCES.ASAH_FARO_BACKEND.name ? _constants.SOURCES.ASAH_FARO_BACKEND.label : _constants.SOURCES.DEFAULT.label
            }))), hasUpdatePermission && /*#__PURE__*/_react.default.createElement("div", {
              className: "form-header-section-right"
            }, /*#__PURE__*/_react.default.createElement("div", {
              className: "btn-group"
            }, /*#__PURE__*/_react.default.createElement("div", {
              className: "btn-group-item mr-2"
            }, /*#__PURE__*/_react.default.createElement(_ClayToggle.default, {
              checked: editing,
              className: "toggle-editing",
              iconOff: "pencil",
              iconOn: "pencil",
              onChange: this._handleCriteriaEdit
            }))), /*#__PURE__*/_react.default.createElement("div", {
              className: "btn-group"
            }, /*#__PURE__*/_react.default.createElement("div", {
              className: "btn-group-item"
            }, /*#__PURE__*/_react.default.createElement(_button.default, {
              className: "text-capitalize",
              displayType: "secondary",
              onClick: this._handleCancelButton,
              small: true
            }, Liferay.Language.get('cancel'))), /*#__PURE__*/_react.default.createElement("div", {
              className: "btn-group-item"
            }, /*#__PURE__*/_react.default.createElement(_button.default, {
              className: "text-capitalize",
              disabled: disabledSave || !validTitle,
              displayType: "primary",
              onClick: this._handleValidate,
              small: true,
              type: "submit"
            }, Liferay.Language.get('save'))))))), /*#__PURE__*/_react.default.createElement("div", {
              className: "form-body"
            }, /*#__PURE__*/_react.default.createElement(_formik.FieldArray, {
              name: "contributors",
              render: this._renderContributors
            }), /*#__PURE__*/_react.default.createElement(_ContributorInputs.default, {
              contributors: contributors
            })))
          );
        }
      }]);

      return SegmentEdit;
    }(_react.Component);

    _defineProperty(SegmentEdit, "contextType", _ThemeContext.default);

    _defineProperty(SegmentEdit, "defaultProps", {
      contributors: [],
      handleBlur: function handleBlur() {},
      initialSegmentActive: true,
      initialSegmentName: {},
      portletNamespace: '',
      showInEditMode: false
    });

    var _default = (0, _formik.withFormik)({
      mapPropsToValues: function mapPropsToValues(props) {
        return {
          active: props.initialSegmentActive || true,
          contributors: props.contributors || [],
          name: props.initialSegmentName || {}
        };
      },
      validate: function validate(values) {
        var errors = {};

        if (!values.name) {
          errors.name = Liferay.Language.get('segment-name-is-required');
        }

        return errors;
      }
    })(SegmentEdit);

    exports.default = _default;
    //# sourceMappingURL=SegmentEdit.es.js.map
  }
});
//# sourceMappingURL=SegmentEdit.es.js.map