Liferay.Loader.define("layout-content-page-editor-web@2.0.123/page_editor/app/components/Sidebar", ['module', 'exports', 'require', '@frontend-taglib-clay$clayui/button', '@frontend-taglib-clay$clayui/icon', '@frontend-taglib-clay$clayui/loading-indicator', '@frontend-taglib-clay$clayui/tooltip', 'frontend-js-react-web$classnames', 'frontend-js-react-web', 'frontend-js-react-web$react', 'frontend-js-react-web$react-dom', '../../core/hooks/useLazy', '../../core/hooks/useLoad', '../../core/hooks/usePlugins', '../actions/index', '../config/index', '../selectors/selectAvailablePanels', '../selectors/selectAvailableSidebarPanels', '../store/index', '../utils/dragAndDrop/useDragAndDrop', '../utils/useId', './Controls'], function (module, exports, require) {
  var define = undefined;
  var global = window;
  {
    Object.defineProperty(exports, "__esModule", {
      value: true
    });
    exports.default = Sidebar;

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

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

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

    var _tooltip = require("@frontend-taglib-clay$clayui/tooltip");

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

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

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

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

    var _useLazy = _interopRequireDefault(require("../../core/hooks/useLazy"));

    var _useLoad = _interopRequireDefault(require("../../core/hooks/useLoad"));

    var _usePlugins2 = _interopRequireDefault(require("../../core/hooks/usePlugins"));

    var Actions = _interopRequireWildcard(require("../actions/index"));

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

    var _selectAvailablePanels = _interopRequireDefault(require("../selectors/selectAvailablePanels"));

    var _selectAvailableSidebarPanels = _interopRequireDefault(require("../selectors/selectAvailableSidebarPanels"));

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

    var _useDragAndDrop = require("../utils/dragAndDrop/useDragAndDrop");

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

    var _Controls = require("./Controls");

    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 _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 _possibleConstructorReturn(self, call) {
      if (call && (_typeof(call) === "object" || typeof call === "function")) {
        return call;
      }return _assertThisInitialized(self);
    }

    function _assertThisInitialized(self) {
      if (self === void 0) {
        throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
      }return self;
    }

    function _getPrototypeOf(o) {
      _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
        return o.__proto__ || Object.getPrototypeOf(o);
      };return _getPrototypeOf(o);
    }

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

    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 Suspense = _react.default.Suspense,
        useCallback = _react.default.useCallback,
        useEffect = _react.default.useEffect;
    /**
     * Failure to preload is a non-critical failure, so we'll use this to swallow
     * rejected promises silently.
     */

    var swallow = [function (value) {
      return value;
    }, function (_error) {
      return undefined;
    }];

    function Sidebar() {
      var _themeDisplay;

      var dropClearRef = (0, _useDragAndDrop.useDropClear)();

      var _useStateSafe = (0, _frontendJsReactWeb.useStateSafe)(false),
          _useStateSafe2 = _slicedToArray(_useStateSafe, 2),
          hasError = _useStateSafe2[0],
          setHasError = _useStateSafe2[1];

      var _usePlugins = (0, _usePlugins2.default)(),
          getInstance = _usePlugins.getInstance,
          register = _usePlugins.register;

      var dispatch = (0, _index3.useDispatch)();
      var isMounted = (0, _frontendJsReactWeb.useIsMounted)();
      var load = (0, _useLoad.default)();
      var selectItem = (0, _Controls.useSelectItem)();
      var sidebarId = (0, _useId.useId)();
      var store = (0, _index3.useSelector)(function (state) {
        return state;
      });
      var panels = (0, _index3.useSelector)((0, _selectAvailablePanels.default)(_index2.config.panels));
      var sidebarPanels = (0, _index3.useSelector)((0, _selectAvailableSidebarPanels.default)(_index2.config.sidebarPanels));
      var sidebarOpen = store.sidebar.open;
      var sidebarPanelId = store.sidebar.panelId;
      var panel = sidebarPanels[sidebarPanelId];
      var promise = panel ? load(sidebarPanelId, panel.pluginEntryPoint) : Promise.resolve();
      var app = {
        Actions: Actions,
        config: _index2.config,
        dispatch: dispatch,
        store: store
      };
      var registerPanel;

      if (sidebarPanelId && panel) {
        registerPanel = register(sidebarPanelId, promise, {
          app: app,
          panel: panel
        });
      }

      var togglePlugin = function togglePlugin() {
        if (hasError) {
          setHasError(false);
        }

        if (registerPanel) {
          registerPanel.then(function (plugin) {
            if (plugin && typeof plugin.activate === 'function' && isMounted()) {
              plugin.activate();
            } else if (!plugin) {
              setHasError(true);
            }
          });
        }
      };

      useEffect(function () {
        if (panel) {
          togglePlugin(panel);
        } else if (sidebarPanelId) {
          dispatch(Actions.switchSidebarPanel({
            sidebarOpen: false,
            sidebarPanelId: null
          }));
        }
      },
      /* eslint-disable react-hooks/exhaustive-deps */
      [panel, sidebarOpen, sidebarPanelId]);
      useEffect(function () {
        var sideNavigation = Liferay.SideNavigation.instance(document.querySelector('.product-menu-toggle'));

        if (sideNavigation) {
          var onHandleSidebar = function onHandleSidebar(open) {
            dispatch(Actions.switchSidebarPanel({
              sidebarOpen: open
            }));
          };

          if (!sideNavigation.visible()) {
            onHandleSidebar(true);
          }

          var sideNavigationListener = sideNavigation.on('openStart.lexicon.sidenav', function () {
            return onHandleSidebar(false);
          });
          return function () {
            sideNavigationListener.removeListener();
          };
        }
      }, []);
      var SidebarPanel = (0, _useLazy.default)(useCallback(function (_ref) {
        var instance = _ref.instance;

        if (typeof instance.renderSidebar === 'function') {
          return instance.renderSidebar();
        } else {
          return null;
        }
      }, []));

      var deselectItem = function deselectItem(event) {
        if (event.target === event.currentTarget) {
          selectItem(null);
        }
      };

      var handleClick = function handleClick(panel) {
        var open = panel.sidebarPanelId === sidebarPanelId ? !sidebarOpen : true;
        var productMenuToggle = document.querySelector('.product-menu-toggle');

        if (productMenuToggle && !sidebarOpen) {
          Liferay.SideNavigation.hide(productMenuToggle);
        }

        dispatch(Actions.switchSidebarPanel({
          sidebarOpen: open,
          sidebarPanelId: panel.sidebarPanelId
        }));
      };

      return (/*#__PURE__*/(0, _reactDom.createPortal)( /*#__PURE__*/_react.default.createElement(_tooltip.ClayTooltipProvider, null, /*#__PURE__*/_react.default.createElement("div", {
          className: "page-editor__sidebar page-editor__theme-adapter-forms",
          ref: dropClearRef
        }, /*#__PURE__*/_react.default.createElement("div", {
          className: (0, _classnames.default)('page-editor__sidebar__buttons', {
            light: true
          }),
          onClick: deselectItem
        }, panels.reduce(function (elements, group, groupIndex) {
          var buttons = group.map(function (panelId) {
            var panel = sidebarPanels[panelId];
            var active = sidebarOpen && sidebarPanelId === panelId;
            var icon = panel.icon,
                isLink = panel.isLink,
                label = panel.label,
                pluginEntryPoint = panel.pluginEntryPoint,
                url = panel.url;

            if (isLink) {
              return (/*#__PURE__*/_react.default.createElement("a", {
                  className: (0, _classnames.default)({
                    active: active
                  }),
                  "data-tooltip-align": "left",
                  href: url,
                  key: panel.sidebarPanelId,
                  title: label
                }, /*#__PURE__*/_react.default.createElement(_icon.default, {
                  symbol: icon
                }))
              );
            }

            var prefetch = function prefetch() {
              var _load;

              return (_load = load(panel.sidebarPanelId, pluginEntryPoint)).then.apply(_load, swallow);
            };

            return (/*#__PURE__*/_react.default.createElement(_button.ClayButtonWithIcon, {
                "aria-pressed": active,
                className: (0, _classnames.default)({
                  active: active
                }),
                "data-tooltip-align": "left",
                displayType: "unstyled",
                id: "".concat(sidebarId).concat(panel.sidebarPanelId),
                key: panel.sidebarPanelId,
                onClick: function onClick() {
                  return handleClick(panel);
                },
                onFocus: prefetch,
                onMouseEnter: prefetch,
                small: true,
                symbol: icon,
                title: label
              })
            );
          }); // Add separator between groups.

          if (groupIndex === panels.length - 1) {
            return elements.concat(buttons);
          } else {
            return elements.concat([].concat(_toConsumableArray(buttons), [/*#__PURE__*/_react.default.createElement("hr", {
              key: "separator-".concat(groupIndex)
            })]));
          }
        }, [])), /*#__PURE__*/_react.default.createElement("div", {
          className: (0, _classnames.default)({
            'page-editor__sidebar__content': true,
            'page-editor__sidebar__content--open': sidebarOpen,
            rtl: _index2.config.languageDirection[(_themeDisplay = themeDisplay) === null || _themeDisplay === void 0 ? void 0 : _themeDisplay.getLanguageId()] === 'rtl'
          }),
          onClick: deselectItem
        }, hasError ? /*#__PURE__*/_react.default.createElement("div", null, /*#__PURE__*/_react.default.createElement(_button.default, {
          block: true,
          displayType: "secondary",
          onClick: function onClick() {
            dispatch(Actions.switchSidebarPanel({
              sidebarOpen: false,
              sidebarPanelId: panels[0] && panels[0][0]
            }));
            setHasError(false);
          },
          small: true
        }, Liferay.Language.get('refresh'))) : /*#__PURE__*/_react.default.createElement(ErrorBoundary, {
          handleError: function handleError() {
            setHasError(true);
          }
        }, /*#__PURE__*/_react.default.createElement(Suspense, {
          fallback: /*#__PURE__*/_react.default.createElement(_loadingIndicator.default, null)
        }, /*#__PURE__*/_react.default.createElement(SidebarPanel, {
          getInstance: getInstance,
          pluginId: sidebarPanelId
        })))))), document.body)
      );
    }

    var ErrorBoundary = /*#__PURE__*/function (_React$Component) {
      _inherits(ErrorBoundary, _React$Component);

      _createClass(ErrorBoundary, null, [{
        key: "getDerivedStateFromError",
        value: function getDerivedStateFromError(_error) {
          return {
            hasError: true
          };
        }
      }]);

      function ErrorBoundary(props) {
        var _this;

        _classCallCheck(this, ErrorBoundary);

        _this = _possibleConstructorReturn(this, _getPrototypeOf(ErrorBoundary).call(this, props));
        _this.state = {
          hasError: false
        };
        return _this;
      }

      _createClass(ErrorBoundary, [{
        key: "componentDidCatch",
        value: function componentDidCatch(error) {
          if (this.props.handleError) {
            this.props.handleError(error);
          }
        }
      }, {
        key: "render",
        value: function render() {
          if (this.state.hasError) {
            return null;
          } else {
            return this.props.children;
          }
        }
      }]);

      return ErrorBoundary;
    }(_react.default.Component);
    //# sourceMappingURL=Sidebar.js.map
  }
});
//# sourceMappingURL=Sidebar.js.map