"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-library/src/freeform/edit.js
var edit_exports = {};
__export(edit_exports, {
  default: () => FreeformEdit
});
module.exports = __toCommonJS(edit_exports);
var import_block_editor = require("@wordpress/block-editor");
var import_compose = require("@wordpress/compose");
var import_data = require("@wordpress/data");
var import_components = require("@wordpress/components");
var import_element = require("@wordpress/element");
var import_i18n = require("@wordpress/i18n");
var import_keycodes = require("@wordpress/keycodes");
var import_convert_to_blocks_button = __toESM(require("./convert-to-blocks-button"));
var import_modal = __toESM(require("./modal"));
var import_jsx_runtime = require("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 = (0, import_data.useSelect)(
    (select) => select(import_block_editor.store).canRemoveBlock(clientId),
    [clientId]
  );
  const [isIframed, setIsIframed] = (0, import_element.useState)(false);
  const ref = (0, import_compose.useRefEffect)((element) => {
    setIsIframed(element.ownerDocument !== document);
  }, []);
  return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_jsx_runtime.Fragment, { children: [
    canRemove && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_block_editor.BlockControls, { children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_components.ToolbarGroup, { children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_convert_to_blocks_button.default, { clientId }) }) }),
    /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { ...(0, import_block_editor.useBlockProps)({ ref }), children: isIframed ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_modal.default, { ...props }) : /* @__PURE__ */ (0, import_jsx_runtime.jsx)(ClassicEdit, { ...props }) })
  ] });
}
function ClassicEdit({
  clientId,
  attributes: { content },
  setAttributes,
  onReplace
}) {
  const { getMultiSelectedBlockClientIds } = (0, import_data.useSelect)(import_block_editor.store);
  const didMountRef = (0, import_element.useRef)(false);
  (0, import_element.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]);
  (0, import_element.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 = (0, import_compose.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 (import_keycodes.isKeyboardEvent.primary(event, "z")) {
          event.stopPropagation();
        }
        if ((event.keyCode === import_keycodes.BACKSPACE || event.keyCode === import_keycodes.DELETE) && isTmceEmpty(editor)) {
          onReplace([]);
          event.preventDefault();
          event.stopImmediatePropagation();
        }
        const { altKey } = event;
        if (altKey && event.keyCode === import_keycodes.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__ */ (0, import_jsx_runtime.jsxs)(import_jsx_runtime.Fragment, { children: [
    /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
      "div",
      {
        id: `toolbar-${clientId}`,
        className: "block-library-classic__toolbar",
        onClick: focus,
        "data-placeholder": (0, import_i18n.__)("Classic"),
        onKeyDown: onToolbarKeyDown
      },
      "toolbar"
    ),
    /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
      "div",
      {
        id: `editor-${clientId}`,
        className: "wp-block-freeform block-library-rich-text__tinymce"
      },
      "editor"
    )
  ] });
}
//# sourceMappingURL=edit.js.map
