// packages/block-editor/src/components/media-placeholder/index.js
import clsx from "clsx";
import {
  Button,
  FormFileUpload,
  Placeholder,
  DropZone,
  __experimentalInputControl as InputControl,
  __experimentalInputControlSuffixWrapper as InputControlSuffixWrapper,
  withFilters
} from "@wordpress/components";
import { __, _x } from "@wordpress/i18n";
import { useState, useEffect, useMemo } from "@wordpress/element";
import { useSelect } from "@wordpress/data";
import { keyboardReturn } from "@wordpress/icons";
import deprecated from "@wordpress/deprecated";
import MediaUpload from "../media-upload";
import MediaUploadCheck from "../media-upload/check";
import URLPopover from "../url-popover";
import { store as blockEditorStore } from "../../store";
import { parseDropEvent } from "../use-on-block-drop";
import { getComputedAcceptAttribute } from "./utils";
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
var noop = () => {
};
var InsertFromURLPopover = ({
  src,
  onChange,
  onSubmit,
  onClose,
  popoverAnchor
}) => /* @__PURE__ */ jsx(URLPopover, { anchor: popoverAnchor, onClose, children: /* @__PURE__ */ jsx(
  "form",
  {
    className: "block-editor-media-placeholder__url-input-form",
    onSubmit,
    children: /* @__PURE__ */ jsx(
      InputControl,
      {
        __next40pxDefaultSize: true,
        label: __("URL"),
        type: "text",
        hideLabelFromVision: true,
        placeholder: __("Paste or type URL"),
        onChange,
        value: src,
        suffix: /* @__PURE__ */ jsx(InputControlSuffixWrapper, { variant: "control", children: /* @__PURE__ */ jsx(
          Button,
          {
            size: "small",
            icon: keyboardReturn,
            label: __("Apply"),
            type: "submit"
          }
        ) })
      }
    )
  }
) });
var URLSelectionUI = ({ src, onChangeSrc, onSelectURL }) => {
  const [popoverAnchor, setPopoverAnchor] = useState(null);
  const [isURLInputVisible, setIsURLInputVisible] = useState(false);
  const openURLInput = () => {
    setIsURLInputVisible(true);
  };
  const closeURLInput = () => {
    setIsURLInputVisible(false);
    popoverAnchor?.focus();
  };
  const onSubmitSrc = (event) => {
    event.preventDefault();
    if (src && onSelectURL) {
      onSelectURL(src);
      closeURLInput();
    }
  };
  return /* @__PURE__ */ jsxs("div", { className: "block-editor-media-placeholder__url-input-container", children: [
    /* @__PURE__ */ jsx(
      Button,
      {
        __next40pxDefaultSize: true,
        className: "block-editor-media-placeholder__button",
        onClick: openURLInput,
        isPressed: isURLInputVisible,
        variant: "secondary",
        "aria-haspopup": "dialog",
        ref: setPopoverAnchor,
        children: __("Insert from URL")
      }
    ),
    isURLInputVisible && /* @__PURE__ */ jsx(
      InsertFromURLPopover,
      {
        src,
        onChange: onChangeSrc,
        onSubmit: onSubmitSrc,
        onClose: closeURLInput,
        popoverAnchor
      }
    )
  ] });
};
function MediaPlaceholder({
  value = {},
  allowedTypes,
  className,
  icon,
  labels = {},
  mediaPreview,
  notices,
  isAppender,
  accept,
  addToGallery,
  multiple = false,
  handleUpload = true,
  disableDropZone,
  disableMediaButtons,
  onError,
  onSelect,
  onCancel,
  onSelectURL,
  onToggleFeaturedImage,
  onDoubleClick,
  onFilesPreUpload = noop,
  onHTMLDrop: deprecatedOnHTMLDrop,
  children,
  mediaLibraryButton,
  placeholder,
  style
}) {
  if (deprecatedOnHTMLDrop) {
    deprecated("wp.blockEditor.MediaPlaceholder onHTMLDrop prop", {
      since: "6.2",
      version: "6.4"
    });
  }
  const { mediaUpload, allowedMimeTypes } = useSelect((select) => {
    const { getSettings } = select(blockEditorStore);
    const settings = getSettings();
    return {
      mediaUpload: settings.mediaUpload,
      allowedMimeTypes: settings.allowedMimeTypes
    };
  }, []);
  const [src, setSrc] = useState("");
  useEffect(() => {
    setSrc(value?.src ?? "");
  }, [value?.src]);
  const computedAccept = useMemo(
    () => getComputedAcceptAttribute(
      allowedTypes,
      allowedMimeTypes,
      accept
    ),
    [allowedTypes, allowedMimeTypes, accept]
  );
  const onlyAllowsImages = () => {
    if (!allowedTypes || allowedTypes.length === 0) {
      return false;
    }
    return allowedTypes.every(
      (allowedType) => allowedType === "image" || allowedType.startsWith("image/")
    );
  };
  const onFilesUpload = (files) => {
    if (!handleUpload || typeof handleUpload === "function" && !handleUpload(files)) {
      return onSelect(files);
    }
    onFilesPreUpload(files);
    let setMedia;
    if (multiple) {
      if (addToGallery) {
        let lastMediaPassed = [];
        setMedia = (newMedia) => {
          const filteredMedia = (value ?? []).filter((item) => {
            if (item.id) {
              return !lastMediaPassed.some(
                // Be sure to convert to number for comparison.
                ({ id }) => Number(id) === Number(item.id)
              );
            }
            return !lastMediaPassed.some(
              ({ urlSlug }) => item.url.includes(urlSlug)
            );
          });
          onSelect(filteredMedia.concat(newMedia));
          lastMediaPassed = newMedia.map((media) => {
            const cutOffIndex = media.url.lastIndexOf(".");
            const urlSlug = media.url.slice(0, cutOffIndex);
            return { id: media.id, urlSlug };
          });
        };
      } else {
        setMedia = onSelect;
      }
    } else {
      setMedia = ([media]) => onSelect(media);
    }
    mediaUpload({
      allowedTypes,
      filesList: files,
      onFileChange: setMedia,
      onError,
      multiple
    });
  };
  async function handleBlocksDrop(event) {
    const { blocks } = parseDropEvent(event);
    if (!blocks?.length) {
      return;
    }
    const uploadedMediaList = await Promise.all(
      blocks.map((block) => {
        const blockType = block.name.split("/")[1];
        if (block.attributes.id) {
          block.attributes.type = blockType;
          return block.attributes;
        }
        return new Promise((resolve, reject) => {
          window.fetch(block.attributes.url).then((response) => response.blob()).then(
            (blob) => mediaUpload({
              filesList: [blob],
              additionalData: {
                title: block.attributes.title,
                alt_text: block.attributes.alt,
                caption: block.attributes.caption,
                type: blockType
              },
              onFileChange: ([media]) => {
                if (media.id) {
                  resolve(media);
                }
              },
              allowedTypes,
              onError: reject
            })
          ).catch(() => resolve(block.attributes.url));
        });
      })
    ).catch((err) => onError(err));
    if (!uploadedMediaList?.length) {
      return;
    }
    onSelect(multiple ? uploadedMediaList : uploadedMediaList[0]);
  }
  const onUpload = (event) => {
    onFilesUpload(event.target.files);
  };
  const defaultRenderPlaceholder = (content) => {
    let { instructions, title } = labels;
    if (!mediaUpload && !onSelectURL) {
      instructions = __(
        "To edit this block, you need permission to upload media."
      );
    }
    if (instructions === void 0 || title === void 0) {
      const typesAllowed = allowedTypes ?? [];
      const [firstAllowedType] = typesAllowed;
      const isOneType = 1 === typesAllowed.length;
      const isAudio = isOneType && "audio" === firstAllowedType;
      const isImage = isOneType && "image" === firstAllowedType;
      const isVideo = isOneType && "video" === firstAllowedType;
      if (instructions === void 0 && mediaUpload) {
        instructions = __(
          "Drag and drop an image or video, upload, or choose from your library."
        );
        if (isAudio) {
          instructions = __(
            "Drag and drop an audio file, upload, or choose from your library."
          );
        } else if (isImage) {
          instructions = __(
            "Drag and drop an image, upload, or choose from your library."
          );
        } else if (isVideo) {
          instructions = __(
            "Drag and drop a video, upload, or choose from your library."
          );
        }
      }
      if (title === void 0) {
        title = __("Media");
        if (isAudio) {
          title = __("Audio");
        } else if (isImage) {
          title = __("Image");
        } else if (isVideo) {
          title = __("Video");
        }
      }
    }
    const placeholderClassName = clsx(
      "block-editor-media-placeholder",
      className,
      {
        "is-appender": isAppender
      }
    );
    return /* @__PURE__ */ jsxs(
      Placeholder,
      {
        icon,
        label: title,
        instructions,
        className: placeholderClassName,
        notices,
        onDoubleClick,
        preview: mediaPreview,
        style,
        children: [
          content,
          children
        ]
      }
    );
  };
  const renderPlaceholder = placeholder ?? defaultRenderPlaceholder;
  const renderDropZone = () => {
    if (disableDropZone) {
      return null;
    }
    return /* @__PURE__ */ jsx(
      DropZone,
      {
        onFilesDrop: onFilesUpload,
        onDrop: handleBlocksDrop,
        isEligible: (dataTransfer) => {
          const prefix = "wp-block:core/";
          const types = [];
          for (const type of dataTransfer.types) {
            if (type.startsWith(prefix)) {
              types.push(type.slice(prefix.length));
            }
          }
          return types.every(
            (type) => allowedTypes.includes(type)
          ) && (multiple ? true : types.length === 1);
        }
      }
    );
  };
  const renderCancelLink = () => {
    return onCancel && /* @__PURE__ */ jsx(
      Button,
      {
        __next40pxDefaultSize: true,
        className: "block-editor-media-placeholder__cancel-button",
        title: __("Cancel"),
        variant: "link",
        onClick: onCancel,
        children: __("Cancel")
      }
    );
  };
  const renderUrlSelectionUI = () => {
    return onSelectURL && /* @__PURE__ */ jsx(
      URLSelectionUI,
      {
        src,
        onChangeSrc: setSrc,
        onSelectURL
      }
    );
  };
  const renderFeaturedImageToggle = () => {
    return onToggleFeaturedImage && /* @__PURE__ */ jsx("div", { className: "block-editor-media-placeholder__url-input-container", children: /* @__PURE__ */ jsx(
      Button,
      {
        __next40pxDefaultSize: true,
        className: "block-editor-media-placeholder__button",
        onClick: onToggleFeaturedImage,
        variant: "secondary",
        children: __("Use featured image")
      }
    ) });
  };
  const renderMediaUploadChecked = () => {
    const defaultButton = ({ open }) => {
      return /* @__PURE__ */ jsx(
        Button,
        {
          __next40pxDefaultSize: true,
          variant: "secondary",
          onClick: () => {
            open();
          },
          children: __("Media Library")
        }
      );
    };
    const libraryButton = mediaLibraryButton ?? defaultButton;
    const uploadMediaLibraryButton = /* @__PURE__ */ jsx(
      MediaUpload,
      {
        addToGallery,
        gallery: multiple && onlyAllowsImages(),
        multiple,
        onSelect,
        allowedTypes,
        mode: "browse",
        value: Array.isArray(value) ? value.map(({ id }) => id) : value.id,
        render: libraryButton
      }
    );
    if (mediaUpload && isAppender) {
      return /* @__PURE__ */ jsxs(Fragment, { children: [
        renderDropZone(),
        /* @__PURE__ */ jsx(
          FormFileUpload,
          {
            onChange: onUpload,
            accept: computedAccept,
            multiple: !!multiple,
            render: ({ openFileDialog }) => {
              const content = /* @__PURE__ */ jsxs(Fragment, { children: [
                /* @__PURE__ */ jsx(
                  Button,
                  {
                    __next40pxDefaultSize: true,
                    variant: "primary",
                    className: clsx(
                      "block-editor-media-placeholder__button",
                      "block-editor-media-placeholder__upload-button"
                    ),
                    onClick: openFileDialog,
                    children: _x("Upload", "verb")
                  }
                ),
                uploadMediaLibraryButton,
                renderUrlSelectionUI(),
                renderFeaturedImageToggle(),
                renderCancelLink()
              ] });
              return renderPlaceholder(content);
            }
          }
        )
      ] });
    }
    if (mediaUpload) {
      const content = /* @__PURE__ */ jsxs(Fragment, { children: [
        renderDropZone(),
        /* @__PURE__ */ jsx(
          FormFileUpload,
          {
            render: ({ openFileDialog }) => /* @__PURE__ */ jsx(
              Button,
              {
                __next40pxDefaultSize: true,
                onClick: openFileDialog,
                variant: "primary",
                className: clsx(
                  "block-editor-media-placeholder__button",
                  "block-editor-media-placeholder__upload-button"
                ),
                children: _x("Upload", "verb")
              }
            ),
            onChange: onUpload,
            accept: computedAccept,
            multiple: !!multiple
          }
        ),
        uploadMediaLibraryButton,
        renderUrlSelectionUI(),
        renderFeaturedImageToggle(),
        renderCancelLink()
      ] });
      return renderPlaceholder(content);
    }
    return renderPlaceholder(uploadMediaLibraryButton);
  };
  if (disableMediaButtons) {
    return /* @__PURE__ */ jsx(MediaUploadCheck, { children: renderDropZone() });
  }
  return /* @__PURE__ */ jsx(
    MediaUploadCheck,
    {
      fallback: renderPlaceholder(renderUrlSelectionUI()),
      children: renderMediaUploadChecked()
    }
  );
}
var media_placeholder_default = withFilters("editor.MediaPlaceholder")(MediaPlaceholder);
export {
  MediaPlaceholder,
  media_placeholder_default as default
};
//# sourceMappingURL=index.js.map
