"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.addQuoteLink = exports.toggleQuote = void 0;
const prosemirror_commands_1 = require("prosemirror-commands");
const utils_1 = require("../../../utils/index.js");
require("../../../types/spec.js");
const commands_1 = require("./PlaceholderWidget/commands.js");
const QuoteLinkSpecs_1 = require("./QuoteLinkSpecs/index.js");
const toggleQuote = (state, dispatch) => {
    const { selection } = state;
    const qType = (0, QuoteLinkSpecs_1.quoteLinkType)(state.schema);
    if (!(0, utils_1.isTextSelection)(selection) || !selection.$cursor)
        return (0, prosemirror_commands_1.wrapIn)(qType)(state, dispatch);
    const { $cursor } = selection;
    let { depth } = $cursor;
    while (depth > 0) {
        const node = $cursor.node(depth);
        const nodeSpec = node.type.spec;
        if (!nodeSpec.complex || nodeSpec.complex === 'root') {
            const targetDepth = depth - 1;
            const range = getBlockRange($cursor, depth);
            let tr = state.tr;
            if ((0, QuoteLinkSpecs_1.isQuoteLinkNode)($cursor.node(targetDepth))) {
                tr = tr.lift(range, targetDepth - 1).scrollIntoView();
                dispatch?.(tr);
            }
            else {
                tr = tr.wrap(range, [{ type: qType }]).scrollIntoView();
                dispatch?.(tr);
            }
            return true;
        }
        depth--;
    }
    return false;
};
exports.toggleQuote = toggleQuote;
function getBlockRange($pos, depth) {
    const { doc } = $pos;
    const $before = doc.resolve($pos.before(depth));
    const $after = doc.resolve($pos.after(depth));
    return $before.blockRange($after);
}
exports.addQuoteLink = commands_1.addQuoteLinkPlaceholder;
//# sourceMappingURL=commands.js.map
