// packages/block-editor/src/components/rich-text/event-listeners/before-input-rules.js
import { insert, isCollapsed } from "@wordpress/rich-text";
import { applyFilters } from "@wordpress/hooks";
import { privateApis as composePrivateApis } from "@wordpress/compose";
import { store as blockEditorStore } from "../../../store/index.mjs";
import { unlock } from "../../../lock-unlock.mjs";
var { subscribeDelegatedListener } = unlock(composePrivateApis);
var wrapSelectionSettings = ["`", '"', "'", "“”", "‘’"];
var before_input_rules_default = (props) => (element) => {
  function onInput(event) {
    const { inputType, data } = event;
    const { value, onChange, registry } = props.current;
    if (inputType !== "insertText") {
      return;
    }
    if (isCollapsed(value)) {
      return;
    }
    const pair = applyFilters(
      "blockEditor.wrapSelectionSettings",
      wrapSelectionSettings
    ).find(
      ([startChar2, endChar2]) => startChar2 === data || endChar2 === data
    );
    if (!pair) {
      return;
    }
    const [startChar, endChar = startChar] = pair;
    const start = value.start;
    const end = value.end + startChar.length;
    let newValue = insert(value, startChar, start, start);
    newValue = insert(newValue, endChar, end, end);
    const {
      __unstableMarkLastChangeAsPersistent,
      __unstableMarkAutomaticChange
    } = registry.dispatch(blockEditorStore);
    __unstableMarkLastChangeAsPersistent();
    onChange(newValue);
    __unstableMarkAutomaticChange();
    const init = {};
    for (const key in event) {
      init[key] = event[key];
    }
    init.data = endChar;
    const { ownerDocument } = element;
    const { defaultView } = ownerDocument;
    const newEvent = new defaultView.InputEvent("input", init);
    window.queueMicrotask(() => {
      event.target.dispatchEvent(newEvent);
    });
    event.preventDefault();
  }
  return subscribeDelegatedListener(element, "beforeinput", onInput, true);
};
export {
  before_input_rules_default as default
};
//# sourceMappingURL=before-input-rules.mjs.map
