"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;
var _base = _interopRequireDefault(require("@emotion/styled/base"));
var _propTypes = _interopRequireDefault(require("prop-types"));
var _react = _interopRequireDefault(require("react"));
var _reactPolyglot = require("react-polyglot");
var _reactImmutableProptypes = _interopRequireDefault(require("react-immutable-proptypes"));
var _reactRedux = require("react-redux");
var _reactRouterDom = require("react-router-dom");
var _reactTopbarProgressIndicator = _interopRequireDefault(require("react-topbar-progress-indicator"));
var _decapCmsUiDefault = require("decap-cms-ui-default");
var _auth = require("../../actions/auth");
var _backend = require("../../backend");
var _collections = require("../../actions/collections");
var _mediaLibrary = require("../../actions/mediaLibrary");
var _MediaLibrary = _interopRequireDefault(require("../MediaLibrary/MediaLibrary"));
var _UI = require("../UI");
var _history = require("../../routing/history");
var _publishModes = require("../../constants/publishModes");
var _Collection = _interopRequireDefault(require("../Collection/Collection"));
var _Workflow = _interopRequireDefault(require("../Workflow/Workflow"));
var _Editor = _interopRequireDefault(require("../Editor/Editor"));
var _NotFoundPage = _interopRequireDefault(require("./NotFoundPage"));
var _Header = _interopRequireDefault(require("./Header"));
var _react2 = require("@emotion/react");
const _excluded = ["collections", "render"];
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : String(i); }
function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
function _extends() { _extends = Object.assign ? Object.assign.bind() : 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 _EMOTION_STRINGIFIED_CSS_ERROR__() { return "You have tried to stringify object returned from `css` function. It isn't supposed to be used directly (e.g. as value of the `className` prop), but rather handed to emotion so it can handle it (e.g. as value of `css` prop)."; }
_reactTopbarProgressIndicator.default.config({
  barColors: {
    0: _decapCmsUiDefault.colors.active,
    '1.0': _decapCmsUiDefault.colors.active
  },
  shadowBlur: 0,
  barThickness: 2
});
const AppMainContainer = /*#__PURE__*/(0, _base.default)("div", {
  target: "eh2m33j2",
  label: "AppMainContainer"
})(process.env.NODE_ENV === "production" ? {
  name: "y0stlg",
  styles: "min-width:800px;max-width:1440px;margin:0 auto"
} : {
  name: "y0stlg",
  styles: "min-width:800px;max-width:1440px;margin:0 auto",
  map: "/*# sourceMappingURL=data:application/json;charset=utf-8;base64,[encoded data, 11676 characters] */",
  toString: _EMOTION_STRINGIFIED_CSS_ERROR__
});
const ErrorContainer = /*#__PURE__*/(0, _base.default)("div", {
  target: "eh2m33j1",
  label: "ErrorContainer"
})(process.env.NODE_ENV === "production" ? {
  name: "3zy121",
  styles: "margin:20px"
} : {
  name: "3zy121",
  styles: "margin:20px",
  map: "/*# sourceMappingURL=data:application/json;charset=utf-8;base64,[encoded data, 11676 characters] */",
  toString: _EMOTION_STRINGIFIED_CSS_ERROR__
});
const ErrorCodeBlock = /*#__PURE__*/(0, _base.default)("pre", {
  target: "eh2m33j0",
  label: "ErrorCodeBlock"
})(process.env.NODE_ENV === "production" ? {
  name: "1dps4tx",
  styles: "margin-left:20px;font-size:15px;line-height:1.5"
} : {
  name: "1dps4tx",
  styles: "margin-left:20px;font-size:15px;line-height:1.5",
  map: "/*# sourceMappingURL=data:application/json;charset=utf-8;base64,[encoded data, 11676 characters] */",
  toString: _EMOTION_STRINGIFIED_CSS_ERROR__
});
function getDefaultPath(collections) {
  const first = collections.filter(collection => collection.get('hide') !== true).first();
  if (first) {
    return `/collections/${first.get('name')}`;
  } else {
    throw new Error('Could not find a non hidden collection');
  }
}
function RouteInCollection(_ref) {
  let {
      collections,
      render
    } = _ref,
    props = _objectWithoutProperties(_ref, _excluded);
  const defaultPath = getDefaultPath(collections);
  return (0, _react2.jsx)(_reactRouterDom.Route, _extends({}, props, {
    render: routeProps => {
      const collectionExists = collections.get(routeProps.match.params.name);
      return collectionExists ? render(routeProps) : (0, _react2.jsx)(_reactRouterDom.Redirect, {
        to: defaultPath
      });
    }
  }));
}
class App extends _react.default.Component {
  configError(config) {
    const t = this.props.t;
    return (0, _react2.jsx)(ErrorContainer, null, (0, _react2.jsx)("h1", null, t('app.app.errorHeader')), (0, _react2.jsx)("div", null, (0, _react2.jsx)("strong", null, t('app.app.configErrors'), ":"), (0, _react2.jsx)(ErrorCodeBlock, null, config.error), (0, _react2.jsx)("span", null, t('app.app.checkConfigYml'))));
  }
  handleLogin(credentials) {
    this.props.loginUser(credentials);
  }
  authenticating() {
    const {
      auth,
      t
    } = this.props;
    const backend = (0, _backend.currentBackend)(this.props.config);
    if (backend == null) {
      return (0, _react2.jsx)("div", null, (0, _react2.jsx)("h1", null, t('app.app.waitingBackend')));
    }
    return (0, _react2.jsx)("div", null, (0, _react2.jsx)(_UI.Notifications, null), /*#__PURE__*/_react.default.createElement(backend.authComponent(), {
      onLogin: this.handleLogin.bind(this),
      error: auth.error,
      inProgress: auth.isFetching,
      siteId: this.props.config.backend.site_domain,
      base_url: this.props.config.backend.base_url,
      authEndpoint: this.props.config.backend.auth_endpoint,
      config: this.props.config,
      clearHash: () => _history.history.replace('/'),
      t
    }));
  }
  handleLinkClick(event, handler, ...args) {
    event.preventDefault();
    handler(...args);
  }
  render() {
    const {
      user,
      config,
      collections,
      logoutUser,
      isFetching,
      publishMode,
      useMediaLibrary,
      openMediaLibrary,
      t,
      showMediaButton
    } = this.props;
    if (config === null) {
      return null;
    }
    if (config.error) {
      return this.configError(config);
    }
    if (config.isFetching) {
      return (0, _react2.jsx)(_decapCmsUiDefault.Loader, {
        active: true
      }, t('app.app.loadingConfig'));
    }
    if (user == null) {
      return this.authenticating(t);
    }
    const defaultPath = getDefaultPath(collections);
    const hasWorkflow = publishMode === _publishModes.EDITORIAL_WORKFLOW;
    return (0, _react2.jsx)(_react.default.Fragment, null, (0, _react2.jsx)(_UI.Notifications, null), (0, _react2.jsx)(_Header.default, {
      user: user,
      collections: collections,
      onCreateEntryClick: _collections.createNewEntry,
      onLogoutClick: logoutUser,
      openMediaLibrary: openMediaLibrary,
      hasWorkflow: hasWorkflow,
      displayUrl: config.display_url,
      isTestRepo: config.backend.name === 'test-repo',
      showMediaButton: showMediaButton
    }), (0, _react2.jsx)(AppMainContainer, null, isFetching && (0, _react2.jsx)(_reactTopbarProgressIndicator.default, null), (0, _react2.jsx)(_reactRouterDom.Switch, null, (0, _react2.jsx)(_reactRouterDom.Redirect, {
      exact: true,
      from: "/",
      to: defaultPath
    }), (0, _react2.jsx)(_reactRouterDom.Redirect, {
      exact: true,
      from: "/search/",
      to: defaultPath
    }), (0, _react2.jsx)(RouteInCollection, {
      exact: true,
      collections: collections,
      path: "/collections/:name/search/",
      render: ({
        match
      }) => (0, _react2.jsx)(_reactRouterDom.Redirect, {
        to: `/collections/${match.params.name}`
      })
    }), (0, _react2.jsx)(_reactRouterDom.Redirect
    // This happens on Identity + Invite Only + External Provider email not matching
    // the registered user
    , {
      from: "/error=access_denied&error_description=Signups+not+allowed+for+this+instance",
      to: defaultPath
    }), hasWorkflow ? (0, _react2.jsx)(_reactRouterDom.Route, {
      path: "/workflow",
      component: _Workflow.default
    }) : null, (0, _react2.jsx)(RouteInCollection, {
      exact: true,
      collections: collections,
      path: "/collections/:name",
      render: props => (0, _react2.jsx)(_Collection.default, props)
    }), (0, _react2.jsx)(RouteInCollection, {
      path: "/collections/:name/new",
      collections: collections,
      render: props => (0, _react2.jsx)(_Editor.default, _extends({}, props, {
        newRecord: true
      }))
    }), (0, _react2.jsx)(RouteInCollection, {
      path: "/collections/:name/entries/*",
      collections: collections,
      render: props => (0, _react2.jsx)(_Editor.default, props)
    }), (0, _react2.jsx)(RouteInCollection, {
      path: "/collections/:name/search/:searchTerm",
      collections: collections,
      render: props => (0, _react2.jsx)(_Collection.default, _extends({}, props, {
        isSearchResults: true,
        isSingleSearchResult: true
      }))
    }), (0, _react2.jsx)(RouteInCollection, {
      collections: collections,
      path: "/collections/:name/filter/:filterTerm*",
      render: props => (0, _react2.jsx)(_Collection.default, props)
    }), (0, _react2.jsx)(_reactRouterDom.Route, {
      path: "/search/:searchTerm",
      render: props => (0, _react2.jsx)(_Collection.default, _extends({}, props, {
        isSearchResults: true
      }))
    }), (0, _react2.jsx)(RouteInCollection, {
      path: "/edit/:name/:entryName",
      collections: collections,
      render: ({
        match
      }) => {
        const {
          name,
          entryName
        } = match.params;
        return (0, _react2.jsx)(_reactRouterDom.Redirect, {
          to: `/collections/${name}/entries/${entryName}`
        });
      }
    }), (0, _react2.jsx)(_reactRouterDom.Route, {
      component: _NotFoundPage.default
    })), useMediaLibrary ? (0, _react2.jsx)(_MediaLibrary.default, null) : null));
  }
}
_defineProperty(App, "propTypes", {
  auth: _propTypes.default.object.isRequired,
  config: _propTypes.default.object.isRequired,
  collections: _reactImmutableProptypes.default.map.isRequired,
  loginUser: _propTypes.default.func.isRequired,
  logoutUser: _propTypes.default.func.isRequired,
  user: _propTypes.default.object,
  isFetching: _propTypes.default.bool.isRequired,
  publishMode: _propTypes.default.oneOf([_publishModes.SIMPLE, _publishModes.EDITORIAL_WORKFLOW]),
  siteId: _propTypes.default.string,
  useMediaLibrary: _propTypes.default.bool,
  openMediaLibrary: _propTypes.default.func.isRequired,
  showMediaButton: _propTypes.default.bool,
  t: _propTypes.default.func.isRequired
});
function mapStateToProps(state) {
  const {
    auth,
    config,
    collections,
    globalUI,
    mediaLibrary
  } = state;
  const user = auth.user;
  const isFetching = globalUI.isFetching;
  const publishMode = config.publish_mode;
  const useMediaLibrary = !mediaLibrary.get('externalLibrary');
  const showMediaButton = mediaLibrary.get('showMediaButton');
  return {
    auth,
    config,
    collections,
    user,
    isFetching,
    publishMode,
    showMediaButton,
    useMediaLibrary
  };
}
const mapDispatchToProps = {
  openMediaLibrary: _mediaLibrary.openMediaLibrary,
  loginUser: _auth.loginUser,
  logoutUser: _auth.logoutUser
};
var _default = exports.default = (0, _reactRedux.connect)(mapStateToProps, mapDispatchToProps)((0, _reactPolyglot.translate)()(App));