"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;
var _i18n = require("@wordpress/i18n");
var _components = require("@wordpress/components");
var _data = require("@wordpress/data");
var _element = require("@wordpress/element");
var _blockEditor = require("@wordpress/block-editor");
var _header = _interopRequireDefault(require("../header"));
var _lockUnlock = require("../../../lock-unlock");
var _revisions = _interopRequireDefault(require("../../revisions"));
var _store = require("../../../store");
var _useGlobalStylesRevisions = _interopRequireDefault(require("./use-global-styles-revisions"));
var _revisionsButtons = _interopRequireDefault(require("./revisions-buttons"));
var _styleBook = _interopRequireDefault(require("../../style-book"));
var _pagination = _interopRequireDefault(require("../../pagination"));
var _jsxRuntime = require("react/jsx-runtime");
/**
 * WordPress dependencies
 */

/**
 * Internal dependencies
 */

const {
  GlobalStylesContext,
  areGlobalStyleConfigsEqual
} = (0, _lockUnlock.unlock)(_blockEditor.privateApis);
const PAGE_SIZE = 10;
function ScreenRevisions() {
  const {
    user: currentEditorGlobalStyles,
    setUserConfig
  } = (0, _element.useContext)(GlobalStylesContext);
  const {
    blocks,
    editorCanvasContainerView
  } = (0, _data.useSelect)(select => ({
    editorCanvasContainerView: (0, _lockUnlock.unlock)(select(_store.store)).getEditorCanvasContainerView(),
    blocks: select(_blockEditor.store).getBlocks()
  }), []);
  const [currentPage, setCurrentPage] = (0, _element.useState)(1);
  const [currentRevisions, setCurrentRevisions] = (0, _element.useState)([]);
  const {
    revisions,
    isLoading,
    hasUnsavedChanges,
    revisionsCount
  } = (0, _useGlobalStylesRevisions.default)({
    query: {
      per_page: PAGE_SIZE,
      page: currentPage
    }
  });
  const numPages = Math.ceil(revisionsCount / PAGE_SIZE);
  const [currentlySelectedRevision, setCurrentlySelectedRevision] = (0, _element.useState)(currentEditorGlobalStyles);
  const [isLoadingRevisionWithUnsavedChanges, setIsLoadingRevisionWithUnsavedChanges] = (0, _element.useState)(false);
  const {
    setEditorCanvasContainerView
  } = (0, _lockUnlock.unlock)((0, _data.useDispatch)(_store.store));
  const selectedRevisionMatchesEditorStyles = areGlobalStyleConfigsEqual(currentlySelectedRevision, currentEditorGlobalStyles);

  // The actual code that triggers the revisions screen to navigate back
  // to the home screen in in `packages/edit-site/src/components/global-styles/ui.js`.
  const onCloseRevisions = () => {
    const canvasContainerView = editorCanvasContainerView === 'global-styles-revisions:style-book' ? 'style-book' : undefined;
    setEditorCanvasContainerView(canvasContainerView);
  };
  const restoreRevision = revision => {
    setUserConfig(() => revision);
    setIsLoadingRevisionWithUnsavedChanges(false);
    onCloseRevisions();
  };
  (0, _element.useEffect)(() => {
    if (!isLoading && revisions.length) {
      setCurrentRevisions(revisions);
    }
  }, [revisions, isLoading]);
  const firstRevision = revisions[0];
  const currentlySelectedRevisionId = currentlySelectedRevision?.id;
  const shouldSelectFirstItem = !!firstRevision?.id && !selectedRevisionMatchesEditorStyles && !currentlySelectedRevisionId;
  (0, _element.useEffect)(() => {
    /*
     * Ensure that the first item is selected and loaded into the preview pane
     * when no revision is selected and the selected styles don't match the current editor styles.
     * This is required in case editor styles are changed outside the revisions panel,
     * e.g., via the reset styles function of useGlobalStylesReset().
     * See: https://github.com/WordPress/gutenberg/issues/55866
     */
    if (shouldSelectFirstItem) {
      setCurrentlySelectedRevision(firstRevision);
    }
  }, [shouldSelectFirstItem, firstRevision]);

  // Only display load button if there is a revision to load,
  // and it is different from the current editor styles.
  const isLoadButtonEnabled = !!currentlySelectedRevisionId && currentlySelectedRevisionId !== 'unsaved' && !selectedRevisionMatchesEditorStyles;
  const hasRevisions = !!currentRevisions.length;
  return /*#__PURE__*/(0, _jsxRuntime.jsxs)(_jsxRuntime.Fragment, {
    children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_header.default, {
      title: revisionsCount &&
      // translators: %s: number of revisions.
      (0, _i18n.sprintf)((0, _i18n.__)('Revisions (%s)'), revisionsCount),
      description: (0, _i18n.__)('Click on previously saved styles to preview them. To restore a selected version to the editor, hit "Apply." When you\'re ready, use the Save button to save your changes.'),
      onBack: onCloseRevisions
    }), !hasRevisions && /*#__PURE__*/(0, _jsxRuntime.jsx)(_components.Spinner, {
      className: "edit-site-global-styles-screen-revisions__loading"
    }), hasRevisions && (editorCanvasContainerView === 'global-styles-revisions:style-book' ? /*#__PURE__*/(0, _jsxRuntime.jsx)(_styleBook.default, {
      userConfig: currentlySelectedRevision,
      isSelected: () => {},
      onClose: () => {
        setEditorCanvasContainerView('global-styles-revisions');
      }
    }) : /*#__PURE__*/(0, _jsxRuntime.jsx)(_revisions.default, {
      blocks: blocks,
      userConfig: currentlySelectedRevision,
      closeButtonLabel: (0, _i18n.__)('Close revisions')
    })), /*#__PURE__*/(0, _jsxRuntime.jsx)(_revisionsButtons.default, {
      onChange: setCurrentlySelectedRevision,
      selectedRevisionId: currentlySelectedRevisionId,
      userRevisions: currentRevisions,
      canApplyRevision: isLoadButtonEnabled,
      onApplyRevision: () => hasUnsavedChanges ? setIsLoadingRevisionWithUnsavedChanges(true) : restoreRevision(currentlySelectedRevision)
    }), numPages > 1 && /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
      className: "edit-site-global-styles-screen-revisions__footer",
      children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_pagination.default, {
        className: "edit-site-global-styles-screen-revisions__pagination",
        currentPage: currentPage,
        numPages: numPages,
        changePage: setCurrentPage,
        totalItems: revisionsCount,
        disabled: isLoading,
        label: (0, _i18n.__)('Global Styles pagination navigation')
      })
    }), isLoadingRevisionWithUnsavedChanges && /*#__PURE__*/(0, _jsxRuntime.jsx)(_components.__experimentalConfirmDialog, {
      isOpen: isLoadingRevisionWithUnsavedChanges,
      confirmButtonText: (0, _i18n.__)('Apply'),
      onConfirm: () => restoreRevision(currentlySelectedRevision),
      onCancel: () => setIsLoadingRevisionWithUnsavedChanges(false),
      size: "medium",
      children: (0, _i18n.__)('Are you sure you want to apply this revision? Any unsaved changes will be lost.')
    })]
  });
}
var _default = exports.default = ScreenRevisions;
//# sourceMappingURL=index.js.map