"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.toYfmCut = exports.createYfmCut = void 0;
const prosemirror_state_1 = require("prosemirror-state");
// @ts-ignore // TODO: fix cjs build
const prosemirror_utils_1 = require("prosemirror-utils");
const const_1 = require("../const.js");
const createYfmCutNode = (schema) => (content) => {
    return (0, const_1.cutType)(schema).create({ class: 'yfm-cut open' }, [
        (0, const_1.cutTitleType)(schema).create(null),
        (0, const_1.cutContentType)(schema).create(null, content),
    ]);
};
const createYfmCut = (state, dispatch) => {
    const { schema, selection: sel } = state;
    const textblock = (0, prosemirror_utils_1.findParentNodeClosestToPos)(sel.$from, (node) => node.isTextblock && !node.type.spec.complex);
    if (!textblock)
        return false;
    if (dispatch) {
        const sliceFromPos = textblock.pos;
        let sliceToPos = sliceFromPos + textblock.node.nodeSize;
        const tbIndex = sel.$from.index(textblock.depth - 1);
        const tbParent = sel.$from.node(textblock.depth - 1);
        const tbParentStartPos = sel.$from.start(textblock.depth - 1);
        let flag = false;
        // find appropriate sliceToPos
        tbParent.forEach((node, offset, index) => {
            if (index < tbIndex || flag)
                return;
            if (node.type.spec.complex && node.type.spec.complex !== 'root') {
                flag = true;
                return;
            }
            const absoluteAfterPos = tbParentStartPos + offset + node.nodeSize;
            sliceToPos = absoluteAfterPos;
            if (sel.to < sliceToPos)
                flag = true;
        });
        const tr = state.tr;
        tr.replaceWith(sliceFromPos, sliceToPos, createYfmCutNode(schema)(tr.doc.slice(sliceFromPos, sliceToPos, false).content));
        // set selection to start of cut title
        tr.setSelection(prosemirror_state_1.TextSelection.create(tr.doc, sliceFromPos + 2));
        dispatch(tr.scrollIntoView());
    }
    return true;
};
exports.createYfmCut = createYfmCut;
exports.toYfmCut = {
    isEnable(state) {
        return (0, exports.createYfmCut)(state);
    },
    run(state, dispatch) {
        (0, exports.createYfmCut)(state, dispatch);
    },
};
//# sourceMappingURL=toYfmCut.js.map
