"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.WysiwygContentHandler = void 0;
const prosemirror_model_1 = require("prosemirror-model");
const prosemirror_state_1 = require("prosemirror-state");
class WysiwygContentHandler {
    #view;
    #parser;
    constructor(view, parser) {
        this.#view = view;
        this.#parser = parser;
    }
    clear() {
        this.#view.dispatch(this.#view.state.tr
            .setSelection(new prosemirror_state_1.AllSelection(this.#view.state.doc))
            .replaceSelection(prosemirror_model_1.Slice.empty));
    }
    replace(newMarkup) {
        this.#view.dispatch(this.#view.state.tr
            .setSelection(new prosemirror_state_1.AllSelection(this.#view.state.doc))
            .replaceSelection(new prosemirror_model_1.Slice(this.#parser.parse(newMarkup).content, 0, 0)));
    }
    prepend(markup) {
        this.#view.dispatch(this.#view.state.tr.insert(0, this.#parser.parse(markup).content));
    }
    append(markup) {
        let tr = this.#view.state.tr;
        if (tr.doc.lastChild?.type.name === 'paragraph' && tr.doc.lastChild.childCount === 0) {
            const pos = tr.doc.nodeSize - 3;
            tr = tr.replaceWith(pos - 1, pos + 1, this.#parser.parse(markup));
        }
        else {
            tr = this.appendContentTr(tr, markup);
        }
        if (tr.doc.lastChild?.type.name !== 'paragraph' || tr.doc.lastChild.childCount !== 0) {
            tr = this.appendContentTr(tr, '');
        }
        this.#view.dispatch(tr);
    }
    moveCursor(position) {
        switch (position) {
            case 'start': {
                const { tr } = this.#view.state;
                this.#view.dispatch(tr.setSelection(prosemirror_state_1.TextSelection.create(tr.doc, 1)));
                break;
            }
            case 'end': {
                const { lastChild } = this.#view.state.doc;
                const { tr } = this.#view.state;
                const pos = tr.doc.nodeSize - 2;
                if (!lastChild?.isTextblock && !lastChild?.isText) {
                    this.appendContentTr(tr, '');
                }
                this.#view.dispatch(tr
                    .setSelection(prosemirror_state_1.TextSelection.create(tr.doc, tr.mapping.map(pos) - 1))
                    .scrollIntoView());
                break;
            }
            default:
                throw new Error('The "position" argument must be "start" or "end"');
        }
    }
    appendContentTr(tr, markup) {
        return tr.insert(tr.doc.nodeSize - 2, this.#parser.parse(markup).content);
    }
}
exports.WysiwygContentHandler = WysiwygContentHandler;
//# sourceMappingURL=ContentHandler.js.map
