import { TIPTAP_CARD_CONTENT_TYPE, TIPTAP_CARD_TYPE } from "./../ricos-content/index.js";
import { Node_Type } from "./../ricos-schema/legacy/wix/rich_content/v1/index.js";
import { Plugin, PluginKey } from "./../tiptap/pm/state.js";
import { createRicosFunctionalExtension } from "./create-ricos-extension/index.js";
const trailingNode = createRicosFunctionalExtension({
  type: "extension",
  groups: [],
  name: "trailingNode",
  reconfigure(config, extensions) {
    return {
      ...config,
      addOptions: () => ({
        node: Node_Type.PARAGRAPH,
        trailingInCard: !!extensions.find((e) => e.name === TIPTAP_CARD_TYPE),
        notAfter: extensions.filter(({ groups }) => groups.includes("no-trailing-node")).map(({ name }) => name)
      })
    };
  },
  createExtensionConfig() {
    return {
      name: this.name,
      addProseMirrorPlugins() {
        const plugin = new PluginKey(this.name);
        return [
          new Plugin({
            key: plugin,
            appendTransaction: (_, __, state) => {
              const { doc, tr, schema } = state;
              if (this.options.trailingInCard) {
                const type2 = schema.nodes[this.options.node];
                let hasChanges = false;
                const insertPositions = [];
                doc.forEach((node, pos) => {
                  if (node.type.name !== Node_Type.CARD) {
                    return;
                  }
                  node.forEach((wrapper, wrapperOffset) => {
                    if (wrapper.type.name !== TIPTAP_CARD_CONTENT_TYPE) {
                      return;
                    }
                    const lastChild = wrapper.lastChild;
                    if (this.options.notAfter.includes(lastChild?.type.name)) {
                      return;
                    }
                    const wrapperEndInner = pos + 1 + wrapperOffset + wrapper.nodeSize - 1;
                    insertPositions.push(wrapperEndInner);
                  });
                });
                for (let i = insertPositions.length - 1; i >= 0; i--) {
                  tr.insert(insertPositions[i], type2.create());
                  hasChanges = true;
                }
                if (hasChanges) {
                  return tr.setMeta("trailingNodeInsertion", true);
                }
                return;
              }
              const lastNode = state.tr.doc.lastChild;
              if (this.options.notAfter.includes(lastNode?.type.name)) {
                return;
              }
              const endPosition = doc.content.size;
              const type = schema.nodes[this.options.node];
              return tr.insert(endPosition, type.create()).setMeta("trailingNodeInsertion", true);
            }
          })
        ];
      }
    };
  }
});
export {
  trailingNode
};
//# sourceMappingURL=trailing-node.js.map
