"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.mergeListsPlugin = void 0;
const prosemirror_state_1 = require("prosemirror-state");
// @ts-ignore // TODO: fix cjs build
const prosemirror_utils_1 = require("prosemirror-utils");
const utils_1 = require("../utils.js");
const mergeListsPlugin = () => new prosemirror_state_1.Plugin({
    appendTransaction(trs, oldState, newState) {
        const docChanged = trs.some((tr) => tr.docChanged);
        if (!docChanged)
            return null;
        const hasParentList = (0, prosemirror_utils_1.hasParentNode)(utils_1.isListNode)(newState.selection) ||
            (0, prosemirror_utils_1.hasParentNode)(utils_1.isListNode)(oldState.selection);
        if (!hasParentList)
            return null;
        const { tr } = newState;
        const listNodes = (0, prosemirror_utils_1.findChildren)(tr.doc, utils_1.isListNode, true);
        mergeAdjacentNodesWithSameType(tr, listNodes);
        return tr.docChanged ? tr : null;
    },
});
exports.mergeListsPlugin = mergeListsPlugin;
function mergeAdjacentNodesWithSameType(tr, nodes) {
    const posAfterMap = {};
    for (const item of nodes) {
        const posBefore = item.pos;
        const posAfter = posBefore + item.node.nodeSize;
        posAfterMap[posAfter] = item.node;
        const nodeBefore = posAfterMap[posBefore];
        if (nodeBefore?.type === item.node.type) {
            tr.join(tr.mapping.map(posBefore));
            posAfterMap[posBefore] = undefined;
        }
    }
}
//# sourceMappingURL=MergeListsPlugin.js.map
