"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.addCheckbox = exports.addCheckboxCmd = void 0;
const prosemirror_state_1 = require("prosemirror-state");
const selection_1 = require("../../../utils/selection.js");
const BaseSchema_1 = require("../../base/BaseSchema/index.js");
const utils_1 = require("./utils.js");
const createCheckbox = (schema, content) => (0, utils_1.checkboxType)(schema).create({}, [
    (0, utils_1.checkboxInputType)(schema).create(),
    (0, utils_1.checkboxLabelType)(schema).create({}, content),
]);
const addCheckboxCmd = (state, dispatch) => {
    function insertCheckbox(tr, pos, content) {
        tr.insert(pos, createCheckbox(state.schema, content));
        return tr.setSelection(prosemirror_state_1.TextSelection.create(tr.doc, pos + 3)); // move cursor inside checkbox
    }
    if ((0, selection_1.isNodeSelection)(state.selection) && rootOrNonComplex(state.selection.node)) {
        const pos = state.selection.to;
        dispatch?.(insertCheckbox(state.tr, pos).scrollIntoView());
        return true;
    }
    const $cursor = (0, selection_1.get$Cursor)(state.selection);
    if (!$cursor)
        return false;
    const inCheckbox = $cursor.parent.type === (0, utils_1.checkboxLabelType)(state.schema) &&
        $cursor.node($cursor.depth - 1).type === (0, utils_1.checkboxType)(state.schema);
    if (inCheckbox) {
        const pos = $cursor.after($cursor.depth - 1);
        dispatch?.(insertCheckbox(state.tr, pos).scrollIntoView());
        return true;
    }
    if (!rootOrNonComplex($cursor.parent))
        return false;
    if (!dispatch)
        return true;
    const { tr } = state;
    const inParagraph = $cursor.parent.type === (0, BaseSchema_1.pType)(state.schema);
    if (inParagraph) {
        const from = $cursor.before(), to = $cursor.after();
        // replace para with checkbox with same content
        tr.replaceWith(from, to, createCheckbox(state.schema, $cursor.parent.content));
        tr.setSelection(prosemirror_state_1.TextSelection.create(tr.doc, $cursor.pos + 2)); // save cursor position in text
    }
    else {
        const pos = $cursor.after();
        insertCheckbox(tr, pos);
    }
    dispatch(tr.scrollIntoView());
    return true;
};
exports.addCheckboxCmd = addCheckboxCmd;
const addCheckbox = () => {
    return {
        isEnable: exports.addCheckboxCmd,
        run: exports.addCheckboxCmd,
    };
};
exports.addCheckbox = addCheckbox;
function rootOrNonComplex(node) {
    const { complex } = node.type.spec;
    return !complex || complex === 'root';
}
//# sourceMappingURL=actions.js.map
