"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.toggleQuote = exports.joinPrevQuote = exports.liftFromQuote = void 0;
const prosemirror_commands_1 = require("prosemirror-commands");
const join_1 = require("../../../commands/join.js");
require("../../../types/spec.js");
const selection_1 = require("../../../utils/selection.js");
const const_1 = require("./const.js");
const liftFromQuote = (state, dispatch) => {
    const $cursor = (0, selection_1.get$CursorAtBlockStart)(state.selection);
    if (!$cursor || !(0, const_1.isBlockqouteNode)($cursor.node(-1)))
        return false;
    return (0, prosemirror_commands_1.lift)(state, dispatch);
};
exports.liftFromQuote = liftFromQuote;
exports.joinPrevQuote = (0, join_1.joinPreviousBlock)({
    checkPrevNode: const_1.isBlockqouteNode,
    skipNode: const_1.isBlockqouteNode,
});
const toggleQuote = (state, dispatch) => {
    const { selection } = state;
    const qType = (0, const_1.blockquoteType)(state.schema);
    if (!(0, selection_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);
            if ((0, const_1.isBlockqouteNode)($cursor.node(targetDepth))) {
                dispatch?.(state.tr.lift(range, targetDepth - 1).scrollIntoView());
            }
            else {
                dispatch?.(state.tr.wrap(range, [{ type: qType }]).scrollIntoView());
            }
            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);
}
//# sourceMappingURL=commands.js.map
