"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;
var _clsx = _interopRequireDefault(require("clsx"));
var _i18n = require("@wordpress/i18n");
var _hooks = require("@wordpress/hooks");
var _components = require("@wordpress/components");
var _blob = require("@wordpress/blob");
var _element = require("@wordpress/element");
var _compose = require("@wordpress/compose");
var _data = require("@wordpress/data");
var _blockEditor = require("@wordpress/block-editor");
var _coreData = require("@wordpress/core-data");
var _check = _interopRequireDefault(require("./check"));
var _store = require("../../store");
var _jsxRuntime = require("react/jsx-runtime");
/**
 * External dependencies
 */

/**
 * WordPress dependencies
 */

/**
 * Internal dependencies
 */

const ALLOWED_MEDIA_TYPES = ['image'];

// Used when labels from post type were not yet loaded or when they are not present.
const DEFAULT_FEATURE_IMAGE_LABEL = (0, _i18n.__)('Featured image');
const DEFAULT_SET_FEATURE_IMAGE_LABEL = (0, _i18n.__)('Add a featured image');
const instructions = /*#__PURE__*/(0, _jsxRuntime.jsx)("p", {
  children: (0, _i18n.__)('To edit the featured image, you need permission to upload media.')
});
function getMediaDetails(media, postId) {
  var _media$media_details$, _media$media_details$2;
  if (!media) {
    return {};
  }
  const defaultSize = (0, _hooks.applyFilters)('editor.PostFeaturedImage.imageSize', 'large', media.id, postId);
  if (defaultSize in ((_media$media_details$ = media?.media_details?.sizes) !== null && _media$media_details$ !== void 0 ? _media$media_details$ : {})) {
    return {
      mediaWidth: media.media_details.sizes[defaultSize].width,
      mediaHeight: media.media_details.sizes[defaultSize].height,
      mediaSourceUrl: media.media_details.sizes[defaultSize].source_url
    };
  }

  // Use fallbackSize when defaultSize is not available.
  const fallbackSize = (0, _hooks.applyFilters)('editor.PostFeaturedImage.imageSize', 'thumbnail', media.id, postId);
  if (fallbackSize in ((_media$media_details$2 = media?.media_details?.sizes) !== null && _media$media_details$2 !== void 0 ? _media$media_details$2 : {})) {
    return {
      mediaWidth: media.media_details.sizes[fallbackSize].width,
      mediaHeight: media.media_details.sizes[fallbackSize].height,
      mediaSourceUrl: media.media_details.sizes[fallbackSize].source_url
    };
  }

  // Use full image size when fallbackSize and defaultSize are not available.
  return {
    mediaWidth: media.media_details.width,
    mediaHeight: media.media_details.height,
    mediaSourceUrl: media.source_url
  };
}
function PostFeaturedImage({
  currentPostId,
  featuredImageId,
  onUpdateImage,
  onRemoveImage,
  media,
  postType,
  noticeUI,
  noticeOperations,
  isRequestingFeaturedImageMedia
}) {
  const returnsFocusRef = (0, _element.useRef)(false);
  const [isLoading, setIsLoading] = (0, _element.useState)(false);
  const {
    getSettings
  } = (0, _data.useSelect)(_blockEditor.store);
  const {
    mediaSourceUrl
  } = getMediaDetails(media, currentPostId);
  function onDropFiles(filesList) {
    getSettings().mediaUpload({
      allowedTypes: ALLOWED_MEDIA_TYPES,
      filesList,
      onFileChange([image]) {
        if ((0, _blob.isBlobURL)(image?.url)) {
          setIsLoading(true);
          return;
        }
        if (image) {
          onUpdateImage(image);
        }
        setIsLoading(false);
      },
      onError(message) {
        noticeOperations.removeAllNotices();
        noticeOperations.createErrorNotice(message);
      },
      multiple: false
    });
  }

  /**
   * Generates the featured image alt text for this editing context.
   *
   * @param {Object} imageMedia                               The image media object.
   * @param {string} imageMedia.alt_text                      The alternative text of the image.
   * @param {Object} imageMedia.media_details                 The media details of the image.
   * @param {Object} imageMedia.media_details.sizes           The sizes of the image.
   * @param {Object} imageMedia.media_details.sizes.full      The full size details of the image.
   * @param {string} imageMedia.media_details.sizes.full.file The file name of the full size image.
   * @param {string} imageMedia.slug                          The slug of the image.
   * @return {string} The featured image alt text.
   */
  function getImageDescription(imageMedia) {
    if (imageMedia.alt_text) {
      return (0, _i18n.sprintf)(
      // Translators: %s: The selected image alt text.
      (0, _i18n.__)('Current image: %s'), imageMedia.alt_text);
    }
    return (0, _i18n.sprintf)(
    // Translators: %s: The selected image filename.
    (0, _i18n.__)('The current image has no alternative text. The file name is: %s'), imageMedia.media_details.sizes?.full?.file || imageMedia.slug);
  }
  function returnFocus(node) {
    if (returnsFocusRef.current && node) {
      node.focus();
      returnsFocusRef.current = false;
    }
  }
  const isMissingMedia = !isRequestingFeaturedImageMedia && !!featuredImageId && !media;
  return /*#__PURE__*/(0, _jsxRuntime.jsxs)(_check.default, {
    children: [noticeUI, /*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
      className: "editor-post-featured-image",
      children: [media && /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
        id: `editor-post-featured-image-${featuredImageId}-describedby`,
        className: "hidden",
        children: getImageDescription(media)
      }), /*#__PURE__*/(0, _jsxRuntime.jsx)(_blockEditor.MediaUploadCheck, {
        fallback: instructions,
        children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_blockEditor.MediaUpload, {
          title: postType?.labels?.featured_image || DEFAULT_FEATURE_IMAGE_LABEL,
          onSelect: onUpdateImage,
          unstableFeaturedImageFlow: true,
          allowedTypes: ALLOWED_MEDIA_TYPES,
          modalClass: "editor-post-featured-image__media-modal",
          render: ({
            open
          }) => /*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
            className: "editor-post-featured-image__container",
            children: [isMissingMedia ? /*#__PURE__*/(0, _jsxRuntime.jsx)(_components.Notice, {
              status: "warning",
              isDismissible: false,
              children: (0, _i18n.__)('Could not retrieve the featured image data.')
            }) : /*#__PURE__*/(0, _jsxRuntime.jsxs)(_components.Button, {
              __next40pxDefaultSize: true,
              ref: returnFocus,
              className: !featuredImageId ? 'editor-post-featured-image__toggle' : 'editor-post-featured-image__preview',
              onClick: open,
              "aria-label": !featuredImageId ? null : (0, _i18n.__)('Edit or replace the featured image'),
              "aria-describedby": !featuredImageId ? null : `editor-post-featured-image-${featuredImageId}-describedby`,
              "aria-haspopup": "dialog",
              disabled: isLoading,
              accessibleWhenDisabled: true,
              children: [!!featuredImageId && media && /*#__PURE__*/(0, _jsxRuntime.jsx)("img", {
                className: "editor-post-featured-image__preview-image",
                src: mediaSourceUrl,
                alt: getImageDescription(media)
              }), (isLoading || isRequestingFeaturedImageMedia) && /*#__PURE__*/(0, _jsxRuntime.jsx)(_components.Spinner, {}), !featuredImageId && !isLoading && (postType?.labels?.set_featured_image || DEFAULT_SET_FEATURE_IMAGE_LABEL)]
            }), !!featuredImageId && /*#__PURE__*/(0, _jsxRuntime.jsxs)(_components.__experimentalHStack, {
              className: (0, _clsx.default)('editor-post-featured-image__actions', {
                'editor-post-featured-image__actions-missing-image': isMissingMedia,
                'editor-post-featured-image__actions-is-requesting-image': isRequestingFeaturedImageMedia
              }),
              children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_components.Button, {
                __next40pxDefaultSize: true,
                className: "editor-post-featured-image__action",
                onClick: open,
                "aria-haspopup": "dialog",
                variant: isMissingMedia ? 'secondary' : undefined,
                children: (0, _i18n.__)('Replace')
              }), /*#__PURE__*/(0, _jsxRuntime.jsx)(_components.Button, {
                __next40pxDefaultSize: true,
                className: "editor-post-featured-image__action",
                onClick: () => {
                  onRemoveImage();
                  // Signal that the toggle button should be focused,
                  // when it is rendered. Can't focus it directly here
                  // because it's rendered conditionally.
                  returnsFocusRef.current = true;
                },
                variant: isMissingMedia ? 'secondary' : undefined,
                isDestructive: isMissingMedia,
                children: (0, _i18n.__)('Remove')
              })]
            }), /*#__PURE__*/(0, _jsxRuntime.jsx)(_components.DropZone, {
              onFilesDrop: onDropFiles
            })]
          }),
          value: featuredImageId
        })
      })]
    })]
  });
}
const applyWithSelect = (0, _data.withSelect)(select => {
  const {
    getEntityRecord,
    getPostType,
    hasFinishedResolution
  } = select(_coreData.store);
  const {
    getCurrentPostId,
    getEditedPostAttribute
  } = select(_store.store);
  const featuredImageId = getEditedPostAttribute('featured_media');
  return {
    media: featuredImageId ? getEntityRecord('postType', 'attachment', featuredImageId, {
      context: 'view'
    }) : null,
    currentPostId: getCurrentPostId(),
    postType: getPostType(getEditedPostAttribute('type')),
    featuredImageId,
    isRequestingFeaturedImageMedia: !!featuredImageId && !hasFinishedResolution('getEntityRecord', ['postType', 'attachment', featuredImageId, {
      context: 'view'
    }])
  };
});
const applyWithDispatch = (0, _data.withDispatch)((dispatch, {
  noticeOperations
}, {
  select
}) => {
  const {
    editPost
  } = dispatch(_store.store);
  return {
    onUpdateImage(image) {
      editPost({
        featured_media: image.id
      });
    },
    onDropImage(filesList) {
      select(_blockEditor.store).getSettings().mediaUpload({
        allowedTypes: ['image'],
        filesList,
        onFileChange([image]) {
          editPost({
            featured_media: image.id
          });
        },
        onError(message) {
          noticeOperations.removeAllNotices();
          noticeOperations.createErrorNotice(message);
        },
        multiple: false
      });
    },
    onRemoveImage() {
      editPost({
        featured_media: 0
      });
    }
  };
});

/**
 * Renders the component for managing the featured image of a post.
 *
 * @param {Object}   props                  Props.
 * @param {number}   props.currentPostId    ID of the current post.
 * @param {number}   props.featuredImageId  ID of the featured image.
 * @param {Function} props.onUpdateImage    Function to call when the image is updated.
 * @param {Function} props.onRemoveImage    Function to call when the image is removed.
 * @param {Object}   props.media            The media object representing the featured image.
 * @param {string}   props.postType         Post type.
 * @param {Element}  props.noticeUI         UI for displaying notices.
 * @param {Object}   props.noticeOperations Operations for managing notices.
 *
 * @return {Element} Component to be rendered .
 */
var _default = exports.default = (0, _compose.compose)(_components.withNotices, applyWithSelect, applyWithDispatch, (0, _components.withFilters)('editor.PostFeaturedImage'))(PostFeaturedImage);
//# sourceMappingURL=index.js.map