// packages/block-editor/src/components/rich-text/event-listeners/paste-handler.js
import { pasteHandler } from "@wordpress/blocks";
import { isEmpty, insert, create } from "@wordpress/rich-text";
import { isURL } from "@wordpress/url";
import { addActiveFormats } from "../utils";
import { getPasteEventData } from "../../../utils/pasting";
var paste_handler_default = (props) => (element) => {
  function _onPaste(event) {
    const {
      disableFormats,
      onChange,
      value,
      formatTypes,
      tagName,
      onReplace,
      __unstableEmbedURLOnPaste,
      preserveWhiteSpace,
      pastePlainText
    } = props.current;
    if (!element.contains(event.target)) {
      return;
    }
    if (event.defaultPrevented) {
      return;
    }
    const { plainText, html } = getPasteEventData(event);
    event.preventDefault();
    window.console.log("Received HTML:\n\n", html);
    window.console.log("Received plain text:\n\n", plainText);
    if (disableFormats) {
      onChange(insert(value, plainText));
      return;
    }
    const isInternal = event.clipboardData.getData("rich-text") === "true";
    function pasteInline(content2) {
      const transformed = formatTypes.reduce(
        (accumulator, { __unstablePasteRule }) => {
          if (__unstablePasteRule && accumulator === value) {
            accumulator = __unstablePasteRule(value, {
              html,
              plainText
            });
          }
          return accumulator;
        },
        value
      );
      if (transformed !== value) {
        onChange(transformed);
      } else {
        const valueToInsert = create({ html: content2 });
        addActiveFormats(valueToInsert, value.activeFormats);
        onChange(insert(value, valueToInsert));
      }
    }
    if (isInternal) {
      pasteInline(html);
      return;
    }
    if (pastePlainText) {
      onChange(insert(value, create({ text: plainText })));
      return;
    }
    let mode = "INLINE";
    const trimmedPlainText = plainText.trim();
    if (__unstableEmbedURLOnPaste && isEmpty(value) && isURL(trimmedPlainText) && // For the link pasting feature, allow only http(s) protocols.
    /^https?:/.test(trimmedPlainText)) {
      mode = "BLOCKS";
    }
    const content = pasteHandler({
      HTML: html,
      plainText,
      mode,
      tagName,
      preserveWhiteSpace
    });
    if (typeof content === "string") {
      pasteInline(content);
    } else if (content.length > 0) {
      if (onReplace && isEmpty(value)) {
        onReplace(content, content.length - 1, -1);
      }
    }
  }
  const { defaultView } = element.ownerDocument;
  defaultView.addEventListener("paste", _onPaste);
  return () => {
    defaultView.removeEventListener("paste", _onPaste);
  };
};
export {
  paste_handler_default as default
};
//# sourceMappingURL=paste-handler.js.map
