"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.cutActivePlugin = void 0;
const prosemirror_state_1 = require("prosemirror-state");
const prosemirror_view_1 = require("prosemirror-view");
const selection_1 = require("../../../../utils/selection.js");
const const_1 = require("../const.js");
const YFM_CUT_ACTIVE_CLASSNAME = 'yfm-cut-active';
const cutActivePlugin = () => {
    return new prosemirror_state_1.Plugin({
        props: {
            decorations(state) {
                const decos = [];
                const sel = state.selection;
                const yfmCutType = (0, const_1.cutType)(state.schema);
                const createDeco = ({ pos, node }) => {
                    decos.push(prosemirror_view_1.Decoration.node(pos, pos + node.nodeSize, {
                        class: YFM_CUT_ACTIVE_CLASSNAME,
                    }));
                };
                if ((0, selection_1.isNodeSelection)(sel)) {
                    if (sel.node.type === yfmCutType)
                        createDeco({ pos: sel.from, node: sel.node });
                    findParentNodesOfType(yfmCutType, sel.$from).forEach(createDeco);
                }
                else if ((0, selection_1.isTextSelection)(sel)) {
                    findParentNodesOfType(yfmCutType, sel.$from).forEach(createDeco);
                    if (!sel.$from.sameParent(sel.$to)) {
                        findParentNodesOfType(yfmCutType, sel.$to).forEach(createDeco);
                        state.doc.nodesBetween(sel.from, sel.to, (node, pos) => {
                            if (node.type === yfmCutType)
                                createDeco({ pos, node });
                            if (node.isTextblock)
                                return false;
                            return true;
                        });
                    }
                }
                else {
                    // some other selection
                    findParentNodesOfType(yfmCutType, sel.$from).forEach(createDeco);
                }
                return decos.length ? prosemirror_view_1.DecorationSet.create(state.doc, decos) : prosemirror_view_1.DecorationSet.empty;
            },
        },
    });
};
exports.cutActivePlugin = cutActivePlugin;
function findParentNodesOfType(type, $pos) {
    let { depth } = $pos;
    const nodes = [];
    while (depth >= 0) {
        const node = $pos.node(depth);
        if (node.type === type)
            nodes.push({ depth, node, pos: $pos.before(depth) });
        depth--;
    }
    return nodes;
}
//# sourceMappingURL=active.js.map
