// packages/block-library/src/file/edit.js
import clsx from "clsx";
import { isBlobURL } from "@wordpress/blob";
import {
  __unstableGetAnimateClassName as getAnimateClassName,
  ResizableBox,
  ToolbarButton
} from "@wordpress/components";
import { useSelect, useDispatch } from "@wordpress/data";
import {
  BlockControls,
  BlockIcon,
  MediaPlaceholder,
  MediaReplaceFlow,
  RichText,
  useBlockProps,
  store as blockEditorStore,
  __experimentalGetElementClassName
} from "@wordpress/block-editor";
import { useState } from "@wordpress/element";
import { useCopyToClipboard } from "@wordpress/compose";
import { __ } from "@wordpress/i18n";
import { file as icon } from "@wordpress/icons";
import { store as coreStore } from "@wordpress/core-data";
import { store as noticesStore } from "@wordpress/notices";
import { getFilename } from "@wordpress/url";
import FileBlockInspector from "./inspector.mjs";
import { browserSupportsPdfs } from "./utils/index.mjs";
import removeAnchorTag from "../utils/remove-anchor-tag.mjs";
import { useUploadMediaFromBlobURL } from "../utils/hooks.mjs";
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
var MIN_PREVIEW_HEIGHT = 200;
var MAX_PREVIEW_HEIGHT = 2e3;
function ClipboardToolbarButton({ text, disabled }) {
  const { createNotice } = useDispatch(noticesStore);
  const ref = useCopyToClipboard(text, () => {
    createNotice("info", __("Copied URL to clipboard."), {
      isDismissible: true,
      type: "snackbar"
    });
  });
  return /* @__PURE__ */ jsx(
    ToolbarButton,
    {
      className: "components-clipboard-toolbar-button",
      ref,
      disabled,
      children: __("Copy URL")
    }
  );
}
function FileEdit({ attributes, isSelected, setAttributes, clientId }) {
  const {
    id,
    fileName,
    href,
    textLinkHref,
    textLinkTarget,
    showDownloadButton,
    downloadButtonText,
    displayPreview,
    previewHeight
  } = attributes;
  const [temporaryURL, setTemporaryURL] = useState(attributes.blob);
  const { media } = useSelect(
    (select) => ({
      media: id === void 0 ? void 0 : select(coreStore).getEntityRecord(
        "postType",
        "attachment",
        id
      )
    }),
    [id]
  );
  const { createErrorNotice } = useDispatch(noticesStore);
  const { toggleSelection } = useDispatch(blockEditorStore);
  useUploadMediaFromBlobURL({
    url: temporaryURL,
    onChange: onSelectFile,
    onError: onUploadError
  });
  function onSelectFile(newMedia) {
    if (!newMedia || !newMedia.url) {
      setAttributes({
        href: void 0,
        fileName: void 0,
        textLinkHref: void 0,
        id: void 0,
        fileId: void 0,
        displayPreview: void 0,
        previewHeight: void 0
      });
      setTemporaryURL();
      return;
    }
    if (isBlobURL(newMedia.url)) {
      setTemporaryURL(newMedia.url);
      return;
    }
    const isPdf = (
      // Media Library and REST API use different properties for mime type.
      (newMedia.mime || newMedia.mime_type) === "application/pdf" || getFilename(newMedia.url).toLowerCase().endsWith(".pdf")
    );
    const pdfAttributes = {
      displayPreview: isPdf ? attributes.displayPreview ?? true : void 0,
      previewHeight: isPdf ? attributes.previewHeight ?? 600 : void 0
    };
    setAttributes({
      href: newMedia.url,
      fileName: newMedia.title,
      textLinkHref: newMedia.url,
      id: newMedia.id,
      fileId: `wp-block-file--media-${clientId}`,
      blob: void 0,
      ...pdfAttributes
    });
    setTemporaryURL();
  }
  function onUploadError(message) {
    setAttributes({ href: void 0 });
    createErrorNotice(message, { type: "snackbar" });
  }
  function changeLinkDestinationOption(newHref) {
    setAttributes({ textLinkHref: newHref });
  }
  function changeOpenInNewWindow(newValue) {
    setAttributes({
      textLinkTarget: newValue ? "_blank" : false
    });
  }
  function changeShowDownloadButton(newValue) {
    setAttributes({ showDownloadButton: newValue });
  }
  function changeDisplayPreview(newValue) {
    setAttributes({ displayPreview: newValue });
  }
  function handleOnResizeStop(event, direction, elt, delta) {
    toggleSelection(true);
    const newHeight = parseInt(previewHeight + delta.height, 10);
    setAttributes({ previewHeight: newHeight });
  }
  function changePreviewHeight(newValue) {
    const newHeight = Math.max(
      parseInt(newValue, 10),
      MIN_PREVIEW_HEIGHT
    );
    setAttributes({ previewHeight: newHeight });
  }
  const attachmentPage = media && media.link;
  const blockProps = useBlockProps({
    className: clsx(
      !!temporaryURL && getAnimateClassName({ type: "loading" }),
      {
        "is-transient": !!temporaryURL
      }
    )
  });
  const displayPreviewInEditor = browserSupportsPdfs() && displayPreview;
  if (!href && !temporaryURL) {
    return /* @__PURE__ */ jsx("div", { ...blockProps, children: /* @__PURE__ */ jsx(
      MediaPlaceholder,
      {
        icon: /* @__PURE__ */ jsx(BlockIcon, { icon }),
        labels: {
          title: __("File"),
          instructions: __(
            "Drag and drop a file, upload, or choose from your library."
          )
        },
        onSelect: onSelectFile,
        onError: onUploadError,
        accept: "*"
      }
    ) });
  }
  return /* @__PURE__ */ jsxs(Fragment, { children: [
    /* @__PURE__ */ jsx(
      FileBlockInspector,
      {
        hrefs: {
          href: href || temporaryURL,
          textLinkHref,
          attachmentPage
        },
        ...{
          openInNewWindow: !!textLinkTarget,
          showDownloadButton,
          changeLinkDestinationOption,
          changeOpenInNewWindow,
          changeShowDownloadButton,
          displayPreview,
          changeDisplayPreview,
          previewHeight,
          changePreviewHeight
        }
      }
    ),
    /* @__PURE__ */ jsxs(BlockControls, { group: "other", children: [
      /* @__PURE__ */ jsx(
        MediaReplaceFlow,
        {
          mediaId: id,
          mediaURL: href,
          accept: "*",
          onSelect: onSelectFile,
          onError: onUploadError,
          onReset: () => onSelectFile(void 0)
        }
      ),
      /* @__PURE__ */ jsx(
        ClipboardToolbarButton,
        {
          text: href,
          disabled: isBlobURL(href)
        }
      )
    ] }),
    /* @__PURE__ */ jsxs("div", { ...blockProps, children: [
      displayPreviewInEditor && /* @__PURE__ */ jsxs(
        ResizableBox,
        {
          size: { height: previewHeight, width: "100%" },
          minHeight: MIN_PREVIEW_HEIGHT,
          maxHeight: MAX_PREVIEW_HEIGHT,
          grid: [1, 10],
          enable: {
            top: false,
            right: false,
            bottom: true,
            left: false,
            topRight: false,
            bottomRight: false,
            bottomLeft: false,
            topLeft: false
          },
          onResizeStart: () => toggleSelection(false),
          onResizeStop: handleOnResizeStop,
          showHandle: isSelected,
          children: [
            /* @__PURE__ */ jsx(
              "object",
              {
                className: "wp-block-file__preview",
                data: href,
                type: "application/pdf",
                "aria-label": __(
                  "Embed of the selected PDF file."
                )
              }
            ),
            !isSelected && /* @__PURE__ */ jsx("div", { className: "wp-block-file__preview-overlay" })
          ]
        }
      ),
      /* @__PURE__ */ jsxs("div", { className: "wp-block-file__content-wrapper", children: [
        /* @__PURE__ */ jsx(
          RichText,
          {
            identifier: "fileName",
            tagName: "a",
            value: fileName,
            placeholder: __("Write file name…"),
            withoutInteractiveFormatting: true,
            onChange: (text) => setAttributes({
              fileName: removeAnchorTag(text)
            }),
            href: textLinkHref
          }
        ),
        showDownloadButton && /* @__PURE__ */ jsx("div", { className: "wp-block-file__button-richtext-wrapper", children: /* @__PURE__ */ jsx(
          RichText,
          {
            identifier: "downloadButtonText",
            tagName: "div",
            "aria-label": __("Download button text"),
            className: clsx(
              "wp-block-file__button",
              __experimentalGetElementClassName(
                "button"
              )
            ),
            value: downloadButtonText,
            withoutInteractiveFormatting: true,
            placeholder: __("Add text…"),
            onChange: (text) => setAttributes({
              downloadButtonText: removeAnchorTag(text)
            })
          }
        ) })
      ] })
    ] })
  ] });
}
var edit_default = FileEdit;
export {
  MAX_PREVIEW_HEIGHT,
  MIN_PREVIEW_HEIGHT,
  edit_default as default
};
//# sourceMappingURL=edit.mjs.map
