import { Plugin, PluginKey } from "./../../tiptap/pm/state.js";
import { createRicosFunctionalExtension } from "../create-ricos-extension/index.js";
import {
  getContentChange,
  getDiffRanges,
  isIgnoredTransaction,
  reportGenericDiff,
  reportLinkDiff,
  reportTextStyleDiff
} from "./diff-tools.js";
const reportDiff = (log, onPluginAdded, onPluginDeleted, onLinkAdded) => (transaction, state) => {
  setTimeout(() => {
    if (!transaction.docChanged || isIgnoredTransaction(transaction)) {
      log("changes are filtered (docs are equal)");
      return true;
    }
    const { newRange, oldRange } = getDiffRanges(state.doc.content, transaction.doc.content);
    if (newRange.isEmpty() && oldRange.isEmpty()) {
      log("changes are filtered (empty ranges)");
      return true;
    }
    log("DIFF RANGES", { oldRange, newRange });
    let contentChanges;
    try {
      contentChanges = getContentChange(state.doc, transaction.doc, {
        oldRange,
        newRange
      });
    } catch (e) {
      log("CONTENT CHANGE ERROR", e);
      return true;
    }
    log("CONTENT CHANGE", contentChanges.toJSON());
    const diffs = contentChanges.getDiff();
    log("CONTENT DIFF", diffs);
    reportGenericDiff(diffs, onPluginAdded, onPluginDeleted);
    reportLinkDiff(diffs, onLinkAdded, onPluginDeleted);
    reportTextStyleDiff(diffs, onPluginAdded, onPluginDeleted);
  }, 0);
  return true;
};
const contentDiff = createRicosFunctionalExtension({
  name: "contentDiff",
  type: "extension",
  groups: [],
  reconfigure(config, _extensions, _props, _settings, services) {
    return {
      ...config,
      addOptions() {
        return {
          logger: services.context.debugMode?.includes("all") || services.context.debugMode?.includes("extensions") ? (message, ...args) => console.debug(message, ...args) : () => {
          },
          publishPluginAddSuccess(pluginId, params) {
            return services.pluginsEvents.publishPluginAddSuccess({ pluginId, params });
          },
          publishPluginDelete(pluginId, _params) {
            return services.pluginsEvents.publishPluginDelete({ pluginId });
          },
          publishPluginLinkable(data) {
            return services.pluginsEvents.publishPluginLinkable(data);
          }
        };
      }
    };
  },
  createExtensionConfig() {
    return {
      name: "contentDiff",
      priority: 1,
      addProseMirrorPlugins() {
        return [
          new Plugin({
            key: new PluginKey("contentDiff"),
            filterTransaction: reportDiff(
              this.options.logger,
              this.options.publishPluginAddSuccess,
              this.options.publishPluginDelete,
              this.options.publishPluginLinkable
            )
          })
        ];
      }
    };
  }
});
export {
  contentDiff
};
//# sourceMappingURL=extension.js.map
