"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// packages/block-editor/src/components/media-replace-flow/index.js
var media_replace_flow_exports = {};
__export(media_replace_flow_exports, {
  default: () => media_replace_flow_default
});
module.exports = __toCommonJS(media_replace_flow_exports);
var import_i18n = require("@wordpress/i18n");
var import_a11y = require("@wordpress/a11y");
var import_components = require("@wordpress/components");
var import_data = require("@wordpress/data");
var import_keycodes = require("@wordpress/keycodes");
var import_icons = require("@wordpress/icons");
var import_compose = require("@wordpress/compose");
var import_dom = require("@wordpress/dom");
var import_notices = require("@wordpress/notices");
var import_element = require("@wordpress/element");
var import_media_upload = __toESM(require("../media-upload"));
var import_check = __toESM(require("../media-upload/check"));
var import_link_control = __toESM(require("../link-control"));
var import_store = require("../../store");
var import_utils = require("../media-placeholder/utils");
var import_jsx_runtime = require("react/jsx-runtime");
var noop = () => {
};
var uniqueId = 0;
var MediaReplaceFlow = ({
  mediaURL,
  mediaId,
  mediaIds,
  allowedTypes,
  accept,
  onError,
  onSelect,
  onSelectURL,
  onReset,
  onToggleFeaturedImage,
  useFeaturedImage,
  onFilesUpload = noop,
  name = (0, import_i18n.__)("Replace"),
  createNotice,
  removeNotice,
  children,
  multiple = false,
  addToGallery,
  handleUpload = true,
  popoverProps,
  renderToggle,
  className
}) => {
  const { mediaUpload, allowedMimeTypes } = (0, import_data.useSelect)((select) => {
    const { getSettings } = select(import_store.store);
    const settings = getSettings();
    return {
      mediaUpload: settings.mediaUpload,
      allowedMimeTypes: settings.allowedMimeTypes
    };
  }, []);
  const errorNoticeID = `block-editor/media-replace-flow/error-notice/${++uniqueId}`;
  const computedAccept = (0, import_element.useMemo)(
    () => (0, import_utils.getComputedAcceptAttribute)(
      allowedTypes,
      allowedMimeTypes,
      accept
    ),
    [allowedTypes, allowedMimeTypes, accept]
  );
  const onUploadError = (message) => {
    const safeMessage = (0, import_dom.__unstableStripHTML)(message);
    if (onError) {
      onError(safeMessage);
      return;
    }
    setTimeout(() => {
      createNotice("error", safeMessage, {
        speak: true,
        id: errorNoticeID,
        isDismissible: true
      });
    }, 1e3);
  };
  const selectMedia = (media, closeMenu) => {
    if (useFeaturedImage && onToggleFeaturedImage) {
      onToggleFeaturedImage();
    }
    closeMenu();
    onSelect(media);
    (0, import_a11y.speak)((0, import_i18n.__)("The media file has been replaced"));
    removeNotice(errorNoticeID);
  };
  const uploadFiles = (event, closeMenu) => {
    const files = event.target.files;
    if (!handleUpload) {
      closeMenu();
      return onSelect(files);
    }
    onFilesUpload(files);
    mediaUpload({
      allowedTypes,
      filesList: files,
      onFileChange: ([media]) => {
        selectMedia(media, closeMenu);
      },
      onError: onUploadError
    });
  };
  const openOnArrowDown = (event) => {
    if (event.keyCode === import_keycodes.DOWN) {
      event.preventDefault();
      event.target.click();
    }
  };
  const onlyAllowsImages = () => {
    if (!allowedTypes || allowedTypes.length === 0) {
      return false;
    }
    return allowedTypes.every(
      (allowedType) => allowedType === "image" || allowedType.startsWith("image/")
    );
  };
  const gallery = multiple && onlyAllowsImages();
  return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
    import_components.Dropdown,
    {
      popoverProps,
      className,
      contentClassName: "block-editor-media-replace-flow__options",
      renderToggle: ({ isOpen, onToggle }) => {
        if (renderToggle) {
          return renderToggle({
            "aria-expanded": isOpen,
            "aria-haspopup": "true",
            onClick: onToggle,
            onKeyDown: openOnArrowDown,
            children: name
          });
        }
        return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
          import_components.ToolbarButton,
          {
            "aria-expanded": isOpen,
            "aria-haspopup": "true",
            onClick: onToggle,
            onKeyDown: openOnArrowDown,
            children: name
          }
        );
      },
      renderContent: ({ onClose }) => /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_jsx_runtime.Fragment, { children: [
        /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_components.NavigableMenu, { className: "block-editor-media-replace-flow__media-upload-menu", children: [
          /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_check.default, { children: [
            /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
              import_media_upload.default,
              {
                gallery,
                addToGallery,
                multiple,
                value: multiple ? mediaIds : mediaId,
                onSelect: (media) => selectMedia(media, onClose),
                allowedTypes,
                render: ({ open }) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
                  import_components.MenuItem,
                  {
                    icon: import_icons.media,
                    onClick: open,
                    children: (0, import_i18n.__)("Open Media Library")
                  }
                )
              }
            ),
            /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
              import_components.FormFileUpload,
              {
                onChange: (event) => {
                  uploadFiles(event, onClose);
                },
                accept: computedAccept,
                multiple: !!multiple,
                render: ({ openFileDialog }) => {
                  return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
                    import_components.MenuItem,
                    {
                      icon: import_icons.upload,
                      onClick: () => {
                        openFileDialog();
                      },
                      children: (0, import_i18n._x)("Upload", "verb")
                    }
                  );
                }
              }
            )
          ] }),
          onToggleFeaturedImage && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
            import_components.MenuItem,
            {
              icon: import_icons.postFeaturedImage,
              onClick: onToggleFeaturedImage,
              isPressed: useFeaturedImage,
              children: (0, import_i18n.__)("Use featured image")
            }
          ),
          mediaURL && onReset && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
            import_components.MenuItem,
            {
              onClick: () => {
                onReset();
                onClose();
              },
              children: (0, import_i18n.__)("Reset")
            }
          ),
          typeof children === "function" ? children({ onClose }) : children
        ] }),
        onSelectURL && /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("form", { className: "block-editor-media-flow__url-input", children: [
          /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { className: "block-editor-media-replace-flow__image-url-label", children: (0, import_i18n.__)("Current media URL:") }),
          /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
            import_link_control.default,
            {
              value: { url: mediaURL },
              settings: [],
              showSuggestions: false,
              onChange: ({ url }) => {
                onSelectURL(url);
              },
              searchInputPlaceholder: (0, import_i18n.__)(
                "Paste or type URL"
              )
            }
          )
        ] })
      ] })
    }
  );
};
var media_replace_flow_default = (0, import_compose.compose)([
  (0, import_data.withDispatch)((dispatch) => {
    const { createNotice, removeNotice } = dispatch(import_notices.store);
    return {
      createNotice,
      removeNotice
    };
  }),
  (0, import_components.withFilters)("editor.MediaReplaceFlow")
])(MediaReplaceFlow);
//# sourceMappingURL=index.js.map
