Liferay.Loader.define("layout-content-page-editor-web@2.0.166/page_editor/plugins/experience/components/ExperienceSelector", ['module', 'exports', 'require', '@frontend-taglib-clay$clayui/alert', '@frontend-taglib-clay$clayui/button', '@frontend-taglib-clay$clayui/icon', '@frontend-taglib-clay$clayui/layout', '@frontend-taglib-clay$clayui/modal', 'frontend-js-react-web', 'frontend-js-web', 'frontend-js-react-web$react', 'frontend-js-react-web$react-dom', '../../../app/config/index', '../../../app/selectors/selectCanUpdateExperiences', '../../../app/selectors/selectCanUpdateSegments', '../../../app/store/index', '../thunks/createExperience', '../thunks/duplicateExperience', '../thunks/removeExperience', '../thunks/updateExperience', '../thunks/updateExperiencePriority', '../utils', './ExperienceModal', './ExperiencesList'], 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 _alert = _interopRequireDefault(require("@frontend-taglib-clay$clayui/alert"));

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

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

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

    var _modal = require("@frontend-taglib-clay$clayui/modal");

    var _frontendJsReactWeb = require("frontend-js-react-web");

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

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

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

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

    var _selectCanUpdateExperiences = _interopRequireDefault(require("../../../app/selectors/selectCanUpdateExperiences"));

    var _selectCanUpdateSegments = _interopRequireDefault(require("../../../app/selectors/selectCanUpdateSegments"));

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

    var _createExperience = _interopRequireDefault(require("../thunks/createExperience"));

    var _duplicateExperience = _interopRequireDefault(require("../thunks/duplicateExperience"));

    var _removeExperience = _interopRequireDefault(require("../thunks/removeExperience"));

    var _updateExperience = _interopRequireDefault(require("../thunks/updateExperience"));

    var _updateExperiencePriority = _interopRequireDefault(require("../thunks/updateExperiencePriority"));

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

    var _ExperienceModal = _interopRequireDefault(require("./ExperienceModal"));

    var _ExperiencesList = _interopRequireDefault(require("./ExperiencesList"));

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

    /**
     * It produces an object with a target and subtarget keys indicating what experiences
     * should change to change the priority of target priority.
     */
    function getUpdateExperiencePriorityTargets(orderedExperiences, targetExperienceId, direction) {
      var targetIndex = orderedExperiences.findIndex(function (experience) {
        return experience.segmentsExperienceId === targetExperienceId;
      });
      var subtargetIndex;

      if (direction === 'up') {
        subtargetIndex = targetIndex - 1;
      } else {
        subtargetIndex = targetIndex + 1;
      }

      var subtargetExperience = orderedExperiences[subtargetIndex];
      var targetExperience = orderedExperiences[targetIndex];
      return {
        priority: subtargetExperience.priority,
        segmentsExperienceId: targetExperience.segmentsExperienceId
      };
    }

    var ExperienceSelector = function ExperienceSelector(_ref) {
      var experiences = _ref.experiences,
          segments = _ref.segments,
          selectId = _ref.selectId,
          selectedExperience = _ref.selectedExperience;
      var dispatch = (0, _index2.useDispatch)();
      var canUpdateExperiences = (0, _index2.useSelector)(_selectCanUpdateExperiences.default);
      var canUpdateSegments = (0, _index2.useSelector)(_selectCanUpdateSegments.default);
      var buttonRef = (0, _react.useRef)();

      var _useState = (0, _react.useState)({
        bottom: 0,
        left: 0
      }),
          _useState2 = _slicedToArray(_useState, 2),
          buttonBoundingClientRect = _useState2[0],
          setButtonBoundingClientRect = _useState2[1];

      var isMounted = (0, _frontendJsReactWeb.useIsMounted)();

      var _useState3 = (0, _react.useState)(false),
          _useState4 = _slicedToArray(_useState3, 2),
          open = _useState4[0],
          setOpen = _useState4[1];

      var _useState5 = (0, _react.useState)(false),
          _useState6 = _slicedToArray(_useState5, 2),
          openModal = _useState6[0],
          setOpenModal = _useState6[1];

      var _useState7 = (0, _react.useState)({}),
          _useState8 = _slicedToArray(_useState7, 2),
          editingExperience = _useState8[0],
          setEditingExperience = _useState8[1];

      var _useModal = (0, _modal.useModal)({
        onClose: function onClose() {
          setOpenModal(false);
          setEditingExperience({});
        }
      }),
          modalObserver = _useModal.observer,
          onModalClose = _useModal.onClose;

      var _useDebounceCallback = (0, _utils.useDebounceCallback)(function (value) {
        if (isMounted() && buttonRef.current) {
          setButtonBoundingClientRect(buttonRef.current.getBoundingClientRect());
          setOpen(value);
        }
      }, 100),
          _useDebounceCallback2 = _slicedToArray(_useDebounceCallback, 1),
          debouncedSetOpen = _useDebounceCallback2[0];

      (0, _react.useEffect)(function () {
        if (_index.config.plid) {
          var modalExperienceState = (0, _utils.recoverModalExperienceState)();

          if (modalExperienceState && _index.config.plid === modalExperienceState.plid) {
            setOpenModal(true);
            setEditingExperience({
              name: modalExperienceState.experienceName,
              segmentsEntryId: _index.config.selectedSegmentsEntryId || modalExperienceState.segmentId,
              segmentsExperienceId: modalExperienceState.experienceId
            });
          }
        }
      }, []);
      (0, _react.useEffect)(function () {
        if (open) {
          var _element$scrollIntoVi;

          var element = document.querySelector('.dropdown-menu__experience--active');
          element === null || element === void 0 ? void 0 : (_element$scrollIntoVi = element.scrollIntoView) === null || _element$scrollIntoVi === void 0 ? void 0 : _element$scrollIntoVi.call(element, {
            behavior: 'auto',
            block: 'center',
            inline: 'nearest'
          });
        }
      }, [open]);
      (0, _react.useEffect)(function () {
        var _element$scrollIntoVi2;

        var element = document.querySelector('.dropdown-menu__experience--active');
        element === null || element === void 0 ? void 0 : (_element$scrollIntoVi2 = element.scrollIntoView) === null || _element$scrollIntoVi2 === void 0 ? void 0 : _element$scrollIntoVi2.call(element, {
          behavior: 'smooth',
          block: 'center',
          inline: 'nearest'
        });
      }, [//LPS-127205
      experiences.length]);

      return (/*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_button.default, {
          className: "form-control-select pr-4 text-left text-truncate",
          displayType: "secondary",
          id: selectId,
          onBlur: function handleDropdownButtonBlur() {
            return debouncedSetOpen(false);
          },
          onClick: function handleDropdownButtonClick() {
            return debouncedSetOpen(!open);
          },
          ref: buttonRef,
          small: true,
          type: "button"
        }, /*#__PURE__*/_react.default.createElement(_layout.default.ContentRow, {
          verticalAlign: "center"
        }, /*#__PURE__*/_react.default.createElement(_layout.default.ContentCol, {
          expand: true
        }, /*#__PURE__*/_react.default.createElement("span", {
          className: "text-truncate"
        }, selectedExperience.name)), /*#__PURE__*/_react.default.createElement(_layout.default.ContentCol, null, selectedExperience.hasLockedSegmentsExperiment && /*#__PURE__*/_react.default.createElement(_icon.default, {
          symbol: "lock"
        })))), open && /*#__PURE__*/(0, _reactDom.createPortal)( /*#__PURE__*/_react.default.createElement("div", {
          className: "dropdown-menu p-4 page-editor__toolbar-experience__dropdown-menu toggled",
          onBlur: function handleDropdownBlur() {
            return debouncedSetOpen(false);
          },
          onFocus: function handleDropdownFocus() {
            return debouncedSetOpen(true);
          },
          style: {
            left: buttonBoundingClientRect.left,
            top: buttonBoundingClientRect.bottom
          },
          tabIndex: "-1"
        }, /*#__PURE__*/_react.default.createElement(ExperiencesSelectorHeader, {
          canCreateExperiences: canUpdateExperiences,
          onNewExperience: function handleOnNewExperiecneClick() {
            return setOpenModal(true);
          },
          showEmptyStateMessage: experiences.length <= 1
        }), experiences.length > 1 && /*#__PURE__*/_react.default.createElement(_ExperiencesList.default, {
          activeExperienceId: selectedExperience.segmentsExperienceId,
          canUpdateExperiences: canUpdateExperiences,
          defaultExperienceId: _index.config.defaultSegmentsExperienceId,
          experiences: experiences,
          onDeleteExperience: function deleteExperience(id) {
            dispatch((0, _removeExperience.default)({
              segmentsExperienceId: id,
              selectedExperienceId: selectedExperience.segmentsExperienceId
            })).then(function () {
              (0, _frontendJsWeb.openToast)({
                message: Liferay.Language.get('the-experience-was-deleted-successfully'),
                type: 'success'
              });
            }).catch(function () {
              (0, _frontendJsWeb.openToast)({
                message: Liferay.Language.get('an-unexpected-error-occurred'),
                type: 'danger'
              });
            });
          },
          onDuplicateExperience: function handleExperienceDuplication(id) {
            dispatch((0, _duplicateExperience.default)({
              segmentsExperienceId: id
            })).then(function () {
              (0, _frontendJsWeb.openToast)({
                message: Liferay.Language.get('the-experience-was-duplicated-successfully'),
                type: 'success'
              });
            }).catch(function () {
              (0, _frontendJsWeb.openToast)({
                message: Liferay.Language.get('an-unexpected-error-occurred'),
                type: 'danger'
              });
            });
          },
          onEditExperience: function handleEditExperienceClick(experienceData) {
            var name = experienceData.name,
                segmentsEntryId = experienceData.segmentsEntryId,
                segmentsExperienceId = experienceData.segmentsExperienceId;
            setOpenModal(true);
            setEditingExperience({
              name: name,
              segmentsEntryId: segmentsEntryId,
              segmentsExperienceId: segmentsExperienceId
            });
          },
          onPriorityDecrease: function decreasePriority(id) {
            var target = getUpdateExperiencePriorityTargets(experiences, id, 'down');
            dispatch((0, _updateExperiencePriority.default)(target));
          },
          onPriorityIncrease: function increasePriority(id) {
            var target = getUpdateExperiencePriorityTargets(experiences, id, 'up');
            dispatch((0, _updateExperiencePriority.default)(target));
          }
        })), document.body), openModal && /*#__PURE__*/_react.default.createElement(_ExperienceModal.default, {
          canUpdateSegments: canUpdateSegments,
          errorMessage: editingExperience.error,
          experienceId: editingExperience.segmentsExperienceId,
          initialName: editingExperience.name,
          observer: modalObserver,
          onClose: onModalClose,
          onErrorDismiss: function onErrorDismiss() {
            return setEditingExperience({
              error: null
            });
          },
          onNewSegmentClick: function handleNewSegmentClick(_ref2) {
            var experienceId = _ref2.experienceId,
                experienceName = _ref2.experienceName,
                segmentId = _ref2.segmentId;
            (0, _utils.storeModalExperienceState)({
              experienceId: experienceId,
              experienceName: experienceName,
              plid: _index.config.plid,
              segmentId: segmentId
            });
            Liferay.Util.navigate(_index.config.editSegmentsEntryURL);
          },
          onSubmit: function handleExperienceCreation(_ref3) {
            var name = _ref3.name,
                segmentsEntryId = _ref3.segmentsEntryId,
                segmentsExperienceId = _ref3.segmentsExperienceId;

            if (segmentsExperienceId) {
              return dispatch((0, _updateExperience.default)({
                name: name,
                segmentsEntryId: segmentsEntryId,
                segmentsExperienceId: segmentsExperienceId
              })).then(function () {
                if (isMounted()) {
                  onModalClose();
                }

                (0, _frontendJsWeb.openToast)({
                  message: Liferay.Language.get('the-experience-was-updated-successfully'),
                  type: 'success'
                });
              }).catch(function () {
                if (isMounted()) {
                  setEditingExperience({
                    error: Liferay.Language.get('an-unexpected-error-occurred-while-updating-the-experience'),
                    name: name,
                    segmentsEntryId: segmentsEntryId,
                    segmentsExperienceId: segmentsExperienceId
                  });
                }
              });
            } else {
              return dispatch((0, _createExperience.default)({
                name: name,
                segmentsEntryId: segmentsEntryId
              })).then(function () {
                if (isMounted()) {
                  onModalClose();
                }

                (0, _frontendJsWeb.openToast)({
                  message: Liferay.Language.get('the-experience-was-created-successfully'),
                  type: 'success'
                });
              }).catch(function () {
                if (isMounted()) {
                  setEditingExperience({
                    error: Liferay.Language.get('an-unexpected-error-occurred-while-creating-the-experience'),
                    name: name,
                    segmentsEntryId: segmentsEntryId,
                    segmentsExperienceId: segmentsExperienceId
                  });
                }
              });
            }
          },
          segmentId: editingExperience.segmentsEntryId,
          segments: segments
        }))
      );
    };

    var ExperiencesSelectorHeader = function ExperiencesSelectorHeader(_ref4) {
      var canCreateExperiences = _ref4.canCreateExperiences,
          onNewExperience = _ref4.onNewExperience,
          showEmptyStateMessage = _ref4.showEmptyStateMessage;
      return (/*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_layout.default.ContentRow, {
          className: "mb-3",
          verticalAlign: "center"
        }, /*#__PURE__*/_react.default.createElement(_layout.default.ContentCol, {
          expand: true
        }, /*#__PURE__*/_react.default.createElement("h3", {
          className: "mb-0"
        }, Liferay.Language.get('select-experience'))), /*#__PURE__*/_react.default.createElement(_layout.default.ContentCol, null, canCreateExperiences === true && /*#__PURE__*/_react.default.createElement(_button.default, {
          "aria-label": Liferay.Language.get('new-experience'),
          displayType: "secondary",
          onClick: onNewExperience,
          small: true
        }, Liferay.Language.get('new-experience')))), canCreateExperiences && /*#__PURE__*/_react.default.createElement("p", {
          className: "text-secondary"
        }, showEmptyStateMessage ? Liferay.Language.get('experience-help-message-empty-state') : Liferay.Language.get('experience-help-message-started-state')), /*#__PURE__*/_react.default.createElement(_alert.default, {
          className: "mx-0",
          displayType: "warning",
          title: Liferay.Language.get('warning')
        }, Liferay.Language.get('changes-to-experiences-are-applied-immediately')))
      );
    };

    var _default = ExperienceSelector;
    exports.default = _default;
    //# sourceMappingURL=ExperienceSelector.js.map
  }
});
//# sourceMappingURL=ExperienceSelector.js.map