/* wp:polyfill */
"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = PostSavedState;
var _clsx = _interopRequireDefault(require("clsx"));
var _components = require("@wordpress/components");
var _compose = require("@wordpress/compose");
var _data = require("@wordpress/data");
var _element = require("@wordpress/element");
var _i18n = require("@wordpress/i18n");
var _icons = require("@wordpress/icons");
var _keycodes = require("@wordpress/keycodes");
var _preferences = require("@wordpress/preferences");
var _postStatus = require("../../components/post-status");
var _store = require("../../store");
var _jsxRuntime = require("react/jsx-runtime");
/**
 * External dependencies
 */

/**
 * WordPress dependencies
 */

/**
 * Internal dependencies
 */

/**
 * Component showing whether the post is saved or not and providing save
 * buttons.
 *
 * @param {Object}   props              Component props.
 * @param {?boolean} props.forceIsDirty Whether to force the post to be marked
 *                                      as dirty.
 * @return {import('react').ComponentType} The component.
 */function PostSavedState({
  forceIsDirty
}) {
  const [forceSavedMessage, setForceSavedMessage] = (0, _element.useState)(false);
  const isLargeViewport = (0, _compose.useViewportMatch)('small');
  const {
    isAutosaving,
    isDirty,
    isNew,
    isPublished,
    isSaveable,
    isSaving,
    isScheduled,
    hasPublishAction,
    showIconLabels,
    postStatus,
    postStatusHasChanged
  } = (0, _data.useSelect)(select => {
    var _getCurrentPost$_link;
    const {
      isEditedPostNew,
      isCurrentPostPublished,
      isCurrentPostScheduled,
      isEditedPostDirty,
      isSavingPost,
      isEditedPostSaveable,
      getCurrentPost,
      isAutosavingPost,
      getEditedPostAttribute,
      getPostEdits
    } = select(_store.store);
    const {
      get
    } = select(_preferences.store);
    return {
      isAutosaving: isAutosavingPost(),
      isDirty: forceIsDirty || isEditedPostDirty(),
      isNew: isEditedPostNew(),
      isPublished: isCurrentPostPublished(),
      isSaving: isSavingPost(),
      isSaveable: isEditedPostSaveable(),
      isScheduled: isCurrentPostScheduled(),
      hasPublishAction: (_getCurrentPost$_link = getCurrentPost()?._links?.['wp:action-publish']) !== null && _getCurrentPost$_link !== void 0 ? _getCurrentPost$_link : false,
      showIconLabels: get('core', 'showIconLabels'),
      postStatus: getEditedPostAttribute('status'),
      postStatusHasChanged: !!getPostEdits()?.status
    };
  }, [forceIsDirty]);
  const isPending = postStatus === 'pending';
  const {
    savePost
  } = (0, _data.useDispatch)(_store.store);
  const wasSaving = (0, _compose.usePrevious)(isSaving);
  (0, _element.useEffect)(() => {
    let timeoutId;
    if (wasSaving && !isSaving) {
      setForceSavedMessage(true);
      timeoutId = setTimeout(() => {
        setForceSavedMessage(false);
      }, 1000);
    }
    return () => clearTimeout(timeoutId);
  }, [isSaving]);

  // Once the post has been submitted for review this button
  // is not needed for the contributor role.
  if (!hasPublishAction && isPending) {
    return null;
  }

  // We shouldn't render the button if the post has not one of the following statuses: pending, draft, auto-draft.
  // The reason for this is that this button handles the `save as pending` and `save draft` actions.
  // An exception for this is when the post has a custom status and there should be a way to save changes without
  // having to publish. This should be handled better in the future when custom statuses have better support.
  // @see https://github.com/WordPress/gutenberg/issues/3144.
  const isIneligibleStatus = !['pending', 'draft', 'auto-draft'].includes(postStatus) && _postStatus.STATUS_OPTIONS.map(({
    value
  }) => value).includes(postStatus);
  if (isPublished || isScheduled || isIneligibleStatus || postStatusHasChanged && ['pending', 'draft'].includes(postStatus)) {
    return null;
  }

  /* translators: button label text should, if possible, be under 16 characters. */
  const label = isPending ? (0, _i18n.__)('Save as pending') : (0, _i18n.__)('Save draft');

  /* translators: button label text should, if possible, be under 16 characters. */
  const shortLabel = (0, _i18n.__)('Save');
  const isSaved = forceSavedMessage || !isNew && !isDirty;
  const isSavedState = isSaving || isSaved;
  const isDisabled = isSaving || isSaved || !isSaveable;
  let text;
  if (isSaving) {
    text = isAutosaving ? (0, _i18n.__)('Autosaving') : (0, _i18n.__)('Saving');
  } else if (isSaved) {
    text = (0, _i18n.__)('Saved');
  } else if (isLargeViewport) {
    text = label;
  } else if (showIconLabels) {
    text = shortLabel;
  }

  // Use common Button instance for all saved states so that focus is not
  // lost.
  return /*#__PURE__*/(0, _jsxRuntime.jsxs)(_components.Button, {
    className: isSaveable || isSaving ? (0, _clsx.default)({
      'editor-post-save-draft': !isSavedState,
      'editor-post-saved-state': isSavedState,
      'is-saving': isSaving,
      'is-autosaving': isAutosaving,
      'is-saved': isSaved,
      [(0, _components.__unstableGetAnimateClassName)({
        type: 'loading'
      })]: isSaving
    }) : undefined,
    onClick: isDisabled ? undefined : () => savePost()
    /*
     * We want the tooltip to show the keyboard shortcut only when the
     * button does something, i.e. when it's not disabled.
     */,
    shortcut: isDisabled ? undefined : _keycodes.displayShortcut.primary('s'),
    variant: "tertiary",
    size: "compact",
    icon: isLargeViewport ? undefined : _icons.cloudUpload,
    label: text || label,
    "aria-disabled": isDisabled,
    children: [isSavedState && /*#__PURE__*/(0, _jsxRuntime.jsx)(_icons.Icon, {
      icon: isSaved ? _icons.check : _icons.cloud
    }), text]
  });
}
//# sourceMappingURL=index.js.map