"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Editor = void 0;
class Editor {
    #cm;
    get cm() {
        return this.#cm;
    }
    get codemirror() {
        return this.#cm;
    }
    constructor(cm) {
        this.#cm = cm;
    }
    focus() {
        return this.#cm.focus();
    }
    hasFocus() {
        return this.#cm.hasFocus;
    }
    getValue() {
        return this.#cm.state.doc.toString();
    }
    isEmpty() {
        return (this.#cm.state.doc.lines === 1 && this.#cm.state.doc.line(1).text.trim().length === 0);
    }
    clear() {
        this.replace('');
    }
    replace(newMarkup) {
        this.#cm.dispatch({ changes: { from: 0, to: this.#cm.state.doc.length, insert: newMarkup } });
    }
    prepend(markup) {
        const changes = this.#cm.state.changes({
            from: 0,
            insert: this._fixMarkupBeforeInsert(markup),
        });
        this.#cm.dispatch({ changes, selection: this.#cm.state.selection.map(changes, 1) });
    }
    append(markup) {
        if (this.isEmpty()) {
            this.#cm.dispatch({ changes: { from: 0, insert: this._fixMarkupBeforeInsert(markup) } });
            this.moveCursor('end');
            return;
        }
        const { lineBreak } = this.#cm.state;
        let insert;
        const { doc, doc: { lines }, } = this.#cm.state;
        if (lines >= 2 && doc.lineAt(lines).length === 0) {
            if (doc.lineAt(lines - 1).length === 0)
                insert = markup;
            else
                insert = lineBreak + markup;
        }
        else {
            insert = lineBreak + lineBreak + markup;
        }
        this.#cm.dispatch({ changes: { from: doc.length, insert } });
    }
    moveCursor(position) {
        let pos;
        switch (position) {
            case 'start':
                pos = 0;
                break;
            case 'end':
                pos = this.#cm.state.doc.length;
                break;
            default:
                throw new Error('The "position" argument must be "start" or "end"');
        }
        this.#cm.dispatch({ selection: { anchor: pos } });
    }
    _fixMarkupBeforeInsert(markup) {
        if (markup.endsWith('\n\n'))
            return markup;
        if (markup.endsWith('\n'))
            return markup + '\n';
        return markup + '\n\n';
    }
}
exports.Editor = Editor;
//# sourceMappingURL=editor.js.map
