// packages/block-library/src/freeform/edit.js
import {
  BlockControls,
  useBlockProps,
  store as blockEditorStore
} from "@wordpress/block-editor";
import { debounce, useRefEffect } from "@wordpress/compose";
import { useSelect } from "@wordpress/data";
import { ToolbarGroup } from "@wordpress/components";
import { useEffect, useRef, useState } from "@wordpress/element";
import { __ } from "@wordpress/i18n";
import { BACKSPACE, DELETE, F10, isKeyboardEvent } from "@wordpress/keycodes";
import ConvertToBlocksButton from "./convert-to-blocks-button";
import ModalEdit from "./modal";
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
var { wp } = window;
function isTmceEmpty(editor) {
  const body = editor.getBody();
  if (body.childNodes.length > 1) {
    return false;
  } else if (body.childNodes.length === 0) {
    return true;
  }
  if (body.childNodes[0].childNodes.length > 1) {
    return false;
  }
  return /^\n?$/.test(body.innerText || body.textContent);
}
function FreeformEdit(props) {
  const { clientId } = props;
  const canRemove = useSelect(
    (select) => select(blockEditorStore).canRemoveBlock(clientId),
    [clientId]
  );
  const [isIframed, setIsIframed] = useState(false);
  const ref = useRefEffect((element) => {
    setIsIframed(element.ownerDocument !== document);
  }, []);
  return /* @__PURE__ */ jsxs(Fragment, { children: [
    canRemove && /* @__PURE__ */ jsx(BlockControls, { children: /* @__PURE__ */ jsx(ToolbarGroup, { children: /* @__PURE__ */ jsx(ConvertToBlocksButton, { clientId }) }) }),
    /* @__PURE__ */ jsx("div", { ...useBlockProps({ ref }), children: isIframed ? /* @__PURE__ */ jsx(ModalEdit, { ...props }) : /* @__PURE__ */ jsx(ClassicEdit, { ...props }) })
  ] });
}
function ClassicEdit({
  clientId,
  attributes: { content },
  setAttributes,
  onReplace
}) {
  const { getMultiSelectedBlockClientIds } = useSelect(blockEditorStore);
  const didMountRef = useRef(false);
  useEffect(() => {
    if (!didMountRef.current) {
      return;
    }
    const editor = window.tinymce.get(`editor-${clientId}`);
    if (!editor) {
      return;
    }
    const currentContent = editor.getContent();
    if (currentContent !== content) {
      editor.setContent(content || "");
    }
  }, [clientId, content]);
  useEffect(() => {
    const { baseURL, suffix } = window.wpEditorL10n.tinymce;
    didMountRef.current = true;
    window.tinymce.EditorManager.overrideDefaults({
      base_url: baseURL,
      suffix
    });
    function onSetup(editor) {
      let bookmark;
      if (content) {
        editor.on("loadContent", () => editor.setContent(content));
      }
      editor.on("blur", () => {
        bookmark = editor.selection.getBookmark(2, true);
        const scrollContainer = document.querySelector(
          ".interface-interface-skeleton__content"
        );
        const scrollPosition = scrollContainer.scrollTop;
        if (!getMultiSelectedBlockClientIds()?.length) {
          setAttributes({
            content: editor.getContent()
          });
        }
        editor.once("focus", () => {
          if (bookmark) {
            editor.selection.moveToBookmark(bookmark);
            if (scrollContainer.scrollTop !== scrollPosition) {
              scrollContainer.scrollTop = scrollPosition;
            }
          }
        });
        return false;
      });
      editor.on("mousedown touchstart", () => {
        bookmark = null;
      });
      const debouncedOnChange = debounce(() => {
        const value = editor.getContent();
        if (value !== editor._lastChange) {
          editor._lastChange = value;
          setAttributes({
            content: value
          });
        }
      }, 250);
      editor.on("Paste Change input Undo Redo", debouncedOnChange);
      editor.on("remove", debouncedOnChange.cancel);
      editor.on("keydown", (event) => {
        if (isKeyboardEvent.primary(event, "z")) {
          event.stopPropagation();
        }
        if ((event.keyCode === BACKSPACE || event.keyCode === DELETE) && isTmceEmpty(editor)) {
          onReplace([]);
          event.preventDefault();
          event.stopImmediatePropagation();
        }
        const { altKey } = event;
        if (altKey && event.keyCode === F10) {
          event.stopPropagation();
        }
      });
      editor.on("paste", (event) => {
        event.stopPropagation();
      });
      editor.on("init", () => {
        const rootNode = editor.getBody();
        if (rootNode.ownerDocument.activeElement === rootNode) {
          rootNode.blur();
          editor.focus();
        }
      });
    }
    function initialize() {
      const { settings } = window.wpEditorL10n.tinymce;
      wp.oldEditor.initialize(`editor-${clientId}`, {
        tinymce: {
          ...settings,
          inline: true,
          content_css: false,
          fixed_toolbar_container: `#toolbar-${clientId}`,
          setup: onSetup
        }
      });
    }
    function onReadyStateChange() {
      if (document.readyState === "complete") {
        initialize();
      }
    }
    if (document.readyState === "complete") {
      initialize();
    } else {
      document.addEventListener("readystatechange", onReadyStateChange);
    }
    return () => {
      document.removeEventListener(
        "readystatechange",
        onReadyStateChange
      );
      wp.oldEditor.remove(`editor-${clientId}`);
      didMountRef.current = false;
    };
  }, []);
  function focus() {
    const editor = window.tinymce.get(`editor-${clientId}`);
    if (editor) {
      editor.focus();
    }
  }
  function onToolbarKeyDown(event) {
    event.stopPropagation();
    event.nativeEvent.stopImmediatePropagation();
  }
  return /* @__PURE__ */ jsxs(Fragment, { children: [
    /* @__PURE__ */ jsx(
      "div",
      {
        id: `toolbar-${clientId}`,
        className: "block-library-classic__toolbar",
        onClick: focus,
        "data-placeholder": __("Classic"),
        onKeyDown: onToolbarKeyDown
      },
      "toolbar"
    ),
    /* @__PURE__ */ jsx(
      "div",
      {
        id: `editor-${clientId}`,
        className: "wp-block-freeform block-library-rich-text__tinymce"
      },
      "editor"
    )
  ] });
}
export {
  FreeformEdit as default
};
//# sourceMappingURL=edit.js.map
